From dc6e9ece6f18abe6bae180e13ea58beea916af76 Mon Sep 17 00:00:00 2001 From: Mark Bates Date: Fri, 3 Jun 2016 20:25:52 -0400 Subject: [PATCH] added a flag to disable flags --- command.go | 10 ++++++++++ command_test.go | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/command.go b/command.go index b92c95c..e1517aa 100644 --- a/command.go +++ b/command.go @@ -120,6 +120,9 @@ type Command struct { DisableSuggestions bool // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0 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 @@ -536,7 +539,11 @@ func (c *Command) execute(a []string) (err error) { } c.preRun() + argWoFlags := c.Flags().Args() + if c.DisableFlagParsing { + argWoFlags = a + } for p := c; p != nil; p = p.Parent() { if p.PersistentPreRunE != nil { @@ -1167,6 +1174,9 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) { // ParseFlags parses persistent flag tree & local flags func (c *Command) ParseFlags(args []string) (err error) { + if c.DisableFlagParsing { + return nil + } c.mergePersistentFlags() err = c.Flags().Parse(args) return diff --git a/command_test.go b/command_test.go index 43ed7a3..291947f 100644 --- a/command_test.go +++ b/command_test.go @@ -1,6 +1,7 @@ package cobra import ( + "os" "reflect" "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) + } +}