Skip to content

Commit

Permalink
Consistent usage hint for unknown subcommand and flag
Browse files Browse the repository at this point in the history
Now, when you try to run a Command with an unknown sub-command vs. an unknown flag, you'll get:
```
$ testcommand asdsa
Error: unknown command "asdsa" for "testcommand"
Run 'testcommand --help' for usage.

$ testcommand --asdsa
Error: unknown flag: --asdsa

$ testcommand -asdsa
Error: unknown shorthand flag: 'a' in -asdsa
```

With these changes, you'll get:
```
$ testcommand asdsa
Error: unknown command "asdsa" for "testcommand"
Run 'testcommand --help' for usage.

$ testcommand --asdsa
Error: unknown flag: --asdsa
Run 'testcommand --help' for usage.

$ testcommand -asdsa
Error: unknown shorthand flag: 'a' in -asdsa
Run 'testcommand --help' for usage.
```

Merge spf13/cobra#1023
  • Loading branch information
dgn authored and hoshsadiq committed Feb 8, 2022
1 parent 09a5d95 commit 5d94f7d
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,11 @@ func (c *Command) UsageString() string {
return bb.String()
}

// UsageHintString returns a string that describes how to obtain usage instructions
func (c *Command) UsageHintString() string {
return fmt.Sprintf("Run '%v --help' for usage.\n", c.CommandPath())
}

// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
// command or a parent, or it returns a function which returns the original
// error.
Expand Down Expand Up @@ -964,7 +969,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
}
if !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
c.PrintErrf(cmd.UsageHintString())
}
return c, err
}
Expand Down Expand Up @@ -999,6 +1004,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// all subcommands should respect it
if !cmd.SilenceUsage && !c.SilenceUsage {
c.Println(cmd.UsageString())
} else if !cmd.SilenceErrors && !c.SilenceErrors {
// if SilenceUsage && !SilenceErrors, we should be consistent with the unknown sub-command case and output a hint
c.Printf(cmd.UsageHintString())
}
}
return cmd, err
Expand Down

0 comments on commit 5d94f7d

Please sign in to comment.