Updates NoArgs to also report invalid argument

NoArgs currently reports "unknown command" in all cases, which
can be is a little misleading to the user if there are no
subcommands. Change it as follows

- if subcommands and one extra arg, say "unknown command"
- otherwise, say "invalid argument(s)" and show all extra args

This should produce more meaningful error messages to users, and
works for both the root and sub-commands.
This commit is contained in:
Brian Fitzgerald 2018-04-06 12:44:58 -07:00
parent 4dab30cb33
commit d8e244d161
2 changed files with 13 additions and 4 deletions

13
args.go
View file

@ -2,6 +2,7 @@ package cobra
import (
"fmt"
"strings"
)
type PositionalArgs func(cmd *Command, args []string) error
@ -25,10 +26,18 @@ func legacyArgs(cmd *Command, args []string) error {
// NoArgs returns an error if any args are included.
func NoArgs(cmd *Command, args []string) error {
if len(args) > 0 {
if len(args) == 0 {
return nil
}
// If we have exactly one argument and we have sub-commands, then assume the user
// made a typo on a subcommand, or typed the wrong subcommand
if len(args) == 1 && len(cmd.commands) > 0 {
return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
}
return nil
// Otherwise, assume that this is one or more invalid arguments
return fmt.Errorf("invalid argument(s) %q for %q", strings.Join(args, " "), cmd.CommandPath())
}
// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.

View file

@ -26,7 +26,7 @@ func TestNoArgsWithArgs(t *testing.T) {
}
got := err.Error()
expected := `unknown command "illegal" for "c"`
expected := `invalid argument(s) "illegal" for "c"`
if got != expected {
t.Errorf("Expected: %q, got: %q", expected, got)
}
@ -223,7 +223,7 @@ func TestChildTakesNoArgs(t *testing.T) {
}
got := err.Error()
expected := `unknown command "illegal" for "root child"`
expected := `invalid argument(s) "illegal args" for "root child"`
if !strings.Contains(got, expected) {
t.Errorf("expected %q, got %q", expected, got)
}