Skip to content
Myr

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

3 files+86 added−22 removed

modified:cobra_test.go+29 added-4 removed
213 unmodified lines
214 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)215 }216217 // 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 line
226 if err == nil {227 t.Errorf("invalid flag should generate error")228 }229230 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 }233233}234235func TestPersistentFlags(t *testing.T) {236 c := initialize()
29 unmodified lines
266 if flagb2 != true {267 t.Errorf("local flag not parsed correctly. Expected false, had %v", flagb2)268 }269}270271func 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()279280 if !strings.Contains(buf.String(), cmdEcho.Long) {281 t.Errorf("Wrong error message displayed, \n %s", buf.String())282 }283284 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()291292 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 lines
52 flagErrorBuf *bytes.Buffer53}5455// find the target command given the args and command tree56// Meant to be run on the highest node. Only searches down.57func (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 }6162 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 lines
7475 return nil, nil, nil76}7777func (c *Command) Commander() *Commander {78func (c *Command) Root() *Command {79 var findRoot func(*Command) *Command8081 findRoot = func(x *Command) *Command {82 if x.HasParent() {
1 unmodified line
84 } else {85 return x86 }87 }8887 cmdr := findRoot(c)89 return findRoot(c)90}9192func (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 lines
113 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 lines
172// Used when a user provides invalid input173// Can be defined by user by overriding Commander.UsageFunc174func (c *Command) Usage() error {175 err := c.Commander().UsageFunc(c)165 if err != nil {166 fmt.Println(err)167 }176 return err177}178179// The full path to this command
198 unmodified lines
modified:commander.go+42 added-11 removed
26 unmodified lines
27 // A Commander is also a Command for top level and global help & flags28 Command2930 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}3839// Provide the user with a new commander.40func NewCommander() (c *Commander) {41 c = new(Commander)42 c.cmdr = c43 c.UsageFunc = c.defaultUsage44 c.HelpFunc = c.defaultHelp45 c.initTemplates()46 return47}4849func (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}6162// Name for commander, should match application name63func (c *Commander) SetName(name string) {64 c.name = name65}
7 unmodified lines
73// 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.76func (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 lines
93}9495func (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}99100func (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}115116//Print to out117func (c *Commander) PrintOut(i ...interface{}) {118 fmt.Fprint(c.out(), i...)119}
1 unmodified line
121// SetOutput sets the destination for usage and error messages.122// If output is nil, os.Stderr is used.123func (c *Commander) SetOutput(output io.Writer) {124 c.output = &output93 //*c.output = output125}126127func (c *Commander) initTemplates() {128 c.UsageTemplate = `{{ $cmd := . }}
13 unmodified lines
142{{end}}143Use "{{.Commander.Name}} help [command]" for more information about that command.144`145115 c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}116117{{end}}{{.Long | trim}}146 c.HelpTemplate = `{{.Name}}147{{.Long | trim}}148{{if .Runnable}}{{.Usage}}{{end}}149`150}