Added ability to do custom stuff when command is not found

This commit is contained in:
Milan Jovanovic 2019-09-19 12:48:23 +01:00
parent 19cf35ea77
commit 0c47c471c4
2 changed files with 22 additions and 2 deletions

View file

@ -114,6 +114,8 @@ type Command struct {
PersistentPostRun func(cmd *Command, args []string)
// PersistentPostRunE: PersistentPostRun but returns an 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 bool
@ -903,9 +905,14 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
c = cmd
}
if !c.SilenceErrors {
if c.OnCommandNotFound != nil {
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
}

View file

@ -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) {
var timesCmdArgs []string
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}