From 36aee64abe8c011e55572b30f0152fd143a32515 Mon Sep 17 00:00:00 2001 From: deads2k Date: Fri, 24 Apr 2015 11:39:11 -0400 Subject: [PATCH] prevent removal of valid arguments --- cobra_test.go | 26 ++++++++++++++++++++++++++ command.go | 21 ++++++++++++--------- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/cobra_test.go b/cobra_test.go index a258508..6feb8e5 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -483,6 +483,32 @@ func TestInvalidSubCommandFlags(t *testing.T) { } +func TestSubCommandArgEvaluation(t *testing.T) { + cmd := initializeWithRootCmd() + + first := &Command{ + Use: "first", + Run: func(cmd *Command, args []string) { + }, + } + cmd.AddCommand(first) + + second := &Command{ + Use: "second", + Run: func(cmd *Command, args []string) { + fmt.Fprintf(cmd.Out(), "%v", args) + }, + } + first.AddCommand(second) + + result := simpleTester(cmd, "first second first third") + + expectedOutput := fmt.Sprintf("%v", []string{"first third"}) + if result.Output != expectedOutput { + t.Errorf("exptected %v, got %v", expectedOutput, result.Output) + } +} + func TestPersistentFlags(t *testing.T) { fullSetupTest("echo -s something -p more here") diff --git a/command.go b/command.go index 59654c2..ef802c6 100644 --- a/command.go +++ b/command.go @@ -328,15 +328,18 @@ func stripFlags(args []string, c *Command) []string { return commands } -func argsMinusX(args []string, x string) []string { - newargs := []string{} - - for _, y := range args { - if x != y { - newargs = append(newargs, y) +// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like +// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). +func argsMinusFirstX(args []string, x string) []string { + for i, y := range args { + if x == y { + ret := []string{} + ret = append(ret, args[:i]...) + ret = append(ret, args[i+1:]...) + return ret } } - return newargs + return args } // find the target command given the args and command tree @@ -359,7 +362,7 @@ func (c *Command) Find(arrs []string) (*Command, []string, error) { matches := make([]*Command, 0) for _, cmd := range c.commands { if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match - return innerfind(cmd, argsMinusX(args, argsWOflags[0])) + return innerfind(cmd, argsMinusFirstX(args, argsWOflags[0])) } else if EnablePrefixMatching { if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match matches = append(matches, cmd) @@ -374,7 +377,7 @@ func (c *Command) Find(arrs []string) (*Command, []string, error) { // only accept a single prefix match - multiple matches would be ambiguous if len(matches) == 1 { - return innerfind(matches[0], argsMinusX(args, argsWOflags[0])) + return innerfind(matches[0], argsMinusFirstX(args, argsWOflags[0])) } } }