From dd7754f40b12113ad44278b33a3abc80499e071c Mon Sep 17 00:00:00 2001 From: Richard Case <198425+richardcase@users.noreply.github.com> Date: Fri, 17 Jul 2020 14:17:29 +0100 Subject: [PATCH] feat: added additionalsetup hook Added a hook point where you can add a function to the command to do any additional setup before flags are parsed. Useful for any dynamic flags --- command.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/command.go b/command.go index 5f1caccc..c00ea6be 100644 --- a/command.go +++ b/command.go @@ -90,6 +90,7 @@ type Command struct { Version string // The *Run functions are executed in the following order: + // * AdditionalSetup() // * PersistentPreRun() // * PreRun() // * Run() @@ -97,6 +98,10 @@ type Command struct { // * PersistentPostRun() // All functions get the same args, the arguments after the command name. // + // AdditionalSetup: If you require any additional setup on the command prior to flag parsing + AdditionalSetup func(cmd *Command, args []string) + // AdditionalSetupE: AdditionalSetup but returns an error + AdditionalSetupE func(cmd *Command, args []string) error // PersistentPreRun: children of this command will inherit and execute. PersistentPreRun func(cmd *Command, args []string) // PersistentPreRunE: PersistentPreRun but returns an error. @@ -761,6 +766,14 @@ func (c *Command) execute(a []string) (err error) { c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) } + if c.AdditionalSetupE != nil { + if err := c.AdditionalSetupE(c, c.Flags().Args()); err != nil { + return err + } + } else if c.AdditionalSetup != nil { + c.AdditionalSetup(c, c.flags.Args()) + } + // initialize help and version flag at the last point possible to allow for user // overriding c.InitDefaultHelpFlag()