mirror of
https://github.com/spf13/cobra
synced 2025-05-06 13:27:26 +00:00
Add CancelRun method to Command
This method will nil out the Run and RunE of a command. This can be called from PreRun-style functions to prevent the command from running. Example: A user can check if the environment has been initialized in a PreRun method and, if not, prevent the command from running. Note that this does not nil out any PostRun-style commands, as these are typically used for clean-up and tear-down operations that likely still need to occur. Signed-off-by: Kevin C. Wells <kevin.c.wells@intel.com>
This commit is contained in:
parent
a1f051bc3e
commit
27866a844f
1 changed files with 10 additions and 1 deletions
|
@ -666,6 +666,13 @@ func (c *Command) ArgsLenAtDash() int {
|
||||||
return c.Flags().ArgsLenAtDash()
|
return c.Flags().ArgsLenAtDash()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CancelRun will nil out the Run and RunE of a command. This can be called from
|
||||||
|
// PreRun-style functions to prevent the command from running.
|
||||||
|
func (c *Command) CancelRun() {
|
||||||
|
c.Run = nil
|
||||||
|
c.RunE = nil
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Command) execute(a []string) (err error) {
|
func (c *Command) execute(a []string) (err error) {
|
||||||
if c == nil {
|
if c == nil {
|
||||||
return fmt.Errorf("Called Execute() on a nil Command")
|
return fmt.Errorf("Called Execute() on a nil Command")
|
||||||
|
@ -757,8 +764,10 @@ func (c *Command) execute(a []string) (err error) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if c.Run != nil {
|
||||||
c.Run(c, argWoFlags)
|
c.Run(c, argWoFlags)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if c.PostRunE != nil {
|
if c.PostRunE != nil {
|
||||||
if err := c.PostRunE(c, argWoFlags); err != nil {
|
if err := c.PostRunE(c, argWoFlags); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
Loading…
Add table
Reference in a new issue