From 27866a844fb4c1d4828b819e3a24ff70b0f6c2b5 Mon Sep 17 00:00:00 2001 From: "Kevin C. Wells" Date: Tue, 27 Mar 2018 14:20:55 -0700 Subject: [PATCH] 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 --- command.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index 15b81127..131b53ee 100644 --- a/command.go +++ b/command.go @@ -666,6 +666,13 @@ func (c *Command) ArgsLenAtDash() int { 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) { if c == nil { return fmt.Errorf("Called Execute() on a nil Command") @@ -757,7 +764,9 @@ func (c *Command) execute(a []string) (err error) { return err } } else { - c.Run(c, argWoFlags) + if c.Run != nil { + c.Run(c, argWoFlags) + } } if c.PostRunE != nil { if err := c.PostRunE(c, argWoFlags); err != nil {