From 37299d4e5a50613fac38c3d50ef32b1c92ac698c Mon Sep 17 00:00:00 2001 From: Chris Winslett Date: Sun, 30 Mar 2014 20:40:46 -0700 Subject: [PATCH] Customizable command not found function --- app.go | 2 ++ app_test.go | 23 +++++++++++++++++++++++ help.go | 6 +++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app.go b/app.go index a614236..a8fd0e6 100644 --- a/app.go +++ b/app.go @@ -25,6 +25,8 @@ type App struct { Before func(context *Context) error // The action to execute when no subcommands are specified Action func(context *Context) + // Execute this function if the proper command cannot be found + CommandNotFound func(context *Context, command string) // Compilation date Compiled time.Time // Author diff --git a/app_test.go b/app_test.go index 4e94f9e..667c0ed 100644 --- a/app_test.go +++ b/app_test.go @@ -278,3 +278,26 @@ func TestAppHelpPrinter(t *testing.T) { t.Errorf("Help printer expected to be called, but was not") } } + +func TestAppCommandNotFound(t *testing.T) { + beforeRun, subcommandRun := false, false + app := cli.NewApp() + + app.CommandNotFound = func(c *cli.Context, command string) { + beforeRun = true + } + + app.Commands = []cli.Command{ + cli.Command{ + Name: "bar", + Action: func(c *cli.Context) { + subcommandRun = true + }, + }, + } + + app.Run([]string{"command", "foo"}) + + expect(t, beforeRun, true) + expect(t, subcommandRun, false) +} diff --git a/help.go b/help.go index 094d01d..d725070 100644 --- a/help.go +++ b/help.go @@ -73,7 +73,11 @@ func ShowCommandHelp(c *Context, command string) { } } - fmt.Printf("No help topic for '%v'\n", command) + if c.App.CommandNotFound != nil { + c.App.CommandNotFound(c, command) + } else { + fmt.Printf("No help topic for '%v'\n", command) + } } // Prints the version number of the App