Sub always uses key as env prefix

This changes the behavior of Sub to always return a non-nil value with the env key prefix set and only optionally setting a map value as config.
This commit is contained in:
Knut Zuidema 2023-04-13 03:56:28 +02:00
parent adc3a873f0
commit 44a8b86cb5
No known key found for this signature in database
GPG key ID: 690C7167807CAB54
2 changed files with 14 additions and 10 deletions

View file

@ -944,20 +944,15 @@ func Sub(key string) *Viper { return v.Sub(key) }
func (v *Viper) Sub(key string) *Viper {
subv := New()
subv.parents = append(v.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
data := v.Get(key)
if data == nil {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Map {
subv.parents = append(v.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
subv.config = cast.ToStringMap(data)
return subv
}
return nil
return subv
}
// GetString returns the value associated with the key as a string.

View file

@ -2619,6 +2619,15 @@ func TestSliceIndexAccess(t *testing.T) {
assert.Equal(t, "Static", v.GetString("tv.0.episodes.1.2"))
}
func TestSubUsesEnvPrefix(t *testing.T) {
testutil.Setenv(t, "TEST_SUB_VALUE", "test")
v.SetEnvPrefix("TEST")
v.AutomaticEnv()
sub := v.Sub("sub")
assert.Equal(t, "test", sub.GetString("value"))
}
func BenchmarkGetBool(b *testing.B) {
key := "BenchmarkGetBool"
v = New()