Execute CommandHandler also if there is no command to run
diff --git a/parser.go b/parser.go
index 91b62e9..2290941 100644
--- a/parser.go
+++ b/parser.go
@@ -47,6 +47,9 @@
// overridden to perform certain actions (such as applying global flags)
// just before the command is executed. Note that if you override the
// handler it is your responsibility to call the command.Execute function.
+ //
+ // The command passed into CommandHandler may be nil in case there is no
+ // command to be executed when parsing has finished.
CommandHandler func(command Commander, args []string) error
internalError error
@@ -310,6 +313,8 @@
} else {
reterr = cmd.Execute(s.retargs)
}
+ } else if p.CommandHandler != nil {
+ reterr = p.CommandHandler(nil, s.retargs)
}
if reterr != nil {
diff --git a/parser_test.go b/parser_test.go
index a354946..4f3b31c 100644
--- a/parser_test.go
+++ b/parser_test.go
@@ -507,6 +507,45 @@
return nil
}
+func TestCommandHandlerNoCommand(t *testing.T) {
+ var opts = struct {
+ Value bool `short:"v"`
+ }{}
+
+ parser := NewParser(&opts, Default&^PrintErrors)
+
+ var executedCommand Commander
+ var executedArgs []string
+
+ executed := false
+
+ parser.CommandHandler = func (command Commander, args []string) error {
+ executed = true
+
+ executedCommand = command
+ executedArgs = args
+
+ return nil
+ }
+
+ _, err := parser.ParseArgs([]string{"arg1", "arg2"})
+
+ if err != nil {
+ t.Fatalf("Unexpected parse error: %s", err)
+ }
+
+ if !executed {
+ t.Errorf("Expected command handler to be executed")
+ }
+
+ if executedCommand != nil {
+ t.Errorf("Did not exect an executed command")
+ }
+
+ assertStringArray(t, executedArgs, []string{"arg1", "arg2"})
+}
+
+
func TestCommandHandler(t *testing.T) {
var opts = struct {
Value bool `short:"v"`
@@ -519,7 +558,11 @@
var executedCommand Commander
var executedArgs []string
+ executed := false
+
parser.CommandHandler = func (command Commander, args []string) error {
+ executed = true
+
executedCommand = command
executedArgs = args
@@ -532,6 +575,10 @@
t.Fatalf("Unexpected parse error: %s", err)
}
+ if !executed {
+ t.Errorf("Expected command handler to be executed")
+ }
+
if executedCommand == nil {
t.Errorf("Expected command handler to be executed")
}