Skip to content

Commit

Permalink
Add a proper processing for pflag.StringArray
Browse files Browse the repository at this point in the history
  • Loading branch information
Felixoid authored and sagikazarmark committed Jun 25, 2021
1 parent 3fcad43 commit bd03865
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
4 changes: 2 additions & 2 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1153,7 +1153,7 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
return cast.ToInt(flag.ValueString())
case "bool":
return cast.ToBool(flag.ValueString())
case "stringSlice":
case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
Expand Down Expand Up @@ -1232,7 +1232,7 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
return cast.ToInt(flag.ValueString())
case "bool":
return cast.ToBool(flag.ValueString())
case "stringSlice":
case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
Expand Down
48 changes: 48 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,54 @@ func TestBindPFlagsStringSlice(t *testing.T) {
}
}

// nolint: dupl
func TestBindPFlagsStringArray(t *testing.T) {
tests := []struct {
Expected []string
Value string
}{
{[]string{}, ""},
{[]string{"jeden"}, "jeden"},
{[]string{"dwa,trzy"}, "dwa,trzy"},
{[]string{"cztery,\"piec , szesc\""}, "cztery,\"piec , szesc\""},
}

v := New() // create independent Viper object
defaultVal := []string{"default"}
v.SetDefault("stringarray", defaultVal)

for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringArray("stringarray", testValue.Expected, "test")

for _, changed := range []bool{true, false} {
flagSet.VisitAll(func(f *pflag.Flag) {
f.Value.Set(testValue.Value)
f.Changed = changed
})

err := v.BindPFlags(flagSet)
if err != nil {
t.Fatalf("error binding flag set, %v", err)
}

type TestStr struct {
StringArray []string
}
val := &TestStr{}
if err := v.Unmarshal(val); err != nil {
t.Fatalf("%+#v cannot unmarshal: %s", testValue.Value, err)
}
if changed {
assert.Equal(t, testValue.Expected, val.StringArray)
assert.Equal(t, testValue.Expected, v.Get("stringarray"))
} else {
assert.Equal(t, defaultVal, val.StringArray)
}
}
}
}

// nolint: dupl
func TestBindPFlagsIntSlice(t *testing.T) {
tests := []struct {
Expand Down

0 comments on commit bd03865

Please sign in to comment.