Merge pull request #87 from eparis/gen-md-doc
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Auto generation of markdown docs!
authored by Eric Paris · committed by Eric Paris · parents c746d30, 8a18f25 · Browse files · 5 files·+233 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+233 added−0 removed
- other:+233 added−0 removed
Provenance
- Commit
c0da825- Tree
7b03f38- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
c746d30- Parent 2
8a18f25
5 files changed+233 added−0 removed
modified:cobra_test.go+9 added
35 unmodified lines36 Use: "echo [string to echo]",37 Aliases: []string{"say"},38 Short: "Echo anything to the screen",39 Long: `an utterly useless command for testing.`,40+ Example: "Just run cobra-test echo",41 Run: func(cmd *Command, args []string) {42 te = args43 },44 }45 46+var cmdEchoSub = &Command{47+ Use: "echosub [string to print]",48+ Short: "second sub command for echo",49+ Long: `an absolutely utterly useless command for testing gendocs!.`,50+ Run: func(cmd *Command, args []string) {51+ },52+}53+54 var cmdTimes = &Command{55 Use: "times [# times] [string to echo]",56 Short: "Echo anything to the screen more times",57 Long: `a slightly useless command for testing.`,731 unmodified linesadded:md_docs_test.go+64 added
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)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+ fmt.Fprintf(os.Stdout, "%s\n", found)64+}added:md_docs.go+121 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 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 inherrited 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+ name := cmd.CommandPath()51+52+ short := cmd.Short53+ long := cmd.Long54+ if len(long) == 0 {55+ long = short56+ }57+58+ fmt.Fprintf(out, "## %s\n\n", name)59+ fmt.Fprintf(out, "%s\n\n", short)60+ fmt.Fprintf(out, "### Synopsis\n\n")61+ fmt.Fprintf(out, "\n%s\n\n", long)62+63+ if cmd.Runnable() {64+ fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())65+ }66+67+ if len(cmd.Example) > 0 {68+ fmt.Fprintf(out, "### Examples\n\n")69+ fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)70+ }71+72+ printOptions(out, cmd, name)73+74+ if len(cmd.Commands()) > 0 || cmd.HasParent() {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, link, parent.Short)82+ }83+84+ children := cmd.Commands()85+ sort.Sort(byName(children))86+87+ for _, child := range children {88+ cname := name + " " + child.Name()89+ link := cname + ".md"90+ link = strings.Replace(link, " ", "_", -1)91+ fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, link, child.Short)92+ }93+ fmt.Fprintf(out, "\n")94+ }95+96+ fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC())97+}98+99+func GenMarkdownTree(cmd *Command, dir string) {100+ for _, c := range cmd.Commands() {101+ GenMarkdownTree(c, dir)102+ }103+104+ out := new(bytes.Buffer)105+106+ GenMarkdown(cmd, out)107+108+ filename := cmd.CommandPath()109+ filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"110+ outFile, err := os.Create(filename)111+ if err != nil {112+ fmt.Println(err)113+ os.Exit(1)114+ }115+ defer outFile.Close()116+ _, err = outFile.Write(out.Bytes())117+ if err != nil {118+ fmt.Println(err)119+ os.Exit(1)120+ }121+}added:md_docs.md+35 added
1234567891011121314151617181920212223242526272829303132333435# Generating Markdown Docs For Your Own cobra.Command
## Generate markdown docs for the entire command tree
This program can actually generate docs for the kubectl command in the kubernetes project
```gopackage main
import ( "io/ioutil" "os"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd" "github.com/spf13/cobra")
func main() { kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard) cobra.GenMarkdownTree(kubectl, "./")}```
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
## Generate markdown docs for a single command
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown()` instead of `GenMarkdownTree`
```go out := new(bytes.Buffer) cobra.GenMarkdown(cmd, out)```
This will write the markdown doc for ONLY "cmd" into the out, buffer.modified:README.md+4 added
346 unmodified lines347 command.SetUsageFunc(f func(*Command) error)348 349 command.SetUsageTemplate(s string)350 351+## Generating markdown formatted documentation for your command352+353+Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md)354+355 ## Generating bash completions for your command356 357 Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md)358 57 unmodified lines