mirror of
https://github.com/spf13/cobra
synced 2024-12-28 07:17:06 +00:00
added persistent pre/post commands.
This commit is contained in:
parent
2df64026ba
commit
fbce60cc56
1 changed files with 21 additions and 1 deletions
22
command.go
22
command.go
|
@ -65,6 +65,10 @@ type Command struct {
|
|||
// PostRun runs the command after run.
|
||||
// The args are the arguments after the command name.
|
||||
PostRun func(cmd *Command, args []string)
|
||||
// PreRun which children of this command will inherit.
|
||||
PersistentPreRun func(cmd *Command, args []string)
|
||||
// PostRun which children of this command will inherit.
|
||||
PersistentPostRun func(cmd *Command, args []string)
|
||||
// Commands is the list of commands supported by this program.
|
||||
commands []*Command
|
||||
// Parent Command for this command
|
||||
|
@ -455,6 +459,9 @@ func (c *Command) execute(a []string) (err error) {
|
|||
c.preRun()
|
||||
argWoFlags := c.Flags().Args()
|
||||
|
||||
if c.PersistentPreRun != nil {
|
||||
c.PersistentPreRun(c, argWoFlags)
|
||||
}
|
||||
if c.PreRun != nil {
|
||||
c.PreRun(c, argWoFlags)
|
||||
}
|
||||
|
@ -464,6 +471,9 @@ func (c *Command) execute(a []string) (err error) {
|
|||
if c.PostRun != nil {
|
||||
c.PostRun(c, argWoFlags)
|
||||
}
|
||||
if c.PersistentPostRun != nil {
|
||||
c.PersistentPostRun(c, argWoFlags)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -545,7 +555,9 @@ func (c *Command) initHelp() {
|
|||
Short: "Help about any command",
|
||||
Long: `Help provides help for any command in the application.
|
||||
Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
||||
Run: c.HelpFunc(),
|
||||
Run: c.HelpFunc(),
|
||||
PersistentPreRun: func(cmd *Command, args []string) {},
|
||||
PersistentPostRun: func(cmd *Command, args []string) {},
|
||||
}
|
||||
}
|
||||
c.AddCommand(c.helpCommand)
|
||||
|
@ -585,6 +597,14 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
c.commandsMaxNameLen = nameLen
|
||||
}
|
||||
c.commands = append(c.commands, x)
|
||||
|
||||
// Pass on peristent pre/post functions to children
|
||||
if x.PersistentPreRun == nil {
|
||||
x.PersistentPreRun = c.PersistentPreRun
|
||||
}
|
||||
if x.PersistentPostRun == nil {
|
||||
x.PersistentPostRun = c.PersistentPostRun
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue