Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: time.Duration slice type conversion #1498

Merged
merged 2 commits into from
Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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()
}
Expand Down
22 changes: 22 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down