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:
Kevin C. Wells 2018-03-27 14:20:55 -07:00
parent a1f051bc3e
commit 27866a844f

View file

@ -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,7 +764,9 @@ func (c *Command) execute(a []string) (err error) {
return err return err
} }
} else { } else {
c.Run(c, argWoFlags) if c.Run != nil {
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 {