Add support for help command
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by spf13 · committed by spf13 · parent 68f3c66 · Browse files · 3 files·+86 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+86 added−22 removed
- other:+86 added−22 removed
Provenance
- Commit
fb2146e- Tree
0d3759e- Author
spf13 <steve.francia@gmail.com>- Committer
spf13 <steve.francia@gmail.com>- Parent
68f3c66
3 files changed+86 added−22 removed
modified:cobra_test.go+29 added-4 removed
213 unmodified lines214 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)215 }216 217 // Testing with flag only existing on child218- buf2 := new(bytes.Buffer)218+ buf.Reset()219 c = initialize()220- c.SetOutput(buf2)220+ c.SetOutput(buf)221 cmdEcho.AddCommand(cmdTimes)222 c.AddCommand(cmdPrint, cmdEcho)223 c.SetArgs(strings.Split("echo -j 99 -i77 one two", " "))224 err := c.Execute()1 unmodified line226 if err == nil {227 t.Errorf("invalid flag should generate error")228 }229 230- if !strings.Contains(buf2.String(), "intone=123") {230+ if !strings.Contains(buf.String(), "intone=123") {231 t.Errorf("Wrong error message displayed, \n %s", buf.String())232 }233-233 }234 235 func TestPersistentFlags(t *testing.T) {236 c := initialize()29 unmodified lines266 if flagb2 != true {267 t.Errorf("local flag not parsed correctly. Expected false, had %v", flagb2)268 }269 }270+271+func TestHelpCommand(t *testing.T) {272+ buf := new(bytes.Buffer)273+ c := initialize()274+ cmdEcho.AddCommand(cmdTimes)275+ c.AddCommand(cmdPrint, cmdEcho)276+ c.SetArgs(strings.Split("help echo", " "))277+ c.SetOutput(buf)278+ c.Execute()279+280+ if !strings.Contains(buf.String(), cmdEcho.Long) {281+ t.Errorf("Wrong error message displayed, \n %s", buf.String())282+ }283+284+ buf.Reset()285+ c = initialize()286+ cmdEcho.AddCommand(cmdTimes)287+ c.AddCommand(cmdPrint, cmdEcho)288+ c.SetArgs(strings.Split("help echo times", " "))289+ c.SetOutput(buf)290+ c.Execute()291+292+ if !strings.Contains(buf.String(), cmdTimes.Long) {293+ t.Errorf("Wrong error message displayed, \n %s", buf.String())294+ }295+}modified:command.go+15 added-7 removed
51 unmodified lines52 flagErrorBuf *bytes.Buffer53 }54 55 // find the target command given the args and command tree56+// Meant to be run on the highest node. Only searches down.57 func (c *Command) Find(args []string) (cmd *Command, a []string, err error) {58 if c == nil {59 return nil, nil, fmt.Errorf("Called find() on a nil Command")60 }61 62 validSubCommand := false62- if len(args) > 1 && c.HasSubCommands() {63+ if len(args) > 0 && c.HasSubCommands() {64 for _, cmd := range c.commands {65 if cmd.Name() == args[0] {66 validSubCommand = true67 return cmd.Find(args[1:])6 unmodified lines74 75 return nil, nil, nil76 }77 77-func (c *Command) Commander() *Commander {78+func (c *Command) Root() *Command {79 var findRoot func(*Command) *Command80 81 findRoot = func(x *Command) *Command {82 if x.HasParent() {1 unmodified line84 } else {85 return x86 }87 }88+87- cmdr := findRoot(c)89+ return findRoot(c)90+}91+92+func (c *Command) Commander() *Commander {93+ cmdr := c.Root()94 if cmdr.cmdr != nil {95 return cmdr.cmdr96 } else {97 panic("commander not found")15 unmodified lines113 cmd, a, e := c.Find(args)114 if e == nil {115 err = cmd.ParseFlags(a)116 if err != nil {117+ // report flag parsing error118+ c.Println(strings.Split(err.Error(), "\n")[0])111- cmd.Usage()119+ erx := cmd.Usage()120+ if erx != nil {121+ return erx122+ }123 return err124 } else {125 argWoFlags := cmd.Flags().Args()126 cmd.Run(cmd, argWoFlags)45 unmodified lines172 // Used when a user provides invalid input173 // Can be defined by user by overriding Commander.UsageFunc174 func (c *Command) Usage() error {175 err := c.Commander().UsageFunc(c)165- if err != nil {166- fmt.Println(err)167- }176 return err177 }178 179 // The full path to this command198 unmodified linesmodified:commander.go+42 added-11 removed
26 unmodified lines27 // A Commander is also a Command for top level and global help & flags28 Command29 30 args []string31- output *io.Writer // nil means stderr; use out() accessor32- UsageFunc func(*Command) error // Usage can be defined by application33- UsageTemplate string // Can be defined by Application34- HelpTemplate string // Can be defined by Application31+ output *io.Writer // nil means stderr; use out() accessor32+ UsageFunc func(*Command) error // Usage can be defined by application33+ UsageTemplate string // Can be defined by Application34+ HelpTemplate string // Can be defined by Application35+ HelpFunc func(*Command, []string) // Help can be defined by application36+ HelpCommand *Command37 }38 39 // Provide the user with a new commander.40 func NewCommander() (c *Commander) {41 c = new(Commander)42 c.cmdr = c43 c.UsageFunc = c.defaultUsage44+ c.HelpFunc = c.defaultHelp45 c.initTemplates()46 return47 }48 49+func (c *Commander) initHelp() {50+ if c.HelpCommand == nil {51+ c.HelpCommand = &Command{52+ Use: "help [command to learn about]",53+ Short: "Help about any command",54+ Long: `Help provides help for any command in the application.55+ Simply type ` + c.Name() + ` help [path to command] for full details.`,56+ Run: c.HelpFunc,57+ }58+ }59+ c.AddCommand(c.HelpCommand)60+}61+62 // Name for commander, should match application name63 func (c *Commander) SetName(name string) {64 c.name = name65 }7 unmodified lines73 // Call execute to use the args (os.Args[1:] by default)74 // and run through the command tree finding appropriate matches75 // for commands and then corresponding flags.76 func (c *Commander) Execute() (err error) {77+ // initialize help as the last point possible to allow for user78+ // overriding79+ c.initHelp()80 if len(c.args) == 0 {81 err = c.execute(os.Args[1:])82 } else {83 err = c.execute(c.args)9 unmodified lines93 }94 95 func (cmdr *Commander) defaultUsage(c *Command) error {96 err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)78- if err != nil {79- c.Println(err)80- }97 return err98 }99 100+func (cmdr *Commander) defaultHelp(c *Command, args []string) {101+ cmd, _, e := c.Root().Find(args)102+ if cmd == nil {103+ cmdr.Printf("Unknown help topic %#q. Run '%v help'.\n", args, cmdr.Name())104+ return105+ }106+ if e != nil {107+ cmdr.Printf("Unknown help topic %#q. Run '%v help'.\n", args, cmdr.Name())108+ } else {109+ err := tmpl(cmdr.out(), cmdr.HelpTemplate, cmd)110+ if err != nil {111+ c.Println(err)112+ }113+ }114+}115+116 //Print to out117 func (c *Commander) PrintOut(i ...interface{}) {118 fmt.Fprint(c.out(), i...)119 }1 unmodified line121 // SetOutput sets the destination for usage and error messages.122 // If output is nil, os.Stderr is used.123 func (c *Commander) SetOutput(output io.Writer) {124 c.output = &output93- //*c.output = output125 }126 127 func (c *Commander) initTemplates() {128 c.UsageTemplate = `{{ $cmd := . }}13 unmodified lines142 {{end}}143 Use "{{.Commander.Name}} help [command]" for more information about that command.144 `145 115- c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}116-117-{{end}}{{.Long | trim}}146+ c.HelpTemplate = `{{.Name}}147+{{.Long | trim}}148+{{if .Runnable}}{{.Usage}}{{end}}149 `150 }