Skip to content
Myr

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

5 files+373 added−4 removed

modified:doc/md_docs.md+3 added-3 removed
modified:doc/util.go+14 added-1 removed
11 unmodified lines
12// limitations under the License.1314package doc1516import "github.com/spf13/cobra"16import (17 "strings"1819 "github.com/spf13/cobra"20)2122// 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.25func hasSeeAlso(cmd *cobra.Command) bool {
8 unmodified lines
34 }35 return false36}3738// Temporary workaround for yaml lib generating incorrect yaml with long strings39// that do not contain \n.40func forceMultiLine(s string) string {41 if len(s) > 60 && !strings.Contains(s, "\n") {42 s = s + "\n"43 }44 return s45}4647type byName []*cobra.Command4849func (s byName) Len() int { return len(s) }50func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1 unmodified line
added:doc/yaml_docs_test.go+88 added
1package doc23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func 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)2021 out := new(bytes.Buffer)2223 // 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()2829 // 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 }3435 // 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 }4041 // 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 }4647 // 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 }5253 // 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 }5859 // 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 }6465 unexpected := cmdDeprecated.Short66 if strings.Contains(found, unexpected) {67 t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)68 }69}7071func 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)7980 if err := GenYaml(c, out); err != nil {81 t.Fatal(err)82 }83 found := out.String()8485 unexpected := "Auto generated"86 checkStringOmits(t, found, unexpected)8788}
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.1314package doc1516import (17 "fmt"18 "io"19 "os"20 "path/filepath"21 "sort"22 "strings"2324 "github.com/spf13/cobra"25 "github.com/spf13/pflag"26 "gopkg.in/yaml.v2"27)2829type cmdOption struct {30 Name string31 Shorthand string `yaml:",omitempty"`32 DefaultValue string `yaml:"default_value,omitempty"`33 Usage string `yaml:",omitempty"`34}3536type 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}4546// 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`.51func 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}5657// GenYamlTreeCustom creates yaml structured ref files58func 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 }6768 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()7576 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}8485// GenYaml creates yaml output86func GenYaml(cmd *cobra.Command, w io.Writer) error {87 return GenYamlCustom(cmd, w, func(s string) string { return s })88}8990// GenYamlCustom creates custom yaml output91func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {92 yamlDoc := cmdDoc{}93 yamlDoc.Name = cmd.CommandPath()9495 yamlDoc.Synopsis = forceMultiLine(cmd.Short)96 yamlDoc.Description = forceMultiLine(cmd.Long)9798 if len(cmd.Example) > 0 {99 yamlDoc.Example = cmd.Example100 }101102 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 }110111 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 }127128 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}138139func genFlagResult(flags *pflag.FlagSet) []cmdOption {140 var result []cmdOption141142 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 })163164 return result165}
added:doc/yaml_docs.md+103 added
1# Generating Yaml Docs For Your Own cobra.Command23Generating yaml files from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "github.com/spf13/cobra"10 "github.com/spf13/cobra/doc"11)1213func main() {14 cmd := &cobra.Command{15 Use: "test",16 Short: "my test program",17 }18 doc.GenYamlTree(cmd, "/tmp")19}20```2122That will get you a Yaml document `/tmp/test.yaml`2324## Generate yaml docs for the entire command tree2526This program can actually generate docs for the kubectl command in the kubernetes project2728```go29package main3031import (32 "io/ioutil"33 "os"3435 "k8s.io/kubernetes/pkg/kubectl/cmd"36 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"3738 "github.com/spf13/cobra/doc"39)4041func main() {42 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)43 doc.GenYamlTree(kubectl, "./")44}45```4647This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")4849## Generate yaml docs for a single command5051You 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`5253```go54 out := new(bytes.Buffer)55 doc.GenYaml(cmd, out)56```5758This will write the yaml doc for ONLY "cmd" into the out, buffer.5960## Customize the output6162Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:6364```go65func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {66 //...67}68```6970```go71func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {72 //...73}74```7576The `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/):7778```go79const fmTemplate = `---80date: %s81title: "%s"82slug: %s83url: %s84---85`8687filePrepender := 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```9596The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:9798```go99linkHandler := func(name string) string {100 base := strings.TrimSuffix(name, path.Ext(name))101 return "/commands/" + strings.ToLower(base) + "/"102}103```