Added support for yaml ouptut in docs gen (#380)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by French Ben · committed by Eric Paris · parent c29ece4 · Browse files · 5 files·+373 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: French Ben <frenchben@docker.com>
Diff stats
5 files+373 added−4 removed
- other:+373 added−4 removed
Provenance
- Commit
35136c0- Tree
0034a70- Author
French Ben <FrenchBen@users.noreply.github.com>- Committer
Eric Paris <eparis@redhat.com>- Parent
c29ece4
5 files changed+373 added−4 removed
modified:doc/md_docs.md+3 added-3 removed
30 unmodified lines313233343535363738394041424342434445464756 unmodified lines30 unmodified linesimport ( "io/ioutil" "os"
kubectlcmd "k8s.io/kubernetes/pkg/kubectl/cmd" "k8s.io/kubernetes/pkg/kubectl/cmd" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"github.com/spf13/cobra/doc")
func main() { cmd := kubectlcmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) doc.GenMarkdownTree(cmd, "./") kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) doc.GenMarkdownTree(kubectl, "./")}```
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")56 unmodified linesmodified:doc/util.go+14 added-1 removed
11 unmodified lines12 // limitations under the License.13 14 package doc15 16-import "github.com/spf13/cobra"16+import (17+ "strings"18 19+ "github.com/spf13/cobra"20+)21+22 // Test to see if we have a reason to print See Also information in docs23 // Basically this is a test for a parent commend or a subcommand which is24 // both not deprecated and not the autogenerated help command.25 func hasSeeAlso(cmd *cobra.Command) bool {8 unmodified lines34 }35 return false36 }37 38+// Temporary workaround for yaml lib generating incorrect yaml with long strings39+// that do not contain \n.40+func forceMultiLine(s string) string {41+ if len(s) > 60 && !strings.Contains(s, "\n") {42+ s = s + "\n"43+ }44+ return s45+}46+47 type byName []*cobra.Command48 49 func (s byName) Len() int { return len(s) }50 func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }1 unmodified lineadded:doc/yaml_docs_test.go+88 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 TestGenYamlDoc(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+ if err := GenYaml(cmdEcho, out); err != nil {25+ t.Fatal(err)26+ }27+ found := out.String()28+29+ // Our description30+ expected := cmdEcho.Long31+ if !strings.Contains(found, expected) {32+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)33+ }34+35+ // Better have our example36+ expected = cmdEcho.Example37+ if !strings.Contains(found, expected) {38+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)39+ }40+41+ // A local flag42+ expected = "boolone"43+ if !strings.Contains(found, expected) {44+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)45+ }46+47+ // persistent flag on parent48+ expected = "rootflag"49+ if !strings.Contains(found, expected) {50+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)51+ }52+53+ // We better output info about our parent54+ expected = cmdRootWithRun.Short55+ if !strings.Contains(found, expected) {56+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)57+ }58+59+ // And about subcommands60+ expected = cmdEchoSub.Short61+ if !strings.Contains(found, expected) {62+ t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)63+ }64+65+ unexpected := cmdDeprecated.Short66+ if strings.Contains(found, unexpected) {67+ t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)68+ }69+}70+71+func TestGenYamlNoTag(t *testing.T) {72+ c := initializeWithRootCmd()73+ // Need two commands to run the command alphabetical sort74+ cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)75+ c.AddCommand(cmdPrint, cmdEcho)76+ c.DisableAutoGenTag = true77+ cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)78+ out := new(bytes.Buffer)79+80+ if err := GenYaml(c, out); err != nil {81+ t.Fatal(err)82+ }83+ found := out.String()84+85+ unexpected := "Auto generated"86+ checkStringOmits(t, found, unexpected)87+88+}added:doc/yaml_docs.go+165 added
1+// Copyright 2016 French Ben. 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+ "fmt"18+ "io"19+ "os"20+ "path/filepath"21+ "sort"22+ "strings"23+24+ "github.com/spf13/cobra"25+ "github.com/spf13/pflag"26+ "gopkg.in/yaml.v2"27+)28+29+type cmdOption struct {30+ Name string31+ Shorthand string `yaml:",omitempty"`32+ DefaultValue string `yaml:"default_value,omitempty"`33+ Usage string `yaml:",omitempty"`34+}35+36+type cmdDoc struct {37+ Name string38+ Synopsis string `yaml:",omitempty"`39+ Description string `yaml:",omitempty"`40+ Options []cmdOption `yaml:",omitempty"`41+ InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"`42+ Example string `yaml:",omitempty"`43+ SeeAlso []string `yaml:"see_also,omitempty"`44+}45+46+// GenYamlTree creates yaml structured ref files for this command and all descendants47+// in the directory given. This function may not work48+// correctly if your command names have - in them. If you have `cmd` with two49+// subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`50+// it is undefined which help output will be in the file `cmd-sub-third.1`.51+func GenYamlTree(cmd *cobra.Command, dir string) error {52+ identity := func(s string) string { return s }53+ emptyStr := func(s string) string { return "" }54+ return GenYamlTreeCustom(cmd, dir, emptyStr, identity)55+}56+57+// GenYamlTreeCustom creates yaml structured ref files58+func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {59+ for _, c := range cmd.Commands() {60+ if !c.IsAvailableCommand() || c.IsHelpCommand() {61+ continue62+ }63+ if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {64+ return err65+ }66+ }67+68+ basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"69+ filename := filepath.Join(dir, basename)70+ f, err := os.Create(filename)71+ if err != nil {72+ return err73+ }74+ defer f.Close()75+76+ if _, err := io.WriteString(f, filePrepender(filename)); err != nil {77+ return err78+ }79+ if err := GenYamlCustom(cmd, f, linkHandler); err != nil {80+ return err81+ }82+ return nil83+}84+85+// GenYaml creates yaml output86+func GenYaml(cmd *cobra.Command, w io.Writer) error {87+ return GenYamlCustom(cmd, w, func(s string) string { return s })88+}89+90+// GenYamlCustom creates custom yaml output91+func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {92+ yamlDoc := cmdDoc{}93+ yamlDoc.Name = cmd.CommandPath()94+95+ yamlDoc.Synopsis = forceMultiLine(cmd.Short)96+ yamlDoc.Description = forceMultiLine(cmd.Long)97+98+ if len(cmd.Example) > 0 {99+ yamlDoc.Example = cmd.Example100+ }101+102+ flags := cmd.NonInheritedFlags()103+ if flags.HasFlags() {104+ yamlDoc.Options = genFlagResult(flags)105+ }106+ flags = cmd.InheritedFlags()107+ if flags.HasFlags() {108+ yamlDoc.InheritedOptions = genFlagResult(flags)109+ }110+111+ if hasSeeAlso(cmd) {112+ result := []string{}113+ if cmd.HasParent() {114+ parent := cmd.Parent()115+ result = append(result, parent.CommandPath()+" - "+parent.Short)116+ }117+ children := cmd.Commands()118+ sort.Sort(byName(children))119+ for _, child := range children {120+ if !child.IsAvailableCommand() || child.IsHelpCommand() {121+ continue122+ }123+ result = append(result, child.Name()+" - "+child.Short)124+ }125+ yamlDoc.SeeAlso = result126+ }127+128+ final, err := yaml.Marshal(&yamlDoc)129+ if err != nil {130+ fmt.Println(err)131+ os.Exit(1)132+ }133+ if _, err := fmt.Fprintf(w, string(final)); err != nil {134+ return err135+ }136+ return nil137+}138+139+func genFlagResult(flags *pflag.FlagSet) []cmdOption {140+ var result []cmdOption141+142+ flags.VisitAll(func(flag *pflag.Flag) {143+ // Todo, when we mark a shorthand is deprecated, but specify an empty message.144+ // The flag.ShorthandDeprecated is empty as the shorthand is deprecated.145+ // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.146+ if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 {147+ opt := cmdOption{148+ flag.Name,149+ flag.Shorthand,150+ flag.DefValue,151+ forceMultiLine(flag.Usage),152+ }153+ result = append(result, opt)154+ } else {155+ opt := cmdOption{156+ Name: flag.Name,157+ DefaultValue: forceMultiLine(flag.DefValue),158+ Usage: forceMultiLine(flag.Usage),159+ }160+ result = append(result, opt)161+ }162+ })163+164+ return result165+}added:doc/yaml_docs.md+103 added
1+# Generating Yaml Docs For Your Own cobra.Command2+3+Generating yaml files from a cobra command is incredibly easy. An example is as follows:4+5+```go6+package main7+8+import (9+ "github.com/spf13/cobra"10+ "github.com/spf13/cobra/doc"11+)12+13+func main() {14+ cmd := &cobra.Command{15+ Use: "test",16+ Short: "my test program",17+ }18+ doc.GenYamlTree(cmd, "/tmp")19+}20+```21+22+That will get you a Yaml document `/tmp/test.yaml`23+24+## Generate yaml docs for the entire command tree25+26+This program can actually generate docs for the kubectl command in the kubernetes project27+28+```go29+package main30+31+import (32+ "io/ioutil"33+ "os"34+35+ "k8s.io/kubernetes/pkg/kubectl/cmd"36+ cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"37+38+ "github.com/spf13/cobra/doc"39+)40+41+func main() {42+ kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)43+ doc.GenYamlTree(kubectl, "./")44+}45+```46+47+This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")48+49+## Generate yaml docs for a single command50+51+You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`52+53+```go54+ out := new(bytes.Buffer)55+ doc.GenYaml(cmd, out)56+```57+58+This will write the yaml doc for ONLY "cmd" into the out, buffer.59+60+## Customize the output61+62+Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:63+64+```go65+func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {66+ //...67+}68+```69+70+```go71+func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {72+ //...73+}74+```75+76+The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):77+78+```go79+const fmTemplate = `---80+date: %s81+title: "%s"82+slug: %s83+url: %s84+---85+`86+87+filePrepender := func(filename string) string {88+ now := time.Now().Format(time.RFC3339)89+ name := filepath.Base(filename)90+ base := strings.TrimSuffix(name, path.Ext(name))91+ url := "/commands/" + strings.ToLower(base) + "/"92+ return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)93+}94+```95+96+The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:97+98+```go99+linkHandler := func(name string) string {100+ base := strings.TrimSuffix(name, path.Ext(name))101+ return "/commands/" + strings.ToLower(base) + "/"102+}103+```