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

closes #2130 new command flag ErrorOnUnknownSubcommand #2167

Open
wants to merge 5 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
20 changes: 16 additions & 4 deletions cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ var initializers []func()
var finalizers []func()

const (
defaultPrefixMatching = false
defaultCommandSorting = true
defaultCaseInsensitive = false
defaultTraverseRunHooks = false
defaultPrefixMatching = false
defaultCommandSorting = true
defaultCaseInsensitive = false
defaultTraverseRunHooks = false
defaultErrorOnUnknownSubcommand = false
)

// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing
Expand All @@ -65,6 +66,17 @@ var EnableCaseInsensitive = defaultCaseInsensitive
// By default this is disabled, which means only the first run hook to be found is executed.
var EnableTraverseRunHooks = defaultTraverseRunHooks

// EnableErrorOnUnknownSubcommand controls the behavior of subcommand handling.
// When the flag is set true the behavior of Command.Execute() will change:
// If a sub-subcommand is not found an error will be returned on calling
// Command.Exec() instead of the old behavior where a nil error was sent.
// If the flag is false (default) the old behavior is performed.
// For this behavior the child subcommand must be nil.
// Example: in root/service/run - there would be an existing subcommand `run`
// in root/service/unknown - there would be an unknown subcommand `unknown` therefore returning an error
// `service` must have a nil Command.Run() function for this.
var EnableErrorOnUnknownSubcommand = defaultErrorOnUnknownSubcommand

// MousetrapHelpText enables an information splash screen on Windows
// if the CLI is started from explorer.exe.
// To disable the mousetrap, just set this variable to blank string ("").
Expand Down
17 changes: 10 additions & 7 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,19 +923,22 @@ func (c *Command) execute(a []string) (err error) {
}
}

if !c.Runnable() {
return flag.ErrHelp
argWoFlags := c.Flags().Args()
if c.DisableFlagParsing {
argWoFlags = a
}

if !c.Runnable() {
if EnableErrorOnUnknownSubcommand && len(argWoFlags) > 0 {
return fmt.Errorf("unknown command %q for %q%s", argWoFlags[0], c.CommandPath(), c.findSuggestions(argWoFlags[0]))
} else {
return flag.ErrHelp
}
}
c.preRun()

defer c.postRun()

argWoFlags := c.Flags().Args()
if c.DisableFlagParsing {
argWoFlags = a
}

if err := c.ValidateArgs(argWoFlags); err != nil {
return err
}
Expand Down
115 changes: 115 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,121 @@ func TestSubcommandExecuteC(t *testing.T) {
}
}

func TestSubcommandExecuteMissingSubcommand(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
const childName = "child"
const grandchildName = "grandchild"
EnableErrorOnUnknownSubcommand = false
defer func() { EnableErrorOnUnknownSubcommand = defaultErrorOnUnknownSubcommand }()
childCmd := &Command{Use: childName, Run: nil}
child2Cmd := &Command{Use: grandchildName, Run: emptyRun}
rootCmd.AddCommand(childCmd)
childCmd.AddCommand(child2Cmd)

// test existing command
c, output, err := executeCommandC(rootCmd, childName)
if !strings.HasPrefix(output, "Usage:") {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != childName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}

// test existing sub command
c, output, err = executeCommandC(rootCmd, childName, grandchildName)
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != grandchildName {
t.Errorf(`invalid command returned from ExecuteC: expected "grandchild"', got: %q`, c.Name())
}

// now test a command which does not exist, we will get no error, just "Usage:" is printed
c, output, err = executeCommandC(rootCmd, childName, "unknownChild")
if !strings.HasPrefix(output, "Usage:") {
t.Errorf("Expected: 'Usage: ...'\nGot:\n %q\n", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != childName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}
}

func TestSubcommandExecuteMissingSubcommandWithErrorOnUnknownSubcommand(t *testing.T) {
const rootName = "root"
rootCmd := &Command{Use: rootName, Run: emptyRun}
const childName = "child"
const grandchildName = "grandchild"
EnableErrorOnUnknownSubcommand = true
defer func() { EnableErrorOnUnknownSubcommand = defaultErrorOnUnknownSubcommand }()
childCmd := &Command{Use: childName, Run: nil}
child2Cmd := &Command{Use: grandchildName, Run: emptyRun}
rootCmd.AddCommand(childCmd)
childCmd.AddCommand(child2Cmd)

// test existing command
c, output, err := executeCommandC(rootCmd, childName)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case should not show an error but should print the usage like before.

if strings.HasPrefix(output, "Error:") {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != childName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}

// test existing sub command
c, output, err = executeCommandC(rootCmd, childName, grandchildName)
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != grandchildName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}

// test a child command which does not exist, we expect an error because of the ErrorOnUnknownSubcommand flag
c, output, err = executeCommandC(rootCmd, "unknownChild")
if !strings.HasPrefix(output, "Error:") {
t.Errorf("Unexpected output: %v", output)
}
if err == nil {
t.Error("Expected error")
}
if err != nil && !strings.HasPrefix(err.Error(), "unknown command") {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != rootName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}

// test a grandchild command which does not exist, we expect an error because of the ErrorOnUnknownSubcommand flag
c, output, err = executeCommandC(rootCmd, childName, "unknownGrandChild")
if !strings.HasPrefix(output, "Error:") {
t.Errorf("Unexpected output: %v", output)
}
if err == nil {
t.Error("Expected error")
}
if err != nil && !strings.HasPrefix(err.Error(), "unknown command") {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != childName {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}
}

func TestExecuteContext(t *testing.T) {
ctx := context.TODO()

Expand Down
2 changes: 1 addition & 1 deletion command_win.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func preExecHook(c *Command) {
time.Sleep(MousetrapDisplayDuration)
} else {
c.Println("Press return to continue...")
fmt.Scanln()
_, _ = fmt.Scanln()
}
os.Exit(1)
}
Expand Down