mirror of https://github.com/spf13/cobra.git
adding support for prefix matching against aliases & names
This commit is contained in:
parent
881657297e
commit
c2c23ac0bd
|
@ -208,6 +208,34 @@ func TestCommandAlias(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPrefixMatching(t *testing.T) {
|
||||||
|
noRRSetupTest("ech times one two")
|
||||||
|
|
||||||
|
if te != nil || tp != nil {
|
||||||
|
t.Error("Wrong command called")
|
||||||
|
}
|
||||||
|
if tt == nil {
|
||||||
|
t.Error("Wrong command called")
|
||||||
|
}
|
||||||
|
if strings.Join(tt, " ") != "one two" {
|
||||||
|
t.Error("Command didn't parse correctly")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAliasPrefixMatching(t *testing.T) {
|
||||||
|
noRRSetupTest("sa times one two")
|
||||||
|
|
||||||
|
if te != nil || tp != nil {
|
||||||
|
t.Error("Wrong command called")
|
||||||
|
}
|
||||||
|
if tt == nil {
|
||||||
|
t.Error("Wrong command called")
|
||||||
|
}
|
||||||
|
if strings.Join(tt, " ") != "one two" {
|
||||||
|
t.Error("Command didn't parse correctly")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChildSameName(t *testing.T) {
|
func TestChildSameName(t *testing.T) {
|
||||||
c := initializeWithSameName()
|
c := initializeWithSameName()
|
||||||
c.AddCommand(cmdPrint, cmdEcho)
|
c.AddCommand(cmdPrint, cmdEcho)
|
||||||
|
|
15
command.go
15
command.go
|
@ -286,11 +286,26 @@ func (c *Command) Find(arrs []string) (*Command, []string, error) {
|
||||||
if len(args) > 0 && c.HasSubCommands() {
|
if len(args) > 0 && c.HasSubCommands() {
|
||||||
argsWOflags := stripFlags(args)
|
argsWOflags := stripFlags(args)
|
||||||
if len(argsWOflags) > 0 {
|
if len(argsWOflags) > 0 {
|
||||||
|
matches := make([]*Command, 0)
|
||||||
for _, cmd := range c.commands {
|
for _, cmd := range c.commands {
|
||||||
if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match
|
if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match
|
||||||
return innerfind(cmd, argsMinusX(args, argsWOflags[0]))
|
return innerfind(cmd, argsMinusX(args, argsWOflags[0]))
|
||||||
|
} else {
|
||||||
|
if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match
|
||||||
|
matches = append(matches, cmd)
|
||||||
|
}
|
||||||
|
for _, x := range cmd.Aliases {
|
||||||
|
if strings.HasPrefix(x, argsWOflags[0]) {
|
||||||
|
matches = append(matches, cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// only accept a single prefix match - multiple matches would be ambiguous
|
||||||
|
if len(matches) == 1 {
|
||||||
|
return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue