added pre and post run hooks.

This commit is contained in:
Alexander Thaller 2015-02-09 23:44:14 +01:00
parent e1e66f7b4e
commit 930089b7da

View file

@ -47,6 +47,12 @@ type Command struct {
// Run runs the command. // Run runs the command.
// The args are the arguments after the command name. // The args are the arguments after the command name.
Run func(cmd *Command, args []string) Run func(cmd *Command, args []string)
// PreRun runs the command after the flags are parsed and before run.
// The args are the arguments after the command name.
PreRun func(cmd *Command, args []string)
// PostRun runs the command after run.
// The args are the arguments after the command name.
PostRun func(cmd *Command, args []string)
// Commands is the list of commands supported by this program. // Commands is the list of commands supported by this program.
commands []*Command commands []*Command
// Parent Command for this command // Parent Command for this command
@ -378,7 +384,17 @@ func (c *Command) execute(a []string) (err error) {
c.preRun() c.preRun()
argWoFlags := c.Flags().Args() argWoFlags := c.Flags().Args()
if c.PreRun != nil {
c.PreRun(c, argWoFlags)
}
c.Run(c, argWoFlags) c.Run(c, argWoFlags)
if c.PostRun != nil {
c.PostRun(c, argWoFlags)
}
return nil return nil
} }
} }
@ -466,8 +482,17 @@ func (c *Command) Execute() (err error) {
} else { } else {
// Only flags left... Call root.Run // Only flags left... Call root.Run
c.preRun() c.preRun()
if c.PreRun != nil {
c.PreRun(c, argWoFlags)
}
c.Run(c, argWoFlags) c.Run(c, argWoFlags)
err = nil err = nil
if c.PostRun != nil {
c.PostRun(c, argWoFlags)
}
} }
} }
} }