mirror of
https://github.com/spf13/cobra
synced 2025-05-06 13:27:26 +00:00
Added ability to do custom stuff when command is not found
This commit is contained in:
parent
19cf35ea77
commit
0c47c471c4
2 changed files with 22 additions and 2 deletions
11
command.go
11
command.go
|
@ -114,6 +114,8 @@ type Command struct {
|
||||||
PersistentPostRun func(cmd *Command, args []string)
|
PersistentPostRun func(cmd *Command, args []string)
|
||||||
// PersistentPostRunE: PersistentPostRun but returns an error.
|
// PersistentPostRunE: PersistentPostRun but returns an error.
|
||||||
PersistentPostRunE func(cmd *Command, args []string) error
|
PersistentPostRunE func(cmd *Command, args []string) error
|
||||||
|
// OnCommandNotFound: custom CommandNotFound handler
|
||||||
|
OnCommandNotFound func (cmd *Command, args []string)
|
||||||
|
|
||||||
// SilenceErrors is an option to quiet errors down stream.
|
// SilenceErrors is an option to quiet errors down stream.
|
||||||
SilenceErrors bool
|
SilenceErrors bool
|
||||||
|
@ -903,8 +905,13 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||||
c = cmd
|
c = cmd
|
||||||
}
|
}
|
||||||
if !c.SilenceErrors {
|
if !c.SilenceErrors {
|
||||||
c.Println("Error:", err.Error())
|
if c.OnCommandNotFound != nil {
|
||||||
c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
|
c.OnCommandNotFound(c, args)
|
||||||
|
return c, nil
|
||||||
|
} else {
|
||||||
|
c.Println("Error:", err.Error())
|
||||||
|
c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
|
@ -147,6 +147,19 @@ func TestRootUnknownCommandSilenced(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRootUnknownCommandCustomHandler(t *testing.T) {
|
||||||
|
rootCmd := &Command{Use: "root", Run: emptyRun}
|
||||||
|
rootCmd.OnCommandNotFound = func(cmd *Command, args []string) {
|
||||||
|
cmd.Println("Command not found. Sorry buddy :(")
|
||||||
|
}
|
||||||
|
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
|
||||||
|
|
||||||
|
output, _ := executeCommand(rootCmd, "unknown")
|
||||||
|
if output != "Command not found. Sorry buddy :(\n" {
|
||||||
|
t.Errorf("Expected custom output message, because of custom CommandNotFound handler.\nGot:\n %q\n", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCommandAlias(t *testing.T) {
|
func TestCommandAlias(t *testing.T) {
|
||||||
var timesCmdArgs []string
|
var timesCmdArgs []string
|
||||||
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
||||||
|
|
Loading…
Add table
Reference in a new issue