Add support for int slice flags

This commit is contained in:
Mark Sagi-Kazar 2019-01-27 03:23:33 +01:00
parent d104d259b3
commit b52b215be2
No known key found for this signature in database
GPG key ID: 34CC109EB5ED1C2A
2 changed files with 57 additions and 0 deletions

View file

@ -697,6 +697,8 @@ func (v *Viper) Get(key string) interface{} {
return cast.ToDuration(val)
case []string:
return cast.ToStringSlice(val)
case []int:
return cast.ToIntSlice(val)
}
}
@ -992,6 +994,11 @@ func (v *Viper) find(lcaseKey string) interface{} {
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return res
case "intSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
default:
return flag.ValueString()
}
@ -1061,6 +1068,11 @@ func (v *Viper) find(lcaseKey string) interface{} {
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return res
case "intSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
default:
return flag.ValueString()
}

View file

@ -658,6 +658,51 @@ func TestBindPFlagsStringSlice(t *testing.T) {
}
}
func TestBindPFlagsIntSlice(t *testing.T) {
tests := []struct {
Expected []int
Value string
}{
{nil, ""},
{[]int{1}, "1"},
{[]int{2, 3}, "2,3"},
}
v := New() // create independent Viper object
defaultVal := []int{0}
v.SetDefault("intslice", defaultVal)
for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.IntSlice("intslice", 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 TestInt struct {
IntSlice []int
}
val := &TestInt{}
if err := v.Unmarshal(val); err != nil {
t.Fatalf("%+#v cannot unmarshal: %s", testValue.Value, err)
}
if changed {
assert.Equal(t, testValue.Expected, val.IntSlice)
} else {
assert.Equal(t, defaultVal, val.IntSlice)
}
}
}
}
func TestBindPFlag(t *testing.T) {
var testString = "testing"
var testValue = newStringValue(testString, &testString)