Skip to content
Closed
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
13 changes: 11 additions & 2 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cobra

import (
"fmt"
"strings"
)

type PositionalArgs func(cmd *Command, args []string) error
Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down