Add Parser.CommandHandler to run before executing a command
Fixes #165.
diff --git a/parser.go b/parser.go
index f9e07ee..91b62e9 100644
--- a/parser.go
+++ b/parser.go
@@ -42,6 +42,13 @@
// You can override this default behavior by specifying a custom CompletionHandler.
CompletionHandler func(items []Completion)
+ // CommandHandler is a function that gets called to handle execution of a
+ // command. By default, the command will simply be executed. This can be
+ // 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.
+ CommandHandler func(command Commander, args []string) error
+
internalError error
}
@@ -298,7 +305,11 @@
} else if len(s.command.commands) != 0 && !s.command.SubcommandsOptional {
reterr = s.estimateCommand()
} else if cmd, ok := s.command.data.(Commander); ok {
- reterr = cmd.Execute(s.retargs)
+ if p.CommandHandler != nil {
+ reterr = p.CommandHandler(cmd, s.retargs)
+ } else {
+ reterr = cmd.Execute(s.retargs)
+ }
}
if reterr != nil {
diff --git a/parser_test.go b/parser_test.go
index 32afc69..a354946 100644
--- a/parser_test.go
+++ b/parser_test.go
@@ -494,7 +494,47 @@
}
assertParseSuccess(t, &opts, "-v")
+
if !opts.V {
t.Errorf("Expected V to be true")
}
}
+
+type command struct {
+}
+
+func (c *command) Execute(args []string) error {
+ return nil
+}
+
+func TestCommandHandler(t *testing.T) {
+ var opts = struct {
+ Value bool `short:"v"`
+
+ Command command `command:"cmd"`
+ }{}
+
+ parser := NewParser(&opts, Default&^PrintErrors)
+
+ var executedCommand Commander
+ var executedArgs []string
+
+ parser.CommandHandler = func (command Commander, args []string) error {
+ executedCommand = command
+ executedArgs = args
+
+ return nil
+ }
+
+ _, err := parser.ParseArgs([]string{"cmd", "arg1", "arg2"})
+
+ if err != nil {
+ t.Fatalf("Unexpected parse error: %s", err)
+ }
+
+ if executedCommand == nil {
+ t.Errorf("Expected command handler to be executed")
+ }
+
+ assertStringArray(t, executedArgs, []string{"arg1", "arg2"})
+}