From b027180f68d2dd09ce6a5b64a4e03b9413c8421e Mon Sep 17 00:00:00 2001 From: Martin Milata Date: Tue, 11 Oct 2016 13:53:10 +0200 Subject: Fix square bracket handling in string_array Same issue fixed in 13e924de for string_slice. --- string_array.go | 3 +-- string_array_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/string_array.go b/string_array.go index f320f2e..93b4e43 100644 --- a/string_array.go +++ b/string_array.go @@ -2,7 +2,6 @@ package pflag import ( "fmt" - "strings" ) var _ = fmt.Fprint @@ -40,7 +39,7 @@ func (s *stringArrayValue) String() string { } func stringArrayConv(sval string) (interface{}, error) { - sval = strings.Trim(sval, "[]") + sval = sval[1 : len(sval)-1] // An empty string would cause a array with one (empty) string if len(sval) == 0 { return []string{}, nil diff --git a/string_array_test.go b/string_array_test.go index 3e3eb74..1ceac8c 100644 --- a/string_array_test.go +++ b/string_array_test.go @@ -192,3 +192,42 @@ func TestSAWithSpecialChar(t *testing.T) { } } } + +func TestSAWithSquareBrackets(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + + in := []string{"][]-[", "[a-z]", "[a-z]+"} + expected := []string{"][]-[", "[a-z]", "[a-z]+"} + argfmt := "--sa=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + arg3 := fmt.Sprintf(argfmt, in[2]) + err := f.Parse([]string{arg1, arg2, arg3}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(sa) { + t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) + } + for i, v := range sa { + if expected[i] != v { + t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) + } + } +} -- cgit v1.2.3