From b1e90a7943957b51bb96a13b44b844475bcf95c0 Mon Sep 17 00:00:00 2001 From: spf13 Date: Tue, 7 Oct 2014 16:15:19 -0400 Subject: [PATCH] Making prefix matching opt in. --- cobra.go | 4 ++++ cobra_test.go | 15 +++++++++++++++ command.go | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/cobra.go b/cobra.go index 039c1853..e03b4969 100644 --- a/cobra.go +++ b/cobra.go @@ -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) diff --git a/cobra_test.go b/cobra_test.go index 10ac8745..05d18d0c 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -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 { @@ -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 { @@ -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) { diff --git a/command.go b/command.go index 161ed806..1337065d 100644 --- a/command.go +++ b/command.go @@ -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) }