mirror of
https://github.com/spf13/viper
synced 2024-12-22 11:37:02 +00:00
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:
parent
5182412574
commit
c898f59d33
2 changed files with 35 additions and 0 deletions
13
viper.go
13
viper.go
|
@ -928,6 +928,8 @@ func (v *Viper) Get(key string) interface{} {
|
|||
return cast.ToStringSlice(val)
|
||||
case []int:
|
||||
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, "]")
|
||||
res, _ := readAsCSV(s)
|
||||
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":
|
||||
return stringToStringConv(flag.ValueString())
|
||||
|
||||
default:
|
||||
return flag.ValueString()
|
||||
}
|
||||
|
@ -1355,6 +1363,11 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
|
|||
return cast.ToIntSlice(res)
|
||||
case "stringToString":
|
||||
return stringToStringConv(flag.ValueString())
|
||||
case "durationSlice":
|
||||
s := strings.TrimPrefix(flag.ValueString(), "[")
|
||||
s = strings.TrimSuffix(s, "]")
|
||||
slice := strings.Split(s, ",")
|
||||
return cast.ToDurationSlice(slice)
|
||||
default:
|
||||
return flag.ValueString()
|
||||
}
|
||||
|
|
|
@ -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
|
||||
func TestBindPFlagsIntSlice(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
|
Loading…
Reference in a new issue