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 isPathShadowedInFlatMap type cast bug #1585

Merged
merged 6 commits into from
Dec 6, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -827,10 +827,12 @@ func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]any) string
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInFlatMap(path []string, mi any) string {
// unify input map
var m map[string]any
switch mi.(type) {
case map[string]string, map[string]FlagValue:
m = cast.ToStringMap(mi)
var m map[string]interface{}
switch miv := mi.(type) {
case map[string]string:
m = castMapStringToMapInterface(miv)
case map[string]FlagValue:
m = castMapFlagToMapInterface(miv)
default:
return ""
}
Expand Down
45 changes: 45 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2637,6 +2637,51 @@ func TestSliceIndexAccess(t *testing.T) {
assert.Equal(t, "Static", v.GetString("tv.0.episodes.1.2"))
}

func TestIsPathShadowedInFlatMap(t *testing.T) {
v := New()

stringMap := map[string]string{
"foo": "value",
}

flagMap := map[string]FlagValue{
"foo": pflagValue{},
}

path1 := []string{"foo", "bar"}
expected1 := "foo"

// "foo.bar" should shadowed by "foo"
assert.Equal(t, expected1, v.isPathShadowedInFlatMap(path1, stringMap))
assert.Equal(t, expected1, v.isPathShadowedInFlatMap(path1, flagMap))

path2 := []string{"bar", "foo"}
expected2 := ""

// "bar.foo" should not shadowed by "foo"
assert.Equal(t, expected2, v.isPathShadowedInFlatMap(path2, stringMap))
assert.Equal(t, expected2, v.isPathShadowedInFlatMap(path2, flagMap))
}

func TestFlagShadow(t *testing.T) {
v := New()

v.SetDefault("foo.bar1.bar2", "default")

flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("foo.bar1", "shadowed", "")
flags.VisitAll(func(flag *pflag.Flag) {
flag.Changed = true
})

v.BindPFlags(flags)

assert.Equal(t, "shadowed", v.GetString("foo.bar1"))
// the default "foo.bar1.bar2" value should shadowed by flag "foo.bar1" value
// and should return an empty string
assert.Equal(t, "", v.GetString("foo.bar1.bar2"))
}

func BenchmarkGetBool(b *testing.B) {
key := "BenchmarkGetBool"
v = New()
Expand Down