Skip to content

Commit

Permalink
Preserve envPrefix in Sub
Browse files Browse the repository at this point in the history
  • Loading branch information
TaylorOno committed Apr 4, 2021
1 parent d49821e commit fd570e1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
3 changes: 2 additions & 1 deletion viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,7 @@ func (v *Viper) Sub(key string) *Viper {
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
Expand Down Expand Up @@ -1749,7 +1750,7 @@ func (v *Viper) marshalWriter(f afero.File, configType string) error {
if sectionName == "default" {
sectionName = ""
}
cfg.Section(sectionName).Key(keyName).SetValue(v.Get(key).(string))
cfg.Section(sectionName).Key(keyName).SetValue(v.GetString(key))
}
cfg.WriteTo(f)
}
Expand Down
9 changes: 7 additions & 2 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,12 +609,17 @@ func TestEnvSubConfig(t *testing.T) {

v.AutomaticEnv()

replacer := strings.NewReplacer(".", "_")
v.SetEnvKeyReplacer(replacer)
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

testutil.Setenv(t, "CLOTHING_PANTS_SIZE", "small")
subv := v.Sub("clothing").Sub("pants")
assert.Equal(t, "small", subv.Get("size"))

// again with EnvPrefix
v.SetEnvPrefix("foo") // will be uppercased automatically
subWithPrefix := v.Sub("clothing").Sub("pants")
testutil.Setenv(t, "FOO_CLOTHING_PANTS_SIZE", "large")
assert.Equal(t, "large", subWithPrefix.Get("size"))
}

func TestAllKeys(t *testing.T) {
Expand Down

0 comments on commit fd570e1

Please sign in to comment.