Skip to content

Commit

Permalink
Making prefix matching opt in.
Browse files Browse the repository at this point in the history
  • Loading branch information
spf13 committed Oct 7, 2014
1 parent c2c23ac commit b1e90a7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import (

var initializers []func()

// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
// Set this to true to enable it
var EnablePrefixMatching bool = false

func OnInitialize(y ...func()) {
for _, x := range y {
initializers = append(initializers, x)
Expand Down
15 changes: 15 additions & 0 deletions cobra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ func TestCommandAlias(t *testing.T) {
}

func TestPrefixMatching(t *testing.T) {
EnablePrefixMatching = true
noRRSetupTest("ech times one two")

if te != nil || tp != nil {
Expand All @@ -220,9 +221,22 @@ func TestPrefixMatching(t *testing.T) {
if strings.Join(tt, " ") != "one two" {
t.Error("Command didn't parse correctly")
}

EnablePrefixMatching = false
}

func TestNoPrefixMatching(t *testing.T) {
EnablePrefixMatching = false

noRRSetupTest("ech times one two")

if !(tt == nil && te == nil && tp == nil) {
t.Error("Wrong command called")
}
}

func TestAliasPrefixMatching(t *testing.T) {
EnablePrefixMatching = true
noRRSetupTest("sa times one two")

if te != nil || tp != nil {
Expand All @@ -234,6 +248,7 @@ func TestAliasPrefixMatching(t *testing.T) {
if strings.Join(tt, " ") != "one two" {
t.Error("Command didn't parse correctly")
}
EnablePrefixMatching = false
}

func TestChildSameName(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ func (c *Command) Find(arrs []string) (*Command, []string, error) {
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]))
} else {
} else if EnablePrefixMatching {
if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match
matches = append(matches, cmd)
}
Expand Down

0 comments on commit b1e90a7

Please sign in to comment.