Skip to content
Myr

Issue #195: Move doc generation into separate pkg

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Move man_docs and md_docs into new doc pkg * Replace *bytes.Buffer with io.Writer * Replace c == cmd.helpCommand with c.IsHelpCommand() * Remove redundant len(children) == 0 check in HasSeeAlso * Duplicate test setup for doc generation

authored by Frank Schroeder · committed by Steve Francia · parent f3aca0a · Browse files · 17 files+863 added−741 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+863 added−741 removed

  • other:+863 added−741 removed

17 files+863 added−741 removed

added:doc/cmd_test.go+145 added
1package doc23import (4 "bytes"5 "fmt"6 "runtime"7 "strings"8 "testing"910 "github.com/spf13/cobra"11)1213var flagb1, flagb2, flagb3, flagbr, flagbp bool14var flags1, flags2a, flags2b, flags3, outs string15var flagi1, flagi2, flagi3, flagir int1617const strtwoParentHelp = "help message for parent flag strtwo"18const strtwoChildHelp = "help message for child flag strtwo"1920var cmdEcho = &cobra.Command{21 Use: "echo [string to echo]",22 Aliases: []string{"say"},23 Short: "Echo anything to the screen",24 Long: `an utterly useless command for testing.`,25 Example: "Just run cobra-test echo",26}2728var cmdEchoSub = &cobra.Command{29 Use: "echosub [string to print]",30 Short: "second sub command for echo",31 Long: `an absolutely utterly useless command for testing gendocs!.`,32 Run: func(cmd *cobra.Command, args []string) {},33}3435var cmdDeprecated = &cobra.Command{36 Use: "deprecated [can't do anything here]",37 Short: "A command which is deprecated",38 Long: `an absolutely utterly useless command for testing deprecation!.`,39 Deprecated: "Please use echo instead",40}4142var cmdTimes = &cobra.Command{43 Use: "times [# times] [string to echo]",44 SuggestFor: []string{"counts"},45 Short: "Echo anything to the screen more times",46 Long: `a slightly useless command for testing.`,47 PersistentPreRun: func(cmd *cobra.Command, args []string) {},48 Run: func(cmd *cobra.Command, args []string) {},49}5051var cmdPrint = &cobra.Command{52 Use: "print [string to print]",53 Short: "Print anything to the screen",54 Long: `an absolutely utterly useless command for testing.`,55}5657var cmdRootNoRun = &cobra.Command{58 Use: "cobra-test",59 Short: "The root can run its own function",60 Long: "The root description for help",61}6263var cmdRootSameName = &cobra.Command{64 Use: "print",65 Short: "Root with the same name as a subcommand",66 Long: "The root description for help",67}6869var cmdRootWithRun = &cobra.Command{70 Use: "cobra-test",71 Short: "The root can run its own function",72 Long: "The root description for help",73}7475var cmdSubNoRun = &cobra.Command{76 Use: "subnorun",77 Short: "A subcommand without a Run function",78 Long: "A long output about a subcommand without a Run function",79}8081var cmdVersion1 = &cobra.Command{82 Use: "version",83 Short: "Print the version number",84 Long: `First version of the version command`,85}8687var cmdVersion2 = &cobra.Command{88 Use: "version",89 Short: "Print the version number",90 Long: `Second version of the version command`,91}9293func flagInit() {94 cmdEcho.ResetFlags()95 cmdPrint.ResetFlags()96 cmdTimes.ResetFlags()97 cmdRootNoRun.ResetFlags()98 cmdRootSameName.ResetFlags()99 cmdRootWithRun.ResetFlags()100 cmdSubNoRun.ResetFlags()101 cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)102 cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")103 cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")104 cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")105 cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")106 cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")107 cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)108 cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")109 cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")110 cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")111 cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")112 cmdVersion1.ResetFlags()113 cmdVersion2.ResetFlags()114}115116func initializeWithRootCmd() *cobra.Command {117 cmdRootWithRun.ResetCommands()118 flagInit()119 cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")120 cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")121 return cmdRootWithRun122}123124func checkStringContains(t *testing.T, found, expected string) {125 if !strings.Contains(found, expected) {126 logErr(t, found, expected)127 }128}129130func checkStringOmits(t *testing.T, found, expected string) {131 if strings.Contains(found, expected) {132 logErr(t, found, expected)133 }134}135136func logErr(t *testing.T, found, expected string) {137 out := new(bytes.Buffer)138139 _, _, line, ok := runtime.Caller(2)140 if ok {141 fmt.Fprintf(out, "Line: %d ", line)142 }143 fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)144 t.Errorf(out.String())145}
added:doc/man_docs_test.go+93 added
1package doc23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func translate(in string) string {15 return strings.Replace(in, "-", "\\-", -1)16}1718func TestGenManDoc(t *testing.T) {19 c := initializeWithRootCmd()20 // Need two commands to run the command alphabetical sort21 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)22 c.AddCommand(cmdPrint, cmdEcho)23 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)2425 out := new(bytes.Buffer)2627 header := &GenManHeader{28 Title: "Project",29 Section: "2",30 }31 // We generate on a subcommand so we have both subcommands and parents32 GenMan(cmdEcho, header, out)33 found := out.String()3435 // Make sure parent has - in CommandPath() in SEE ALSO:36 parentPath := cmdEcho.Parent().CommandPath()37 dashParentPath := strings.Replace(parentPath, " ", "-", -1)38 expected := translate(dashParentPath)39 expected = expected + "(" + header.Section + ")"40 checkStringContains(t, found, expected)4142 // Our description43 expected = translate(cmdEcho.Name())44 checkStringContains(t, found, expected)4546 // Better have our example47 expected = translate(cmdEcho.Name())48 checkStringContains(t, found, expected)4950 // A local flag51 expected = "boolone"52 checkStringContains(t, found, expected)5354 // persistent flag on parent55 expected = "rootflag"56 checkStringContains(t, found, expected)5758 // We better output info about our parent59 expected = translate(cmdRootWithRun.Name())60 checkStringContains(t, found, expected)6162 // And about subcommands63 expected = translate(cmdEchoSub.Name())64 checkStringContains(t, found, expected)6566 unexpected := translate(cmdDeprecated.Name())67 checkStringOmits(t, found, unexpected)6869 // auto generated70 expected = translate("Auto generated")71 checkStringContains(t, found, expected)72}7374func TestGenManNoGenTag(t *testing.T) {75 c := initializeWithRootCmd()76 // Need two commands to run the command alphabetical sort77 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)78 c.AddCommand(cmdPrint, cmdEcho)79 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)80 cmdEcho.DisableAutoGenTag = true81 out := new(bytes.Buffer)8283 header := &GenManHeader{84 Title: "Project",85 Section: "2",86 }87 // We generate on a subcommand so we have both subcommands and parents88 GenMan(cmdEcho, header, out)89 found := out.String()9091 unexpected := translate("#HISTORY")92 checkStringOmits(t, found, unexpected)93}
added:doc/man_docs.go+219 added
1// Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package doc1516import (17 "bytes"18 "fmt"19 "io"20 "os"21 "sort"22 "strings"23 "time"2425 mangen "github.com/cpuguy83/go-md2man/md2man"26 "github.com/spf13/cobra"27 "github.com/spf13/pflag"28)2930// GenManTree will generate a man page for this command and all decendants31// in the directory given. The header may be nil. This function may not work32// correctly if your command names have - in them. If you have `cmd` with two33// subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`34// it is undefined which help output will be in the file `cmd-sub-third.1`.35func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) {36 if header == nil {37 header = &GenManHeader{}38 }39 for _, c := range cmd.Commands() {40 if !c.IsAvailableCommand() || c.IsHelpCommand() {41 continue42 }43 GenManTree(c, header, dir)44 }45 out := new(bytes.Buffer)4647 needToResetTitle := header.Title == ""4849 GenMan(cmd, header, out)5051 if needToResetTitle {52 header.Title = ""53 }5455 filename := cmd.CommandPath()56 filename = dir + strings.Replace(filename, " ", "-", -1) + ".1"57 outFile, err := os.Create(filename)58 if err != nil {59 fmt.Println(err)60 os.Exit(1)61 }62 defer outFile.Close()63 _, err = outFile.Write(out.Bytes())64 if err != nil {65 fmt.Println(err)66 os.Exit(1)67 }68}6970// GenManHeader is a lot like the .TH header at the start of man pages. These71// include the title, section, date, source, and manual. We will use the72// current time if Date if unset and will use "Auto generated by spf13/cobra"73// if the Source is unset.74type GenManHeader struct {75 Title string76 Section string77 Date *time.Time78 date string79 Source string80 Manual string81}8283// GenMan will generate a man page for the given command in the out buffer.84// The header argument may be nil, however obviously out may not.85func GenMan(cmd *cobra.Command, header *GenManHeader, out io.Writer) {86 if header == nil {87 header = &GenManHeader{}88 }89 buf := genMan(cmd, header)90 final := mangen.Render(buf)91 out.Write(final)92}9394func fillHeader(header *GenManHeader, name string) {95 if header.Title == "" {96 header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))97 }98 if header.Section == "" {99 header.Section = "1"100 }101 if header.Date == nil {102 now := time.Now()103 header.Date = &now104 }105 header.date = (*header.Date).Format("Jan 2006")106 if header.Source == "" {107 header.Source = "Auto generated by spf13/cobra"108 }109}110111func manPreamble(out io.Writer, header *GenManHeader, name, short, long string) {112 dashName := strings.Replace(name, " ", "-", -1)113 fmt.Fprintf(out, `%% %s(%s)%s114%% %s115%% %s116# NAME117`, header.Title, header.Section, header.date, header.Source, header.Manual)118 fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)119 fmt.Fprintf(out, "# SYNOPSIS\n")120 fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)121 fmt.Fprintf(out, "# DESCRIPTION\n")122 fmt.Fprintf(out, "%s\n\n", long)123}124125func manPrintFlags(out io.Writer, flags *pflag.FlagSet) {126 flags.VisitAll(func(flag *pflag.Flag) {127 if len(flag.Deprecated) > 0 || flag.Hidden {128 return129 }130 format := ""131 if len(flag.Shorthand) > 0 {132 format = "**-%s**, **--%s**"133 } else {134 format = "%s**--%s**"135 }136 if len(flag.NoOptDefVal) > 0 {137 format = format + "["138 }139 if flag.Value.Type() == "string" {140 // put quotes on the value141 format = format + "=%q"142 } else {143 format = format + "=%s"144 }145 if len(flag.NoOptDefVal) > 0 {146 format = format + "]"147 }148 format = format + "\n\t%s\n\n"149 fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)150 })151}152153func manPrintOptions(out io.Writer, command *cobra.Command) {154 flags := command.NonInheritedFlags()155 if flags.HasFlags() {156 fmt.Fprintf(out, "# OPTIONS\n")157 manPrintFlags(out, flags)158 fmt.Fprintf(out, "\n")159 }160 flags = command.InheritedFlags()161 if flags.HasFlags() {162 fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")163 manPrintFlags(out, flags)164 fmt.Fprintf(out, "\n")165 }166}167168func genMan(cmd *cobra.Command, header *GenManHeader) []byte {169 // something like `rootcmd subcmd1 subcmd2`170 commandName := cmd.CommandPath()171 // something like `rootcmd-subcmd1-subcmd2`172 dashCommandName := strings.Replace(commandName, " ", "-", -1)173174 fillHeader(header, commandName)175176 buf := new(bytes.Buffer)177178 short := cmd.Short179 long := cmd.Long180 if len(long) == 0 {181 long = short182 }183184 manPreamble(buf, header, commandName, short, long)185 manPrintOptions(buf, cmd)186 if len(cmd.Example) > 0 {187 fmt.Fprintf(buf, "# EXAMPLE\n")188 fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)189 }190 if hasSeeAlso(cmd) {191 fmt.Fprintf(buf, "# SEE ALSO\n")192 if cmd.HasParent() {193 parentPath := cmd.Parent().CommandPath()194 dashParentPath := strings.Replace(parentPath, " ", "-", -1)195 fmt.Fprintf(buf, "**%s(%s)**", dashParentPath, header.Section)196 cmd.VisitParents(func(c *cobra.Command) {197 if c.DisableAutoGenTag {198 cmd.DisableAutoGenTag = c.DisableAutoGenTag199 }200 })201 }202 children := cmd.Commands()203 sort.Sort(byName(children))204 for i, c := range children {205 if !c.IsAvailableCommand() || c.IsHelpCommand() {206 continue207 }208 if cmd.HasParent() || i > 0 {209 fmt.Fprintf(buf, ", ")210 }211 fmt.Fprintf(buf, "**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)212 }213 fmt.Fprintf(buf, "\n")214 }215 if !cmd.DisableAutoGenTag {216 fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))217 }218 return buf.Bytes()219}
added:doc/man_docs.md+25 added
added:doc/man_examples_test.go+35 added
1package doc_test23import (4 "bytes"5 "fmt"67 "github.com/spf13/cobra"8 "github.com/spf13/cobra/doc"9)1011func ExampleCommand_GenManTree() {12 cmd := &cobra.Command{13 Use: "test",14 Short: "my test program",15 }16 header := &doc.GenManHeader{17 Title: "MINE",18 Section: "3",19 }20 doc.GenManTree(cmd, header, "/tmp")21}2223func ExampleCommand_GenMan() {24 cmd := &cobra.Command{25 Use: "test",26 Short: "my test program",27 }28 header := &doc.GenManHeader{29 Title: "MINE",30 Section: "3",31 }32 out := new(bytes.Buffer)33 doc.GenMan(cmd, header, out)34 fmt.Print(out.String())35}
added:doc/md_docs_test.go+84 added
1package doc23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func TestGenMdDoc(t *testing.T) {15 c := initializeWithRootCmd()16 // Need two commands to run the command alphabetical sort17 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)18 c.AddCommand(cmdPrint, cmdEcho)19 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)2021 out := new(bytes.Buffer)2223 // We generate on s subcommand so we have both subcommands and parents24 GenMarkdown(cmdEcho, out)25 found := out.String()2627 // Our description28 expected := cmdEcho.Long29 if !strings.Contains(found, expected) {30 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)31 }3233 // Better have our example34 expected = cmdEcho.Example35 if !strings.Contains(found, expected) {36 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)37 }3839 // A local flag40 expected = "boolone"41 if !strings.Contains(found, expected) {42 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)43 }4445 // persistent flag on parent46 expected = "rootflag"47 if !strings.Contains(found, expected) {48 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)49 }5051 // We better output info about our parent52 expected = cmdRootWithRun.Short53 if !strings.Contains(found, expected) {54 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)55 }5657 // And about subcommands58 expected = cmdEchoSub.Short59 if !strings.Contains(found, expected) {60 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)61 }6263 unexpected := cmdDeprecated.Short64 if strings.Contains(found, unexpected) {65 t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)66 }67}6869func TestGenMdNoTag(t *testing.T) {70 c := initializeWithRootCmd()71 // Need two commands to run the command alphabetical sort72 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)73 c.AddCommand(cmdPrint, cmdEcho)74 c.DisableAutoGenTag = true75 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)76 out := new(bytes.Buffer)7778 GenMarkdown(c, out)79 found := out.String()8081 unexpected := "Auto generated"82 checkStringOmits(t, found, unexpected)8384}
added:doc/md_docs.go+143 added
1//Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package doc1516import (17 "bytes"18 "fmt"19 "io"20 "os"21 "sort"22 "strings"23 "time"2425 "github.com/spf13/cobra"26)2728func printOptions(out io.Writer, cmd *cobra.Command, name string) {29 flags := cmd.NonInheritedFlags()30 flags.SetOutput(out)31 if flags.HasFlags() {32 fmt.Fprintf(out, "### Options\n\n```\n")33 flags.PrintDefaults()34 fmt.Fprintf(out, "```\n\n")35 }3637 parentFlags := cmd.InheritedFlags()38 parentFlags.SetOutput(out)39 if parentFlags.HasFlags() {40 fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n")41 parentFlags.PrintDefaults()42 fmt.Fprintf(out, "```\n\n")43 }44}4546func GenMarkdown(cmd *cobra.Command, out io.Writer) {47 GenMarkdownCustom(cmd, out, func(s string) string { return s })48}4950func GenMarkdownCustom(cmd *cobra.Command, out io.Writer, linkHandler func(string) string) {51 name := cmd.CommandPath()5253 short := cmd.Short54 long := cmd.Long55 if len(long) == 0 {56 long = short57 }5859 fmt.Fprintf(out, "## %s\n\n", name)60 fmt.Fprintf(out, "%s\n\n", short)61 fmt.Fprintf(out, "### Synopsis\n\n")62 fmt.Fprintf(out, "\n%s\n\n", long)6364 if cmd.Runnable() {65 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())66 }6768 if len(cmd.Example) > 0 {69 fmt.Fprintf(out, "### Examples\n\n")70 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)71 }7273 printOptions(out, cmd, name)74 if hasSeeAlso(cmd) {75 fmt.Fprintf(out, "### SEE ALSO\n")76 if cmd.HasParent() {77 parent := cmd.Parent()78 pname := parent.CommandPath()79 link := pname + ".md"80 link = strings.Replace(link, " ", "_", -1)81 fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)82 cmd.VisitParents(func(c *cobra.Command) {83 if c.DisableAutoGenTag {84 cmd.DisableAutoGenTag = c.DisableAutoGenTag85 }86 })87 }8889 children := cmd.Commands()90 sort.Sort(byName(children))9192 for _, child := range children {93 if !child.IsAvailableCommand() || child.IsHelpCommand() {94 continue95 }96 cname := name + " " + child.Name()97 link := cname + ".md"98 link = strings.Replace(link, " ", "_", -1)99 fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)100 }101 fmt.Fprintf(out, "\n")102 }103 if !cmd.DisableAutoGenTag {104 fmt.Fprintf(out, "###### Auto generated by spf13/cobra on %s\n", time.Now().Format("2-Jan-2006"))105 }106}107108func GenMarkdownTree(cmd *cobra.Command, dir string) {109 identity := func(s string) string { return s }110 emptyStr := func(s string) string { return "" }111 GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)112}113114func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {115 for _, c := range cmd.Commands() {116 if !c.IsAvailableCommand() || c.IsHelpCommand() {117 continue118 }119 GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler)120 }121 out := new(bytes.Buffer)122123 GenMarkdownCustom(cmd, out, linkHandler)124125 filename := cmd.CommandPath()126 filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"127 outFile, err := os.Create(filename)128 if err != nil {129 fmt.Println(err)130 os.Exit(1)131 }132 defer outFile.Close()133 _, err = outFile.WriteString(filePrepender(filename))134 if err != nil {135 fmt.Println(err)136 os.Exit(1)137 }138 _, err = outFile.Write(out.Bytes())139 if err != nil {140 fmt.Println(err)141 os.Exit(1)142 }143}
added:doc/md_docs.md+81 added
1# Generating Markdown Docs For Your Own cobra.Command23## Generate markdown docs for the entire command tree45This program can actually generate docs for the kubectl command in the kubernetes project67```go8package main910import (11 "io/ioutil"12 "os"1314 "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"15 "github.com/spf13/cobra/cobra"16)1718func main() {19 kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)20 doc.GenMarkdownTree(kubectl, "./")21}22```2324This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")2526## Generate markdown docs for a single command2728You 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`2930```go31 out := new(bytes.Buffer)32 doc.GenMarkdown(cmd, out)33```3435This will write the markdown doc for ONLY "cmd" into the out, buffer.3637## Customize the output3839Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:4041```go42func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {43 //...44}45```4647```go48func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {49 //...50}51```5253The `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](http://gohugo.io/):5455```go56const fmTemplate = `---57date: %s58title: "%s"59slug: %s60url: %s61---62`6364filePrepender := func(filename string) string {65 now := time.Now().Format(time.RFC3339)66 name := filepath.Base(filename)67 base := strings.TrimSuffix(name, path.Ext(name))68 url := "/commands/" + strings.ToLower(base) + "/"69 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)70}71```7273The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:7475```go76linkHandler := func(name string) string {77 base := strings.TrimSuffix(name, path.Ext(name))78 return "/commands/" + strings.ToLower(base) + "/"79}80```81
added:doc/util.go+38 added
1// Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package doc1516import "github.com/spf13/cobra"1718// Test to see if we have a reason to print See Also information in docs19// Basically this is a test for a parent commend or a subcommand which is20// both not deprecated and not the autogenerated help command.21func hasSeeAlso(cmd *cobra.Command) bool {22 if cmd.HasParent() {23 return true24 }25 for _, c := range cmd.Commands() {26 if !c.IsAvailableCommand() || c.IsHelpCommand() {27 continue28 }29 return true30 }31 return false32}3334type byName []*cobra.Command3536func (s byName) Len() int { return len(s) }37func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }38func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
deleted:doc_util.go-34 removed
1// Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516// Test to see if we have a reason to print See Also information in docs17// Basically this is a test for a parent commend or a subcommand which is18// both not deprecated and not the autogenerated help command.19func (cmd *Command) hasSeeAlso() bool {20 if cmd.HasParent() {21 return true22 }23 children := cmd.Commands()24 if len(children) == 0 {25 return false26 }27 for _, c := range children {28 if !c.IsAvailableCommand() || c == cmd.helpCommand {29 continue30 }31 return true32 }33 return false34}
deleted:examples_test.go-34 removed
1package cobra_test23import (4 "bytes"5 "fmt"67 "github.com/spf13/cobra"8)910func ExampleCommand_GenManTree() {11 cmd := &cobra.Command{12 Use: "test",13 Short: "my test program",14 }15 header := &cobra.GenManHeader{16 Title: "MINE",17 Section: "3",18 }19 cmd.GenManTree(header, "/tmp")20}2122func ExampleCommand_GenMan() {23 cmd := &cobra.Command{24 Use: "test",25 Short: "my test program",26 }27 header := &cobra.GenManHeader{28 Title: "MINE",29 Section: "3",30 }31 out := new(bytes.Buffer)32 cmd.GenMan(header, out)33 fmt.Print(out.String())34}
deleted:man_docs_test.go-94 removed
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func translate(in string) string {15 return strings.Replace(in, "-", "\\-", -1)16}1718func TestGenManDoc(t *testing.T) {19 c := initializeWithRootCmd()20 // Need two commands to run the command alphabetical sort21 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)22 c.AddCommand(cmdPrint, cmdEcho)23 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)2425 out := new(bytes.Buffer)2627 header := &GenManHeader{28 Title: "Project",29 Section: "2",30 }31 // We generate on a subcommand so we have both subcommands and parents32 cmdEcho.GenMan(header, out)33 found := out.String()3435 // Make sure parent has - in CommandPath() in SEE ALSO:36 parentPath := cmdEcho.Parent().CommandPath()37 dashParentPath := strings.Replace(parentPath, " ", "-", -1)38 expected := translate(dashParentPath)39 expected = expected + "(" + header.Section + ")"40 checkStringContains(t, found, expected)4142 // Our description43 expected = translate(cmdEcho.Name())44 checkStringContains(t, found, expected)4546 // Better have our example47 expected = translate(cmdEcho.Name())48 checkStringContains(t, found, expected)4950 // A local flag51 expected = "boolone"52 checkStringContains(t, found, expected)5354 // persistent flag on parent55 expected = "rootflag"56 checkStringContains(t, found, expected)5758 // We better output info about our parent59 expected = translate(cmdRootWithRun.Name())60 checkStringContains(t, found, expected)6162 // And about subcommands63 expected = translate(cmdEchoSub.Name())64 checkStringContains(t, found, expected)6566 unexpected := translate(cmdDeprecated.Name())67 checkStringOmits(t, found, unexpected)6869 // auto generated70 expected = translate("Auto generated")71 checkStringContains(t, found, expected)72}7374func TestGenManNoGenTag(t *testing.T) {7576 c := initializeWithRootCmd()77 // Need two commands to run the command alphabetical sort78 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)79 c.AddCommand(cmdPrint, cmdEcho)80 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)81 cmdEcho.DisableAutoGenTag = true82 out := new(bytes.Buffer)8384 header := &GenManHeader{85 Title: "Project",86 Section: "2",87 }88 // We generate on a subcommand so we have both subcommands and parents89 cmdEcho.GenMan(header, out)90 found := out.String()9192 unexpected := translate("#HISTORY")93 checkStringOmits(t, found, unexpected)94}
deleted:man_docs.go-227 removed
1// Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516import (17 "bytes"18 "fmt"19 "os"20 "sort"21 "strings"22 "time"2324 mangen "github.com/cpuguy83/go-md2man/md2man"25 "github.com/spf13/pflag"26)2728// GenManTree will call cmd.GenManTree(header, dir)29func GenManTree(cmd *Command, header *GenManHeader, dir string) {30 cmd.GenManTree(header, dir)31}3233// GenManTree will generate a man page for this command and all decendants34// in the directory given. The header may be nil. This function may not work35// correctly if your command names have - in them. If you have `cmd` with two36// subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`37// it is undefined which help output will be in the file `cmd-sub-third.1`.38func (cmd *Command) GenManTree(header *GenManHeader, dir string) {39 if header == nil {40 header = &GenManHeader{}41 }42 for _, c := range cmd.Commands() {43 if !c.IsAvailableCommand() || c == cmd.helpCommand {44 continue45 }46 GenManTree(c, header, dir)47 }48 out := new(bytes.Buffer)4950 needToResetTitle := header.Title == ""5152 cmd.GenMan(header, out)5354 if needToResetTitle {55 header.Title = ""56 }5758 filename := cmd.CommandPath()59 filename = dir + strings.Replace(filename, " ", "-", -1) + ".1"60 outFile, err := os.Create(filename)61 if err != nil {62 fmt.Println(err)63 os.Exit(1)64 }65 defer outFile.Close()66 _, err = outFile.Write(out.Bytes())67 if err != nil {68 fmt.Println(err)69 os.Exit(1)70 }71}7273// GenManHeader is a lot like the .TH header at the start of man pages. These74// include the title, section, date, source, and manual. We will use the75// current time if Date if unset and will use "Auto generated by spf13/cobra"76// if the Source is unset.77type GenManHeader struct {78 Title string79 Section string80 Date *time.Time81 date string82 Source string83 Manual string84}8586// GenMan will call cmd.GenMan(header, out)87func GenMan(cmd *Command, header *GenManHeader, out *bytes.Buffer) {88 cmd.GenMan(header, out)89}9091// GenMan will generate a man page for the given command in the out buffer.92// The header argument may be nil, however obviously out may not.93func (cmd *Command) GenMan(header *GenManHeader, out *bytes.Buffer) {94 if header == nil {95 header = &GenManHeader{}96 }97 buf := genMarkdown(cmd, header)98 final := mangen.Render(buf)99 out.Write(final)100}101102func fillHeader(header *GenManHeader, name string) {103 if header.Title == "" {104 header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))105 }106 if header.Section == "" {107 header.Section = "1"108 }109 if header.Date == nil {110 now := time.Now()111 header.Date = &now112 }113 header.date = (*header.Date).Format("Jan 2006")114 if header.Source == "" {115 header.Source = "Auto generated by spf13/cobra"116 }117}118119func manPreamble(out *bytes.Buffer, header *GenManHeader, name, short, long string) {120 dashName := strings.Replace(name, " ", "-", -1)121 fmt.Fprintf(out, `%% %s(%s)%s122%% %s123%% %s124# NAME125`, header.Title, header.Section, header.date, header.Source, header.Manual)126 fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)127 fmt.Fprintf(out, "# SYNOPSIS\n")128 fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)129 fmt.Fprintf(out, "# DESCRIPTION\n")130 fmt.Fprintf(out, "%s\n\n", long)131}132133func manPrintFlags(out *bytes.Buffer, flags *pflag.FlagSet) {134 flags.VisitAll(func(flag *pflag.Flag) {135 if len(flag.Deprecated) > 0 || flag.Hidden {136 return137 }138 format := ""139 if len(flag.Shorthand) > 0 {140 format = "**-%s**, **--%s**"141 } else {142 format = "%s**--%s**"143 }144 if len(flag.NoOptDefVal) > 0 {145 format = format + "["146 }147 if flag.Value.Type() == "string" {148 // put quotes on the value149 format = format + "=%q"150 } else {151 format = format + "=%s"152 }153 if len(flag.NoOptDefVal) > 0 {154 format = format + "]"155 }156 format = format + "\n\t%s\n\n"157 fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)158 })159}160161func manPrintOptions(out *bytes.Buffer, command *Command) {162 flags := command.NonInheritedFlags()163 if flags.HasFlags() {164 fmt.Fprintf(out, "# OPTIONS\n")165 manPrintFlags(out, flags)166 fmt.Fprintf(out, "\n")167 }168 flags = command.InheritedFlags()169 if flags.HasFlags() {170 fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")171 manPrintFlags(out, flags)172 fmt.Fprintf(out, "\n")173 }174}175176func genMarkdown(cmd *Command, header *GenManHeader) []byte {177 // something like `rootcmd subcmd1 subcmd2`178 commandName := cmd.CommandPath()179 // something like `rootcmd-subcmd1-subcmd2`180 dashCommandName := strings.Replace(commandName, " ", "-", -1)181182 fillHeader(header, commandName)183184 buf := new(bytes.Buffer)185186 short := cmd.Short187 long := cmd.Long188 if len(long) == 0 {189 long = short190 }191192 manPreamble(buf, header, commandName, short, long)193 manPrintOptions(buf, cmd)194 if len(cmd.Example) > 0 {195 fmt.Fprintf(buf, "# EXAMPLE\n")196 fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)197 }198 if cmd.hasSeeAlso() {199 fmt.Fprintf(buf, "# SEE ALSO\n")200 if cmd.HasParent() {201 parentPath := cmd.Parent().CommandPath()202 dashParentPath := strings.Replace(parentPath, " ", "-", -1)203 fmt.Fprintf(buf, "**%s(%s)**", dashParentPath, header.Section)204 cmd.VisitParents(func(c *Command) {205 if c.DisableAutoGenTag {206 cmd.DisableAutoGenTag = c.DisableAutoGenTag207 }208 })209 }210 children := cmd.Commands()211 sort.Sort(byName(children))212 for i, c := range children {213 if !c.IsAvailableCommand() || c == cmd.helpCommand {214 continue215 }216 if cmd.HasParent() || i > 0 {217 fmt.Fprintf(buf, ", ")218 }219 fmt.Fprintf(buf, "**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)220 }221 fmt.Fprintf(buf, "\n")222 }223 if !cmd.DisableAutoGenTag {224 fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))225 }226 return buf.Bytes()227}
deleted:man_docs.md-25 removed
deleted:md_docs_test.go-84 removed
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func TestGenMdDoc(t *testing.T) {15 c := initializeWithRootCmd()16 // Need two commands to run the command alphabetical sort17 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)18 c.AddCommand(cmdPrint, cmdEcho)19 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)2021 out := new(bytes.Buffer)2223 // We generate on s subcommand so we have both subcommands and parents24 GenMarkdown(cmdEcho, out)25 found := out.String()2627 // Our description28 expected := cmdEcho.Long29 if !strings.Contains(found, expected) {30 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)31 }3233 // Better have our example34 expected = cmdEcho.Example35 if !strings.Contains(found, expected) {36 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)37 }3839 // A local flag40 expected = "boolone"41 if !strings.Contains(found, expected) {42 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)43 }4445 // persistent flag on parent46 expected = "rootflag"47 if !strings.Contains(found, expected) {48 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)49 }5051 // We better output info about our parent52 expected = cmdRootWithRun.Short53 if !strings.Contains(found, expected) {54 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)55 }5657 // And about subcommands58 expected = cmdEchoSub.Short59 if !strings.Contains(found, expected) {60 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)61 }6263 unexpected := cmdDeprecated.Short64 if strings.Contains(found, unexpected) {65 t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)66 }67}6869func TestGenMdNoTag(t *testing.T) {70 c := initializeWithRootCmd()71 // Need two commands to run the command alphabetical sort72 cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)73 c.AddCommand(cmdPrint, cmdEcho)74 c.DisableAutoGenTag = true75 cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)76 out := new(bytes.Buffer)7778 GenMarkdown(c, out)79 found := out.String()8081 unexpected := "Auto generated"82 checkStringOmits(t, found, unexpected)8384}
deleted:md_docs.go-162 removed
1//Copyright 2015 Red Hat Inc. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516import (17 "bytes"18 "fmt"19 "os"20 "sort"21 "strings"22 "time"23)2425func printOptions(out *bytes.Buffer, cmd *Command, name string) {26 flags := cmd.NonInheritedFlags()27 flags.SetOutput(out)28 if flags.HasFlags() {29 fmt.Fprintf(out, "### Options\n\n```\n")30 flags.PrintDefaults()31 fmt.Fprintf(out, "```\n\n")32 }3334 parentFlags := cmd.InheritedFlags()35 parentFlags.SetOutput(out)36 if parentFlags.HasFlags() {37 fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n")38 parentFlags.PrintDefaults()39 fmt.Fprintf(out, "```\n\n")40 }41}4243type byName []*Command4445func (s byName) Len() int { return len(s) }46func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }47func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }4849func GenMarkdown(cmd *Command, out *bytes.Buffer) {50 cmd.GenMarkdown(out)51}5253func (cmd *Command) GenMarkdown(out *bytes.Buffer) {54 cmd.GenMarkdownCustom(out, func(s string) string { return s })55}5657func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {58 cmd.GenMarkdownCustom(out, linkHandler)59}6061func (cmd *Command) GenMarkdownCustom(out *bytes.Buffer, linkHandler func(string) string) {62 name := cmd.CommandPath()6364 short := cmd.Short65 long := cmd.Long66 if len(long) == 0 {67 long = short68 }6970 fmt.Fprintf(out, "## %s\n\n", name)71 fmt.Fprintf(out, "%s\n\n", short)72 fmt.Fprintf(out, "### Synopsis\n\n")73 fmt.Fprintf(out, "\n%s\n\n", long)7475 if cmd.Runnable() {76 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())77 }7879 if len(cmd.Example) > 0 {80 fmt.Fprintf(out, "### Examples\n\n")81 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)82 }8384 printOptions(out, cmd, name)85 if cmd.hasSeeAlso() {86 fmt.Fprintf(out, "### SEE ALSO\n")87 if cmd.HasParent() {88 parent := cmd.Parent()89 pname := parent.CommandPath()90 link := pname + ".md"91 link = strings.Replace(link, " ", "_", -1)92 fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)93 cmd.VisitParents(func(c *Command) {94 if c.DisableAutoGenTag {95 cmd.DisableAutoGenTag = c.DisableAutoGenTag96 }97 })98 }99100 children := cmd.Commands()101 sort.Sort(byName(children))102103 for _, child := range children {104 if !child.IsAvailableCommand() || child == cmd.helpCommand {105 continue106 }107 cname := name + " " + child.Name()108 link := cname + ".md"109 link = strings.Replace(link, " ", "_", -1)110 fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)111 }112 fmt.Fprintf(out, "\n")113 }114 if !cmd.DisableAutoGenTag {115 fmt.Fprintf(out, "###### Auto generated by spf13/cobra on %s\n", time.Now().Format("2-Jan-2006"))116 }117}118119func GenMarkdownTree(cmd *Command, dir string) {120 cmd.GenMarkdownTree(dir)121}122123func (cmd *Command) GenMarkdownTree(dir string) {124 identity := func(s string) string { return s }125 emptyStr := func(s string) string { return "" }126 cmd.GenMarkdownTreeCustom(dir, emptyStr, identity)127}128129func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {130 cmd.GenMarkdownTreeCustom(dir, filePrepender, linkHandler)131}132133func (cmd *Command) GenMarkdownTreeCustom(dir string, filePrepender func(string) string, linkHandler func(string) string) {134 for _, c := range cmd.Commands() {135 if !c.IsAvailableCommand() || c == cmd.helpCommand {136 continue137 }138 c.GenMarkdownTreeCustom(dir, filePrepender, linkHandler)139 }140 out := new(bytes.Buffer)141142 cmd.GenMarkdownCustom(out, linkHandler)143144 filename := cmd.CommandPath()145 filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"146 outFile, err := os.Create(filename)147 if err != nil {148 fmt.Println(err)149 os.Exit(1)150 }151 defer outFile.Close()152 _, err = outFile.WriteString(filePrepender(filename))153 if err != nil {154 fmt.Println(err)155 os.Exit(1)156 }157 _, err = outFile.Write(out.Bytes())158 if err != nil {159 fmt.Println(err)160 os.Exit(1)161 }162}
deleted:md_docs.md-81 removed
1# Generating Markdown Docs For Your Own cobra.Command23## Generate markdown docs for the entire command tree45This program can actually generate docs for the kubectl command in the kubernetes project67```go8package main910import (11 "io/ioutil"12 "os"1314 "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"15 "github.com/spf13/cobra"16)1718func main() {19 kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)20 cobra.GenMarkdownTree(kubectl, "./")21}22```2324This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")2526## Generate markdown docs for a single command2728You 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`2930```go31 out := new(bytes.Buffer)32 cobra.GenMarkdown(cmd, out)33```3435This will write the markdown doc for ONLY "cmd" into the out, buffer.3637## Customize the output3839Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:4041```go42func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {43 //...44}45```4647```go48func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {49 //...50}51```5253The `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](http://gohugo.io/):5455```go56const fmTemplate = `---57date: %s58title: "%s"59slug: %s60url: %s61---62`6364filePrepender := func(filename string) string {65 now := time.Now().Format(time.RFC3339)66 name := filepath.Base(filename)67 base := strings.TrimSuffix(name, path.Ext(name))68 url := "/commands/" + strings.ToLower(base) + "/"69 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)70}71```7273The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:7475```go76linkHandler := func(name string) string {77 base := strings.TrimSuffix(name, path.Ext(name))78 return "/commands/" + strings.ToLower(base) + "/"79}80```81