mirror of
https://github.com/spf13/cobra
synced 2025-05-05 04:47:22 +00:00
added pre and post run hooks.
This commit is contained in:
parent
e1e66f7b4e
commit
930089b7da
1 changed files with 25 additions and 0 deletions
25
command.go
25
command.go
|
@ -47,6 +47,12 @@ type Command struct {
|
|||
// Run runs the command.
|
||||
// The args are the arguments after the command name.
|
||||
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 []*Command
|
||||
// Parent Command for this command
|
||||
|
@ -378,7 +384,17 @@ func (c *Command) execute(a []string) (err error) {
|
|||
|
||||
c.preRun()
|
||||
argWoFlags := c.Flags().Args()
|
||||
|
||||
if c.PreRun != nil {
|
||||
c.PreRun(c, argWoFlags)
|
||||
}
|
||||
|
||||
c.Run(c, argWoFlags)
|
||||
|
||||
if c.PostRun != nil {
|
||||
c.PostRun(c, argWoFlags)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@ -466,8 +482,17 @@ func (c *Command) Execute() (err error) {
|
|||
} else {
|
||||
// Only flags left... Call root.Run
|
||||
c.preRun()
|
||||
|
||||
if c.PreRun != nil {
|
||||
c.PreRun(c, argWoFlags)
|
||||
}
|
||||
|
||||
c.Run(c, argWoFlags)
|
||||
err = nil
|
||||
|
||||
if c.PostRun != nil {
|
||||
c.PostRun(c, argWoFlags)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue