Skip to content

Commit f736363

Browse files
fix isPathShadowedInFlatMap type cast bug (#1585)
* fix isPathShadowedInFlatMap type cast bug * Add "IsPathShadowedInFlatMap" method unit test * fix: typo * add an unit test for flag shadow --------- Co-authored-by: Márk Sági-Kazár <[email protected]>
1 parent 36a3868 commit f736363

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

viper.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -827,10 +827,12 @@ func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]any) string
827827
// "foo.bar.baz" in a lower-priority map
828828
func (v *Viper) isPathShadowedInFlatMap(path []string, mi any) string {
829829
// unify input map
830-
var m map[string]any
831-
switch mi.(type) {
832-
case map[string]string, map[string]FlagValue:
833-
m = cast.ToStringMap(mi)
830+
var m map[string]interface{}
831+
switch miv := mi.(type) {
832+
case map[string]string:
833+
m = castMapStringToMapInterface(miv)
834+
case map[string]FlagValue:
835+
m = castMapFlagToMapInterface(miv)
834836
default:
835837
return ""
836838
}

viper_test.go

+45
Original file line numberDiff line numberDiff line change
@@ -2575,6 +2575,51 @@ func TestSliceIndexAccess(t *testing.T) {
25752575
assert.Equal(t, "Static", v.GetString("tv.0.episodes.1.2"))
25762576
}
25772577

2578+
func TestIsPathShadowedInFlatMap(t *testing.T) {
2579+
v := New()
2580+
2581+
stringMap := map[string]string{
2582+
"foo": "value",
2583+
}
2584+
2585+
flagMap := map[string]FlagValue{
2586+
"foo": pflagValue{},
2587+
}
2588+
2589+
path1 := []string{"foo", "bar"}
2590+
expected1 := "foo"
2591+
2592+
// "foo.bar" should shadowed by "foo"
2593+
assert.Equal(t, expected1, v.isPathShadowedInFlatMap(path1, stringMap))
2594+
assert.Equal(t, expected1, v.isPathShadowedInFlatMap(path1, flagMap))
2595+
2596+
path2 := []string{"bar", "foo"}
2597+
expected2 := ""
2598+
2599+
// "bar.foo" should not shadowed by "foo"
2600+
assert.Equal(t, expected2, v.isPathShadowedInFlatMap(path2, stringMap))
2601+
assert.Equal(t, expected2, v.isPathShadowedInFlatMap(path2, flagMap))
2602+
}
2603+
2604+
func TestFlagShadow(t *testing.T) {
2605+
v := New()
2606+
2607+
v.SetDefault("foo.bar1.bar2", "default")
2608+
2609+
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
2610+
flags.String("foo.bar1", "shadowed", "")
2611+
flags.VisitAll(func(flag *pflag.Flag) {
2612+
flag.Changed = true
2613+
})
2614+
2615+
v.BindPFlags(flags)
2616+
2617+
assert.Equal(t, "shadowed", v.GetString("foo.bar1"))
2618+
// the default "foo.bar1.bar2" value should shadowed by flag "foo.bar1" value
2619+
// and should return an empty string
2620+
assert.Equal(t, "", v.GetString("foo.bar1.bar2"))
2621+
}
2622+
25782623
func BenchmarkGetBool(b *testing.B) {
25792624
key := "BenchmarkGetBool"
25802625
v = New()

0 commit comments

Comments
 (0)