1 # Generating ReStructured Text Docs For Your Own cobra.Command
3 Generating ReST pages 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.GenReSTTree(cmd, "/tmp")
27 That will get you a ReST document `/tmp/test.rst`
29 ## Generate ReST 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.GenReSTTree(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 ReST 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 `GenReST` instead of `GenReSTTree`
63 out := new(bytes.Buffer)
64 err := doc.GenReST(cmd, out)
70 This will write the ReST doc for ONLY "cmd" into the out, buffer.
72 ## Customize the output
74 Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:
77 func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
83 func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
88 The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
91 const fmTemplate = `---
98 filePrepender := func(filename string) string {
99 now := time.Now().Format(time.RFC3339)
100 name := filepath.Base(filename)
101 base := strings.TrimSuffix(name, path.Ext(name))
102 url := "/commands/" + strings.ToLower(base) + "/"
103 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
107 The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:
110 // Sphinx cross-referencing format
111 linkHandler := func(name, ref string) string {
112 return fmt.Sprintf(":ref:`%s <%s>`", name, ref)