mirror of
https://github.com/spf13/cobra
synced 2024-11-25 07:07:15 +00:00
Add support for user specified args validation func (#663)
Add an attribute (which is a function) to Command which is called before any Run steps. If an error is returned the command execution terminates.
This commit is contained in:
parent
4dab30cb33
commit
9191622a46
1 changed files with 9 additions and 0 deletions
|
@ -84,6 +84,7 @@ type Command struct {
|
|||
Version string
|
||||
|
||||
// The *Run functions are executed in the following order:
|
||||
// * ValidateArgsFn()
|
||||
// * PersistentPreRun()
|
||||
// * PreRun()
|
||||
// * Run()
|
||||
|
@ -91,6 +92,8 @@ type Command struct {
|
|||
// * PersistentPostRun()
|
||||
// All functions get the same args, the arguments after the command name.
|
||||
//
|
||||
// ValidateArgsFn: Used to validate the input arguments from the user.
|
||||
ValidateArgsFn 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.
|
||||
|
@ -736,6 +739,12 @@ func (c *Command) execute(a []string) (err error) {
|
|||
return err
|
||||
}
|
||||
|
||||
if c.ValidateArgsFn != nil {
|
||||
if err := c.ValidateArgsFn(c, argWoFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for p := c; p != nil; p = p.Parent() {
|
||||
if p.PersistentPreRunE != nil {
|
||||
if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
|
||||
|
|
Loading…
Reference in a new issue