1
0
Fork 0
mirror of https://github.com/spf13/cobra synced 2025-04-11 09:17:18 +00:00
This commit is contained in:
Michael Vogt 2025-03-21 21:50:59 -04:00 committed by GitHub
commit 75255bbd6b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 27 additions and 3 deletions

15
args.go
View file

@ -21,6 +21,17 @@ import (
type PositionalArgs func(cmd *Command, args []string) error
// UnknownCommandError is returned for unknown command
type UnknownCommandError struct {
unknownCmd string
cmdPath string
suggestions string
}
func (e UnknownCommandError) Error() string {
return fmt.Sprintf("unknown command %q for %q%s", e.unknownCmd, e.cmdPath, e.suggestions)
}
// legacyArgs validation has the following behaviour:
// - root commands with no subcommands can take arbitrary arguments
// - root commands with subcommands will do subcommand validity checking
@ -33,7 +44,7 @@ func legacyArgs(cmd *Command, args []string) error {
// root command with subcommands, do subcommand checking.
if !cmd.HasParent() && len(args) > 0 {
return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
return UnknownCommandError{args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])}
}
return nil
}
@ -41,7 +52,7 @@ 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 {
return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
return UnknownCommandError{args[0], cmd.CommandPath(), ""}
}
return nil
}

View file

@ -147,7 +147,10 @@ func TestRootExecuteUnknownCommand(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, _ := executeCommand(rootCmd, "unknown")
output, err := executeCommand(rootCmd, "unknown")
if _, ok := err.(UnknownCommandError); !ok {
t.Errorf("Expected:\n %T\nGot:\n %T\n", err, UnknownCommandError{})
}
expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"
@ -156,6 +159,16 @@ func TestRootExecuteUnknownCommand(t *testing.T) {
}
}
func TestRootFindUnknownCommandErrorType(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
_, _, err := rootCmd.Find([]string{"unknown"})
if _, ok := err.(UnknownCommandError); !ok {
t.Errorf("Expected:\n %T\nGot:\n %T\n", err, UnknownCommandError{})
}
}
func TestSubcommandExecuteC(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}