Merge pull request #289 from markbates/disable-flags

added a flag to disable flags
This commit is contained in:
Eric Paris 2016-06-04 00:47:32 -04:00
commit f447048345
2 changed files with 31 additions and 0 deletions

View File

@ -120,6 +120,9 @@ type Command struct {
DisableSuggestions bool DisableSuggestions bool
// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
SuggestionsMinimumDistance int SuggestionsMinimumDistance int
// Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
DisableFlagParsing bool
} }
// os.Args[1:] by default, if desired, can be overridden // os.Args[1:] by default, if desired, can be overridden
@ -536,7 +539,11 @@ func (c *Command) execute(a []string) (err error) {
} }
c.preRun() c.preRun()
argWoFlags := c.Flags().Args() argWoFlags := c.Flags().Args()
if c.DisableFlagParsing {
argWoFlags = a
}
for p := c; p != nil; p = p.Parent() { for p := c; p != nil; p = p.Parent() {
if p.PersistentPreRunE != nil { if p.PersistentPreRunE != nil {
@ -1167,6 +1174,9 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
// ParseFlags parses persistent flag tree & local flags // ParseFlags parses persistent flag tree & local flags
func (c *Command) ParseFlags(args []string) (err error) { func (c *Command) ParseFlags(args []string) (err error) {
if c.DisableFlagParsing {
return nil
}
c.mergePersistentFlags() c.mergePersistentFlags()
err = c.Flags().Parse(args) err = c.Flags().Parse(args)
return return

View File

@ -1,6 +1,7 @@
package cobra package cobra
import ( import (
"os"
"reflect" "reflect"
"testing" "testing"
) )
@ -112,3 +113,23 @@ func TestStripFlags(t *testing.T) {
} }
} }
} }
func Test_DisableFlagParsing(t *testing.T) {
as := []string{"-v", "-race", "-file", "foo.go"}
targs := []string{}
cmdPrint := &Command{
DisableFlagParsing: true,
Run: func(cmd *Command, args []string) {
targs = args
},
}
osargs := []string{"cmd"}
os.Args = append(osargs, as...)
err := cmdPrint.Execute()
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(as, targs) {
t.Errorf("expected: %v, got: %v", as, targs)
}
}