Exit non-zero if a unknown subcommand is given

Currently it just prints the help message and exits 0.

We do this by modifying the helpCommand and helpSubcommand cli.Commands
to return an error if they are called with an unknown subcommand. This
propogates up to the app which exits with 3 and prints the error.

Thanks to @danslimmon for the initial approach!

Fixes #276
This commit is contained in:
Jesse Szwedko
2016-05-07 17:22:09 -07:00
parent d3a4d5467b
commit 592f1d97e5
3 changed files with 81 additions and 19 deletions

32
help.go
View File

@@ -81,10 +81,10 @@ var helpCommand = Command{
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowAppHelp(c)
return ShowCommandHelp(c, args.First())
}
ShowAppHelp(c)
return nil
},
}
@@ -97,11 +97,10 @@ var helpSubcommand = Command{
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowSubcommandHelp(c)
return ShowCommandHelp(c, args.First())
}
return nil
return ShowSubcommandHelp(c)
},
}
@@ -127,30 +126,31 @@ func DefaultAppComplete(c *Context) {
}
// Prints help for the given command
func ShowCommandHelp(ctx *Context, command string) {
func ShowCommandHelp(ctx *Context, command string) error {
// show the subcommand help for a command with subcommands
if command == "" {
HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
return
return nil
}
for _, c := range ctx.App.Commands {
if c.HasName(command) {
HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
return
return nil
}
}
if ctx.App.CommandNotFound != nil {
ctx.App.CommandNotFound(ctx, command)
} else {
fmt.Fprintf(ctx.App.Writer, "No help topic for '%v'\n", command)
if ctx.App.CommandNotFound == nil {
return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3)
}
ctx.App.CommandNotFound(ctx, command)
return nil
}
// Prints help for the given subcommand
func ShowSubcommandHelp(c *Context) {
ShowCommandHelp(c, c.Command.Name)
func ShowSubcommandHelp(c *Context) error {
return ShowCommandHelp(c, c.Command.Name)
}
// Prints the version number of the App