Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide usefull errors when using invalid sub command #1716

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ func legacyArgs(cmd *Command, args []string) error {
return nil
}

// Legacy sub command arg validation has the following behaviour:
// - commands with no subcommands can take arbitrary arguments
// - commands with subcommands will do subcommand validity checking
// - subcommands will always accept arbitrary arguments
func legacySubCommandArgs(cmd *Command, args []string) error {
// no subcommand, always take args
if !cmd.HasSubCommands() {
return nil
}

// command with subcommands, do subcommand checking.
if len(args) > 0 {
return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
}
return nil
}

// NoArgs returns an error if any args are included.
func NoArgs(cmd *Command, args []string) error {
if len(args) > 0 {
Expand Down
5 changes: 4 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,10 @@ func (c *Command) Traverse(args []string) (*Command, []string, error) {

cmd := c.findNext(arg)
if cmd == nil {
return c, args, nil
if c.Runnable() {
return c, args, nil
}
return c, args, legacySubCommandArgs(c, args)
}

if err := c.ParseFlags(flags); err != nil {
Expand Down