fix: time.Duration slice type conversion (#1498)

* fix DurationSlice

* Fix typo

---------

Co-authored-by: Márk Sági-Kazár <sagikazarmark@users.noreply.github.com>
This commit is contained in:
Dawid Urbański 2023-02-05 18:30:05 +01:00 committed by GitHub
parent 5182412574
commit c898f59d33
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View file

@ -928,6 +928,8 @@ func (v *Viper) Get(key string) interface{} {
return cast.ToStringSlice(val) return cast.ToStringSlice(val)
case []int: case []int:
return cast.ToIntSlice(val) return cast.ToIntSlice(val)
case []time.Duration:
return cast.ToDurationSlice(val)
} }
} }
@ -1274,8 +1276,14 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
s = strings.TrimSuffix(s, "]") s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s) res, _ := readAsCSV(s)
return cast.ToIntSlice(res) return cast.ToIntSlice(res)
case "durationSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
slice := strings.Split(s, ",")
return cast.ToDurationSlice(slice)
case "stringToString": case "stringToString":
return stringToStringConv(flag.ValueString()) return stringToStringConv(flag.ValueString())
default: default:
return flag.ValueString() return flag.ValueString()
} }
@ -1355,6 +1363,11 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
return cast.ToIntSlice(res) return cast.ToIntSlice(res)
case "stringToString": case "stringToString":
return stringToStringConv(flag.ValueString()) return stringToStringConv(flag.ValueString())
case "durationSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
slice := strings.Split(s, ",")
return cast.ToDurationSlice(slice)
default: default:
return flag.ValueString() return flag.ValueString()
} }

View file

@ -1094,6 +1094,28 @@ func TestBindPFlagsStringArray(t *testing.T) {
} }
} }
func TestSliceFlagsReturnCorrectType(t *testing.T) {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.IntSlice("int", []int{1, 2}, "")
flagSet.StringSlice("str", []string{"3", "4"}, "")
flagSet.DurationSlice("duration", []time.Duration{5 * time.Second}, "")
v := New()
v.BindPFlags(flagSet)
all := v.AllSettings()
if _, ok := all["int"].([]int); !ok {
t.Errorf("unexpected type %T expected []int", all["int"])
}
if _, ok := all["str"].([]string); !ok {
t.Errorf("unexpected type %T expected []string", all["str"])
}
if _, ok := all["duration"].([]time.Duration); !ok {
t.Errorf("unexpected type %T expected []time.Duration", all["duration"])
}
}
//nolint:dupl //nolint:dupl
func TestBindPFlagsIntSlice(t *testing.T) { func TestBindPFlagsIntSlice(t *testing.T) {
tests := []struct { tests := []struct {