spf13--cobra/md_docs.md
bep 1d99c8ff6d genmarkdown: add optional frontmatter- and linkadjustment-funcs
The automatic Markdown generator works great!

But to use it to render the documentation in Hugo, we need front matter and slightly different links.

This commit adds optional callback funcs to add that.
2015-05-13 15:22:00 +02:00

2.2 KiB

Generating Markdown Docs For Your Own cobra.Command

Generate markdown docs for the entire command tree

This program can actually generate docs for the kubectl command in the kubernetes project

package main

import (
	"io/ioutil"
	"os"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
	"github.com/spf13/cobra"
)

func main() {
	kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
	cobra.GenMarkdownTree(kubectl, "./")
}

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")

Generate markdown docs for a single command

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 GenMarkdown instead of GenMarkdownTree

	out := new(bytes.Buffer)
	cobra.GenMarkdown(cmd, out)

This will write the markdown doc for ONLY "cmd" into the out, buffer.

Customize the output

Both GenMarkdown and GenMarkdownTree has alternate versions with callbacks to get some control of the output:

func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {
    //...
}
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {
    //...
}

The filePrepender will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with Hugo:

const fmTemplate = `---
date: %s
title: "%s"
slug: %s
url: %s
---
`

filePrepender := func(filename string) string {
	now := time.Now().Format(time.RFC3339)
	name := filepath.Base(filename)
	base := strings.TrimSuffix(name, path.Ext(name))
	url := "/commands/" + strings.ToLower(base) + "/"
	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
}

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

linkHandler := func(name string) string {
	base := strings.TrimSuffix(name, path.Ext(name))
	return "/commands/" + strings.ToLower(base) + "/"
}