From 44a8b86cb5e5bc18eef11b5a3844eef265f059ad Mon Sep 17 00:00:00 2001 From: Knut Zuidema Date: Thu, 13 Apr 2023 03:56:28 +0200 Subject: [PATCH] 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. --- viper.go | 15 +++++---------- viper_test.go | 9 +++++++++ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/viper.go b/viper.go index 7eac4b7..e0eea24 100644 --- a/viper.go +++ b/viper.go @@ -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. diff --git a/viper_test.go b/viper_test.go index 8283b5c..14fda59 100644 --- a/viper_test.go +++ b/viper_test.go @@ -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()