From 9191622a467b200ac7998abd72b973258d96505d Mon Sep 17 00:00:00 2001 From: Sion Williams Date: Thu, 5 Apr 2018 19:12:12 +0100 Subject: [PATCH] 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. --- command.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/command.go b/command.go index 34d1bf36..733c1e7f 100644 --- a/command.go +++ b/command.go @@ -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 {