Skip to content

Commit

Permalink
Handle single string=>string flags without quotes (#179)
Browse files Browse the repository at this point in the history
OK: --f1 "a=5,6" --f2 b=3,4 --f3 "c=5,6",d=7
Not OK: --f4 c="5,6"
  • Loading branch information
tamalsaha authored and eparis committed Aug 21, 2018
1 parent 947b89b commit d929dcb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
19 changes: 15 additions & 4 deletions string_to_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,22 @@ func newStringToStringValue(val map[string]string, p *map[string]string) *string

// Format: a=1,b=2
func (s *stringToStringValue) Set(val string) error {
r := csv.NewReader(strings.NewReader(val))
ss, err := r.Read()
if err != nil {
return err
var ss []string
n := strings.Count(val, "=")
switch n {
case 0:
return fmt.Errorf("%s must be formatted as key=value", val)
case 1:
ss = append(ss, strings.Trim(val, `"`))
default:
r := csv.NewReader(strings.NewReader(val))
var err error
ss, err = r.Read()
if err != nil {
return err
}
}

out := make(map[string]string, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
Expand Down
14 changes: 9 additions & 5 deletions string_to_string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,20 @@ func TestS2SCalledTwice(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSet(&s2s)

in := []string{"a=1,b=2", "b=3", `"e=5,6"`, `f="7,8"`}
in := []string{"a=1,b=2", "b=3", `"e=5,6"`, `f=7,8`}
expected := map[string]string{"a": "1", "b": "3", "e": "5,6", "f": "7,8"}
argfmt := "--s2s=%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})
arg0 := fmt.Sprintf(argfmt, in[0])
arg1 := fmt.Sprintf(argfmt, in[1])
arg2 := fmt.Sprintf(argfmt, in[2])
arg3 := fmt.Sprintf(argfmt, in[3])
err := f.Parse([]string{arg0, arg1, arg2, arg3})
if err != nil {
t.Fatal("expected no error; got", err)
}
if len(s2s) != len(expected) {
t.Fatalf("expected %d flags; got %d flags", len(expected), len(s2s))
}
for i, v := range s2s {
if expected[i] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s", i, expected[i], v)
Expand Down

0 comments on commit d929dcb

Please sign in to comment.