From 07ad27d2399629313551f54a3614b4574f7ceaee Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Mon, 22 Jun 2015 17:26:11 -0400 Subject: [PATCH] Handle grand children with the same name as the root This fixes a problem where if you had a root command and a grand child with the same name, the parser would break and would not run the grandchild. The code was special casing if the immediate child had the same name, but didn't handle grand-children --- cobra_test.go | 18 ++++++++++++++++++ command.go | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/cobra_test.go b/cobra_test.go index 7e64907f..f181a079 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -378,6 +378,24 @@ func TestChildSameName(t *testing.T) { } } +func TestGrandChildSameName(t *testing.T) { + c := initializeWithSameName() + cmdTimes.AddCommand(cmdPrint) + c.AddCommand(cmdTimes) + c.SetArgs(strings.Split("times print one two", " ")) + c.Execute() + + if te != nil || tt != nil { + t.Error("Wrong command called") + } + if tp == nil { + t.Error("Wrong command called") + } + if strings.Join(tp, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + func TestFlagLong(t *testing.T) { noRRSetupTest("echo --intone=13 something here") diff --git a/command.go b/command.go index 8375aa56..141cfab1 100644 --- a/command.go +++ b/command.go @@ -423,8 +423,9 @@ func (c *Command) Find(args []string) (*Command, []string, error) { commandFound, a := innerfind(c, args) // If we matched on the root, but we asked for a subcommand, return an error - if commandFound.Name() == c.Name() && len(stripFlags(args, c)) > 0 && commandFound.Name() != args[0] { - return nil, a, fmt.Errorf("unknown command %q", stripFlags(args, c)[0]) + argsWOflags := stripFlags(a, commandFound) + if commandFound == c && len(argsWOflags) > 0 { + return nil, a, fmt.Errorf("unknown command %q", argsWOflags[0]) } return commandFound, a, nil