mirror of
https://github.com/spf13/cobra
synced 2025-05-07 22:07:23 +00:00
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
This commit is contained in:
parent
b95db644ed
commit
dd7754f40b
1 changed files with 13 additions and 0 deletions
13
command.go
13
command.go
|
@ -90,6 +90,7 @@ type Command struct {
|
||||||
Version string
|
Version string
|
||||||
|
|
||||||
// The *Run functions are executed in the following order:
|
// The *Run functions are executed in the following order:
|
||||||
|
// * AdditionalSetup()
|
||||||
// * PersistentPreRun()
|
// * PersistentPreRun()
|
||||||
// * PreRun()
|
// * PreRun()
|
||||||
// * Run()
|
// * Run()
|
||||||
|
@ -97,6 +98,10 @@ type Command struct {
|
||||||
// * PersistentPostRun()
|
// * PersistentPostRun()
|
||||||
// All functions get the same args, the arguments after the command name.
|
// 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: children of this command will inherit and execute.
|
||||||
PersistentPreRun func(cmd *Command, args []string)
|
PersistentPreRun func(cmd *Command, args []string)
|
||||||
// PersistentPreRunE: PersistentPreRun but returns an error.
|
// 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)
|
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
|
// initialize help and version flag at the last point possible to allow for user
|
||||||
// overriding
|
// overriding
|
||||||
c.InitDefaultHelpFlag()
|
c.InitDefaultHelpFlag()
|
||||||
|
|
Loading…
Add table
Reference in a new issue