Skip to content

Commit

Permalink
Trim off blank values of slice and map arguments (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
itzg authored Oct 28, 2023
1 parent c0bd140 commit 3af1ed6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
26 changes: 20 additions & 6 deletions flagset.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,17 @@ func (s *strSliceVar) Set(val string) error {

func parseStringSlice(val string) []string {
splitter := regexp.MustCompile("[\n,]")
return splitter.Split(val, -1)
parts := splitter.Split(val, -1)

// trim out blank parts
result := make([]string, 0, len(parts))
for _, s := range parts {
s = strings.TrimSpace(s)
if s != "" {
result = append(result, s)
}
}
return result
}

type strToStrMapVar struct {
Expand Down Expand Up @@ -702,11 +712,15 @@ func parseStringToStringMap(val string) map[string]string {

pairs := splitter.Split(val, -1)
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) == 2 {
result[kv[0]] = kv[1]
} else {
result[kv[0]] = ""
pair = strings.TrimSpace(pair)

if pair != "" {
kv := strings.SplitN(pair, "=", 2)
if len(kv) == 2 {
result[kv[0]] = kv[1]
} else {
result[kv[0]] = ""
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion flagset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ func TestStringToStringMap(t *testing.T) {
err = flagset.Parse([]string{"--no-default",
"k1=v1",
"--no-default",
"k2=v2,k3=v3\nk4=v4",
"k2=v2,k3=v3\nk4=v4\n",
})
require.NoError(t, err)

Expand Down

0 comments on commit 3af1ed6

Please sign in to comment.