1 # Generating Yaml Docs For Your Own cobra.Command
3 Generating yaml files from a cobra command is incredibly easy. An example is as follows:
11 "github.com/spf13/cobra"
12 "github.com/spf13/cobra/doc"
16 cmd := &cobra.Command{
18 Short: "my test program",
20 err := doc.GenYamlTree(cmd, "/tmp")
27 That will get you a Yaml document `/tmp/test.yaml`
29 ## Generate yaml docs for the entire command tree
31 This program can actually generate docs for the kubectl command in the kubernetes project
41 "k8s.io/kubernetes/pkg/kubectl/cmd"
42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
44 "github.com/spf13/cobra/doc"
48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
49 err := doc.GenYamlTree(kubectl, "./")
56 This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
58 ## Generate yaml docs for a single command
60 You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`
63 out := new(bytes.Buffer)
67 This will write the yaml doc for ONLY "cmd" into the out, buffer.
69 ## Customize the output
71 Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:
74 func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
80 func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
85 The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
88 const fmTemplate = `---
96 filePrepender := func(filename string) string {
97 now := time.Now().Format(time.RFC3339)
98 name := filepath.Base(filename)
99 base := strings.TrimSuffix(name, path.Ext(name))
100 url := "/commands/" + strings.ToLower(base) + "/"
101 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
105 The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
108 linkHandler := func(name string) string {
109 base := strings.TrimSuffix(name, path.Ext(name))
110 return "/commands/" + strings.ToLower(base) + "/"