From 1d33e9d9b07dba0aae8971c960afe000f5450300 Mon Sep 17 00:00:00 2001 From: Yi-Ting Shih Date: Mon, 30 Mar 2026 03:39:11 +0800 Subject: [PATCH] feat: add int64Slice support --- viper.go | 18 ++++++++++++++++++ viper_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/viper.go b/viper.go index 2d5158cbd..91e265405 100644 --- a/viper.go +++ b/viper.go @@ -899,6 +899,14 @@ func (v *Viper) GetIntSlice(key string) []int { return cast.ToIntSlice(v.Get(key)) } +// GetInt64Slice returns the value associated with the key as a slice of int64 values. +func GetInt64Slice(key string) []int64 { return v.GetInt64Slice(key) } + +// GetInt64Slice returns the value associated with the key as a slice of int64 values. +func (v *Viper) GetInt64Slice(key string) []int64 { + return cast.ToInt64Slice(v.Get(key)) +} + // GetStringSlice returns the value associated with the key as a slice of strings. func GetStringSlice(key string) []string { return v.GetStringSlice(key) } @@ -1241,6 +1249,11 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) any { s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) + case "int64Slice": + s := strings.TrimPrefix(flag.ValueString(), "[") + s = strings.TrimSuffix(s, "]") + res, _ := readAsCSV(s) + return cast.ToInt64Slice(res) case "uintSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") @@ -1343,6 +1356,11 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) any { s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) + case "int64Slice": + s := strings.TrimPrefix(flag.ValueString(), "[") + s = strings.TrimSuffix(s, "]") + res, _ := readAsCSV(s) + return cast.ToInt64Slice(res) case "uintSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") diff --git a/viper_test.go b/viper_test.go index 8b0232aee..674271e0a 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1292,6 +1292,42 @@ func TestBindPFlagsIntSlice(t *testing.T) { } } +func TestBindPFlagsInt64Slice(t *testing.T) { + tests := []struct { + Expected []int64 + Value string + }{ + {[]int64{}, ""}, + {[]int64{1}, "1"}, + {[]int64{2, 3}, "2,3"}, + } + + v := New() // create independent Viper object + defaultVal := []int64{0} + v.SetDefault("int64slice", defaultVal) + + for _, testValue := range tests { + flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) + flagSet.Int64Slice("int64slice", 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) + require.NoError(t, err, "error binding flag set") + + if changed { + assert.Equal(t, testValue.Expected, v.GetInt64Slice("int64slice")) + } else { + assert.Equal(t, defaultVal, v.GetInt64Slice("int64slice")) + } + } + } +} + func TestBindPFlag(t *testing.T) { v := New() testString := "testing"