Add a proper processing for pflag.StringArray

This commit is contained in:
Mikhail f. Shiryaev 2021-06-23 13:24:02 +02:00 committed by Márk Sági-Kazár
parent 3fcad43618
commit bd03865899
2 changed files with 50 additions and 2 deletions

View file

@ -1153,7 +1153,7 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
return cast.ToInt(flag.ValueString()) return cast.ToInt(flag.ValueString())
case "bool": case "bool":
return cast.ToBool(flag.ValueString()) return cast.ToBool(flag.ValueString())
case "stringSlice": case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[") s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]") s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s) res, _ := readAsCSV(s)
@ -1232,7 +1232,7 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
return cast.ToInt(flag.ValueString()) return cast.ToInt(flag.ValueString())
case "bool": case "bool":
return cast.ToBool(flag.ValueString()) return cast.ToBool(flag.ValueString())
case "stringSlice": case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[") s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]") s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s) res, _ := readAsCSV(s)

View file

@ -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 // nolint: dupl
func TestBindPFlagsIntSlice(t *testing.T) { func TestBindPFlagsIntSlice(t *testing.T) {
tests := []struct { tests := []struct {