Skip to content
Myr

adding support for prefix matching against aliases & names

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by spf13 · committed by spf13 · parent 8816572 · Browse files · 2 files+43 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+43 added−0 removed

  • other:+43 added−0 removed

2 files+43 added−0 removed

modified:cobra_test.go+28 added
206 unmodified lines
207 t.Error("Command didn't parse correctly")208 }209}210211func TestPrefixMatching(t *testing.T) {212 noRRSetupTest("ech times one two")213214 if te != nil || tp != nil {215 t.Error("Wrong command called")216 }217 if tt == nil {218 t.Error("Wrong command called")219 }220 if strings.Join(tt, " ") != "one two" {221 t.Error("Command didn't parse correctly")222 }223}224225func TestAliasPrefixMatching(t *testing.T) {226 noRRSetupTest("sa times one two")227228 if te != nil || tp != nil {229 t.Error("Wrong command called")230 }231 if tt == nil {232 t.Error("Wrong command called")233 }234 if strings.Join(tt, " ") != "one two" {235 t.Error("Command didn't parse correctly")236 }237}238239func TestChildSameName(t *testing.T) {240 c := initializeWithSameName()241 c.AddCommand(cmdPrint, cmdEcho)242 c.SetArgs(strings.Split("print one two", " "))
250 unmodified lines
modified:command.go+15 added
284 unmodified lines
285 innerfind = func(c *Command, args []string) (*Command, []string) {286 if len(args) > 0 && c.HasSubCommands() {287 argsWOflags := stripFlags(args)288 if len(argsWOflags) > 0 {289 matches := make([]*Command, 0)290 for _, cmd := range c.commands {291 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match292 return innerfind(cmd, argsMinusX(args, argsWOflags[0]))293 } else {294 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match295 matches = append(matches, cmd)296 }297 for _, x := range cmd.Aliases {298 if strings.HasPrefix(x, argsWOflags[0]) {299 matches = append(matches, cmd)300 }301 }302 }303 }304305 // only accept a single prefix match - multiple matches would be ambiguous306 if len(matches) == 1 {307 return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))308 }309 }310 }311312 return c, args
452 unmodified lines