Skip to content
Myr

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

5 files+233 added−0 removed

modified:cobra_test.go+9 added
35 unmodified lines
36 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}4546var 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}5354var 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 lines
added:md_docs_test.go+64 added
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)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 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.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 inherrited 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 name := cmd.CommandPath()5152 short := cmd.Short53 long := cmd.Long54 if len(long) == 0 {55 long = short56 }5758 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)6263 if cmd.Runnable() {64 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())65 }6667 if len(cmd.Example) > 0 {68 fmt.Fprintf(out, "### Examples\n\n")69 fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)70 }7172 printOptions(out, cmd, name)7374 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 }8384 children := cmd.Commands()85 sort.Sort(byName(children))8687 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 }9596 fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC())97}9899func GenMarkdownTree(cmd *Command, dir string) {100 for _, c := range cmd.Commands() {101 GenMarkdownTree(c, dir)102 }103104 out := new(bytes.Buffer)105106 GenMarkdown(cmd, out)107108 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
modified:README.md+4 added
346 unmodified lines
347 command.SetUsageFunc(f func(*Command) error)348349 command.SetUsageTemplate(s string)350351## Generating markdown formatted documentation for your command352353Cobra 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)354355## Generating bash completions for your command356357Cobra 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