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:
Sion Williams 2018-04-05 19:12:12 +01:00
parent 4dab30cb33
commit 9191622a46

View file

@ -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 {