mirror of
https://github.com/spf13/cobra
synced 2025-05-06 05:17:21 +00:00
issue#798 support initializers that return error
This commit is contained in:
parent
d2d81d9a96
commit
4cf9a0c444
2 changed files with 21 additions and 0 deletions
7
cobra.go
7
cobra.go
|
@ -37,6 +37,7 @@ var templateFuncs = template.FuncMap{
|
||||||
}
|
}
|
||||||
|
|
||||||
var initializers []func()
|
var initializers []func()
|
||||||
|
var initializersWithError []func() error
|
||||||
|
|
||||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||||
// to automatically enable in CLI tools.
|
// to automatically enable in CLI tools.
|
||||||
|
@ -76,6 +77,12 @@ func OnInitialize(y ...func()) {
|
||||||
initializers = append(initializers, y...)
|
initializers = append(initializers, y...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OnInitializeE sets the passed functions to be run when each command's
|
||||||
|
// Execute method is called.
|
||||||
|
func OnInitializeE(y ...func() error) {
|
||||||
|
initializers = append(initializers, y...)
|
||||||
|
}
|
||||||
|
|
||||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||||
|
|
||||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||||
|
|
14
command.go
14
command.go
|
@ -727,6 +727,11 @@ func (c *Command) execute(a []string) (err error) {
|
||||||
|
|
||||||
c.preRun()
|
c.preRun()
|
||||||
|
|
||||||
|
err = c.preRunE()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
argWoFlags := c.Flags().Args()
|
argWoFlags := c.Flags().Args()
|
||||||
if c.DisableFlagParsing {
|
if c.DisableFlagParsing {
|
||||||
argWoFlags = a
|
argWoFlags = a
|
||||||
|
@ -793,6 +798,15 @@ func (c *Command) preRun() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Command) preRunE() {
|
||||||
|
for _, x := range initializersWithError {
|
||||||
|
err := x()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Execute uses the args (os.Args[1:] by default)
|
// Execute uses the args (os.Args[1:] by default)
|
||||||
// and run through the command tree finding appropriate matches
|
// and run through the command tree finding appropriate matches
|
||||||
// for commands and then corresponding flags.
|
// for commands and then corresponding flags.
|
||||||
|
|
Loading…
Add table
Reference in a new issue