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
Provenance
- Commit
b3f29e9- Tree
0df71e5- Author
Frank Schroeder <frank.schroeder@gmail.com>- Committer
Steve Francia <steve.francia@gmail.com>- Parent
f3aca0a
17 files changed+863 added−741 removed
added:doc/cmd_test.go+145 added
1+package doc2+3+import (4+ "bytes"5+ "fmt"6+ "runtime"7+ "strings"8+ "testing"9+10+ "github.com/spf13/cobra"11+)12+13+var flagb1, flagb2, flagb3, flagbr, flagbp bool14+var flags1, flags2a, flags2b, flags3, outs string15+var flagi1, flagi2, flagi3, flagir int16+17+const strtwoParentHelp = "help message for parent flag strtwo"18+const strtwoChildHelp = "help message for child flag strtwo"19+20+var 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+}27+28+var 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+}34+35+var 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+}41+42+var 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+}50+51+var 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+}56+57+var cmdRootNoRun = &cobra.Command{58+ Use: "cobra-test",59+ Short: "The root can run its own function",60+ Long: "The root description for help",61+}62+63+var cmdRootSameName = &cobra.Command{64+ Use: "print",65+ Short: "Root with the same name as a subcommand",66+ Long: "The root description for help",67+}68+69+var cmdRootWithRun = &cobra.Command{70+ Use: "cobra-test",71+ Short: "The root can run its own function",72+ Long: "The root description for help",73+}74+75+var 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+}80+81+var cmdVersion1 = &cobra.Command{82+ Use: "version",83+ Short: "Print the version number",84+ Long: `First version of the version command`,85+}86+87+var cmdVersion2 = &cobra.Command{88+ Use: "version",89+ Short: "Print the version number",90+ Long: `Second version of the version command`,91+}92+93+func 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+}115+116+func 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+}123+124+func checkStringContains(t *testing.T, found, expected string) {125+ if !strings.Contains(found, expected) {126+ logErr(t, found, expected)127+ }128+}129+130+func checkStringOmits(t *testing.T, found, expected string) {131+ if strings.Contains(found, expected) {132+ logErr(t, found, expected)133+ }134+}135+136+func logErr(t *testing.T, found, expected string) {137+ out := new(bytes.Buffer)138+139+ _, _, 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
1+package doc2+3+import (4+ "bytes"5+ "fmt"6+ "os"7+ "strings"8+ "testing"9+)10+11+var _ = fmt.Println12+var _ = os.Stderr13+14+func translate(in string) string {15+ return strings.Replace(in, "-", "\\-", -1)16+}17+18+func 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)24+25+ out := new(bytes.Buffer)26+27+ 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()34+35+ // 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)41+42+ // Our description43+ expected = translate(cmdEcho.Name())44+ checkStringContains(t, found, expected)45+46+ // Better have our example47+ expected = translate(cmdEcho.Name())48+ checkStringContains(t, found, expected)49+50+ // A local flag51+ expected = "boolone"52+ checkStringContains(t, found, expected)53+54+ // persistent flag on parent55+ expected = "rootflag"56+ checkStringContains(t, found, expected)57+58+ // We better output info about our parent59+ expected = translate(cmdRootWithRun.Name())60+ checkStringContains(t, found, expected)61+62+ // And about subcommands63+ expected = translate(cmdEchoSub.Name())64+ checkStringContains(t, found, expected)65+66+ unexpected := translate(cmdDeprecated.Name())67+ checkStringOmits(t, found, unexpected)68+69+ // auto generated70+ expected = translate("Auto generated")71+ checkStringContains(t, found, expected)72+}73+74+func 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)82+83+ 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()90+91+ 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.13+14+package doc15+16+import (17+ "bytes"18+ "fmt"19+ "io"20+ "os"21+ "sort"22+ "strings"23+ "time"24+25+ mangen "github.com/cpuguy83/go-md2man/md2man"26+ "github.com/spf13/cobra"27+ "github.com/spf13/pflag"28+)29+30+// 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`.35+func 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)46+47+ needToResetTitle := header.Title == ""48+49+ GenMan(cmd, header, out)50+51+ if needToResetTitle {52+ header.Title = ""53+ }54+55+ 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+}69+70+// 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.74+type GenManHeader struct {75+ Title string76+ Section string77+ Date *time.Time78+ date string79+ Source string80+ Manual string81+}82+83+// 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.85+func 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+}93+94+func 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+}110+111+func 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+}124+125+func 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+}152+153+func 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+}167+168+func 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)173+174+ fillHeader(header, commandName)175+176+ buf := new(bytes.Buffer)177+178+ short := cmd.Short179+ long := cmd.Long180+ if len(long) == 0 {181+ long = short182+ }183+184+ 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
12345678910111213141516171819202122232425# Generating Man Pages For Your Own cobra.Command
Generating man pages from a cobra command is incredibly easy. An example is as follows:
```gopackage main
import ( "github.com/spf13/cobra")
func main() { cmd := &cobra.Command{ Use: "test", Short: "my test program", } header := &cobra.GenManHeader{ Title: "MINE", Section: "3", } cmd.GenManTree(header, "/tmp")}```
That will get you a man page `/tmp/test.1`added:doc/man_examples_test.go+35 added
1+package doc_test2+3+import (4+ "bytes"5+ "fmt"6+7+ "github.com/spf13/cobra"8+ "github.com/spf13/cobra/doc"9+)10+11+func 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+}22+23+func 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
1+package doc2+3+import (4+ "bytes"5+ "fmt"6+ "os"7+ "strings"8+ "testing"9+)10+11+var _ = fmt.Println12+var _ = os.Stderr13+14+func 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)20+21+ out := new(bytes.Buffer)22+23+ // We generate on s subcommand so we have both subcommands and parents24+ GenMarkdown(cmdEcho, out)25+ found := out.String()26+27+ // 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+ }32+33+ // 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+ }38+39+ // 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+ }44+45+ // 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+ }50+51+ // 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+ }56+57+ // 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+ }62+63+ unexpected := cmdDeprecated.Short64+ if strings.Contains(found, unexpected) {65+ t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)66+ }67+}68+69+func 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)77+78+ GenMarkdown(c, out)79+ found := out.String()80+81+ unexpected := "Auto generated"82+ checkStringOmits(t, found, unexpected)83+84+}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.13+14+package doc15+16+import (17+ "bytes"18+ "fmt"19+ "io"20+ "os"21+ "sort"22+ "strings"23+ "time"24+25+ "github.com/spf13/cobra"26+)27+28+func 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+ }36+37+ 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+}45+46+func GenMarkdown(cmd *cobra.Command, out io.Writer) {47+ GenMarkdownCustom(cmd, out, func(s string) string { return s })48+}49+50+func GenMarkdownCustom(cmd *cobra.Command, out io.Writer, linkHandler func(string) string) {51+ name := cmd.CommandPath()52+53+ short := cmd.Short54+ long := cmd.Long55+ if len(long) == 0 {56+ long = short57+ }58+59+ 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)63+64+ if cmd.Runnable() {65+ fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())66+ }67+68+ if len(cmd.Example) > 0 {69+ fmt.Fprintf(out, "### Examples\n\n")70+ fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)71+ }72+73+ 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+ }88+89+ children := cmd.Commands()90+ sort.Sort(byName(children))91+92+ 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+}107+108+func 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+}113+114+func 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)122+123+ GenMarkdownCustom(cmd, out, linkHandler)124+125+ 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.Command2+3+## Generate markdown docs for the entire command tree4+5+This program can actually generate docs for the kubectl command in the kubernetes project6+7+```go8+package main9+10+import (11+ "io/ioutil"12+ "os"13+14+ "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"15+ "github.com/spf13/cobra/cobra"16+)17+18+func main() {19+ kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)20+ doc.GenMarkdownTree(kubectl, "./")21+}22+```23+24+This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")25+26+## Generate markdown docs for a single command27+28+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`29+30+```go31+ out := new(bytes.Buffer)32+ doc.GenMarkdown(cmd, out)33+```34+35+This will write the markdown doc for ONLY "cmd" into the out, buffer.36+37+## Customize the output38+39+Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:40+41+```go42+func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {43+ //...44+}45+```46+47+```go48+func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {49+ //...50+}51+```52+53+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](http://gohugo.io/):54+55+```go56+const fmTemplate = `---57+date: %s58+title: "%s"59+slug: %s60+url: %s61+---62+`63+64+filePrepender := 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+```72+73+The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:74+75+```go76+linkHandler := 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.13+14+package doc15+16+import "github.com/spf13/cobra"17+18+// 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.21+func 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+}33+34+type byName []*cobra.Command35+36+func (s byName) Len() int { return len(s) }37+func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }38+func (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.13-14-package cobra15-16-// 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.19-func (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
1-package cobra_test2-3-import (4- "bytes"5- "fmt"6-7- "github.com/spf13/cobra"8-)9-10-func 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-}21-22-func 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
1-package cobra2-3-import (4- "bytes"5- "fmt"6- "os"7- "strings"8- "testing"9-)10-11-var _ = fmt.Println12-var _ = os.Stderr13-14-func translate(in string) string {15- return strings.Replace(in, "-", "\\-", -1)16-}17-18-func 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)24-25- out := new(bytes.Buffer)26-27- 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()34-35- // 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)41-42- // Our description43- expected = translate(cmdEcho.Name())44- checkStringContains(t, found, expected)45-46- // Better have our example47- expected = translate(cmdEcho.Name())48- checkStringContains(t, found, expected)49-50- // A local flag51- expected = "boolone"52- checkStringContains(t, found, expected)53-54- // persistent flag on parent55- expected = "rootflag"56- checkStringContains(t, found, expected)57-58- // We better output info about our parent59- expected = translate(cmdRootWithRun.Name())60- checkStringContains(t, found, expected)61-62- // And about subcommands63- expected = translate(cmdEchoSub.Name())64- checkStringContains(t, found, expected)65-66- unexpected := translate(cmdDeprecated.Name())67- checkStringOmits(t, found, unexpected)68-69- // auto generated70- expected = translate("Auto generated")71- checkStringContains(t, found, expected)72-}73-74-func TestGenManNoGenTag(t *testing.T) {75-76- 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)83-84- 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()91-92- 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.13-14-package cobra15-16-import (17- "bytes"18- "fmt"19- "os"20- "sort"21- "strings"22- "time"23-24- mangen "github.com/cpuguy83/go-md2man/md2man"25- "github.com/spf13/pflag"26-)27-28-// GenManTree will call cmd.GenManTree(header, dir)29-func GenManTree(cmd *Command, header *GenManHeader, dir string) {30- cmd.GenManTree(header, dir)31-}32-33-// 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`.38-func (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)49-50- needToResetTitle := header.Title == ""51-52- cmd.GenMan(header, out)53-54- if needToResetTitle {55- header.Title = ""56- }57-58- 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-}72-73-// 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.77-type GenManHeader struct {78- Title string79- Section string80- Date *time.Time81- date string82- Source string83- Manual string84-}85-86-// GenMan will call cmd.GenMan(header, out)87-func GenMan(cmd *Command, header *GenManHeader, out *bytes.Buffer) {88- cmd.GenMan(header, out)89-}90-91-// 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.93-func (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-}101-102-func 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-}118-119-func 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-}132-133-func 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-}160-161-func 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-}175-176-func 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)181-182- fillHeader(header, commandName)183-184- buf := new(bytes.Buffer)185-186- short := cmd.Short187- long := cmd.Long188- if len(long) == 0 {189- long = short190- }191-192- 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
12345678910111213141516171819202122232425# Generating Man Pages For Your Own cobra.Command
Generating man pages from a cobra command is incredibly easy. An example is as follows:
```gopackage main
import ( "github.com/spf13/cobra")
func main() { cmd := &cobra.Command{ Use: "test", Short: "my test program", } header := &cobra.GenManHeader{ Title: "MINE", Section: "3", } cmd.GenManTree(header, "/tmp")}```
That will get you a man page `/tmp/test.1`deleted:md_docs_test.go-84 removed
1-package cobra2-3-import (4- "bytes"5- "fmt"6- "os"7- "strings"8- "testing"9-)10-11-var _ = fmt.Println12-var _ = os.Stderr13-14-func 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)20-21- out := new(bytes.Buffer)22-23- // We generate on s subcommand so we have both subcommands and parents24- GenMarkdown(cmdEcho, out)25- found := out.String()26-27- // 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- }32-33- // 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- }38-39- // 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- }44-45- // 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- }50-51- // 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- }56-57- // 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- }62-63- unexpected := cmdDeprecated.Short64- if strings.Contains(found, unexpected) {65- t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)66- }67-}68-69-func 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)77-78- GenMarkdown(c, out)79- found := out.String()80-81- unexpected := "Auto generated"82- checkStringOmits(t, found, unexpected)83-84-}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.13-14-package cobra15-16-import (17- "bytes"18- "fmt"19- "os"20- "sort"21- "strings"22- "time"23-)24-25-func 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- }33-34- 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-}42-43-type byName []*Command44-45-func (s byName) Len() int { return len(s) }46-func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }47-func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }48-49-func GenMarkdown(cmd *Command, out *bytes.Buffer) {50- cmd.GenMarkdown(out)51-}52-53-func (cmd *Command) GenMarkdown(out *bytes.Buffer) {54- cmd.GenMarkdownCustom(out, func(s string) string { return s })55-}56-57-func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {58- cmd.GenMarkdownCustom(out, linkHandler)59-}60-61-func (cmd *Command) GenMarkdownCustom(out *bytes.Buffer, linkHandler func(string) string) {62- name := cmd.CommandPath()63-64- short := cmd.Short65- long := cmd.Long66- if len(long) == 0 {67- long = short68- }69-70- 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)74-75- if cmd.Runnable() {76- fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())77- }78-79- if len(cmd.Example) > 0 {80- fmt.Fprintf(out, "### Examples\n\n")81- fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)82- }83-84- 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- }99-100- children := cmd.Commands()101- sort.Sort(byName(children))102-103- 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-}118-119-func GenMarkdownTree(cmd *Command, dir string) {120- cmd.GenMarkdownTree(dir)121-}122-123-func (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-}128-129-func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {130- cmd.GenMarkdownTreeCustom(dir, filePrepender, linkHandler)131-}132-133-func (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)141-142- cmd.GenMarkdownCustom(out, linkHandler)143-144- 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.Command2-3-## Generate markdown docs for the entire command tree4-5-This program can actually generate docs for the kubectl command in the kubernetes project6-7-```go8-package main9-10-import (11- "io/ioutil"12- "os"13-14- "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"15- "github.com/spf13/cobra"16-)17-18-func main() {19- kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)20- cobra.GenMarkdownTree(kubectl, "./")21-}22-```23-24-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")25-26-## Generate markdown docs for a single command27-28-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`29-30-```go31- out := new(bytes.Buffer)32- cobra.GenMarkdown(cmd, out)33-```34-35-This will write the markdown doc for ONLY "cmd" into the out, buffer.36-37-## Customize the output38-39-Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:40-41-```go42-func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {43- //...44-}45-```46-47-```go48-func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {49- //...50-}51-```52-53-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](http://gohugo.io/):54-55-```go56-const fmTemplate = `---57-date: %s58-title: "%s"59-slug: %s60-url: %s61----62-`63-64-filePrepender := 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-```72-73-The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:74-75-```go76-linkHandler := func(name string) string {77- base := strings.TrimSuffix(name, path.Ext(name))78- return "/commands/" + strings.ToLower(base) + "/"79-}80-```81-