mirror of https://github.com/spf13/viper.git
Sub inerits from automaticEnvApplied and envKeyReplacer
parents are tracked so sub(x).sub(y).GetString(z) looks up x.y.z
This commit is contained in:
parent
c898f59d33
commit
3f4449054d
8
viper.go
8
viper.go
|
@ -206,6 +206,7 @@ type Viper struct {
|
|||
envKeyReplacer StringReplacer
|
||||
allowEmptyEnv bool
|
||||
|
||||
parents []string
|
||||
config map[string]interface{}
|
||||
override map[string]interface{}
|
||||
defaults map[string]interface{}
|
||||
|
@ -232,6 +233,7 @@ func New() *Viper {
|
|||
v.configPermissions = os.FileMode(0o644)
|
||||
v.fs = afero.NewOsFs()
|
||||
v.config = make(map[string]interface{})
|
||||
v.parents = []string{}
|
||||
v.override = make(map[string]interface{})
|
||||
v.defaults = make(map[string]interface{})
|
||||
v.kvstore = make(map[string]interface{})
|
||||
|
@ -948,6 +950,9 @@ 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.envKeyReplacer = v.envKeyReplacer
|
||||
subv.config = cast.ToStringMap(data)
|
||||
return subv
|
||||
}
|
||||
|
@ -1294,9 +1299,10 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
|
|||
|
||||
// Env override next
|
||||
if v.automaticEnvApplied {
|
||||
envKey := strings.Join(append(v.parents, lcaseKey), ".")
|
||||
// even if it hasn't been registered, if automaticEnv is used,
|
||||
// check any Get request
|
||||
if val, ok := v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); ok {
|
||||
if val, ok := v.getEnv(v.mergeWithEnvPrefix(envKey)); ok {
|
||||
return val
|
||||
}
|
||||
if nested && v.isPathShadowedInAutoEnv(path) != "" {
|
||||
|
|
|
@ -733,6 +733,19 @@ func TestEnvKeyReplacer(t *testing.T) {
|
|||
assert.Equal(t, "30s", v.Get("refresh-interval"))
|
||||
}
|
||||
|
||||
func TestEnvSubConfig(t *testing.T) {
|
||||
initYAML()
|
||||
|
||||
v.AutomaticEnv()
|
||||
|
||||
replacer := strings.NewReplacer(".", "_")
|
||||
v.SetEnvKeyReplacer(replacer)
|
||||
|
||||
testutil.Setenv(t, "CLOTHING_PANTS_SIZE", "small")
|
||||
subv := v.Sub("clothing").Sub("pants")
|
||||
assert.Equal(t, "small", subv.Get("size"))
|
||||
}
|
||||
|
||||
func TestAllKeys(t *testing.T) {
|
||||
initConfigs()
|
||||
|
||||
|
@ -1522,6 +1535,14 @@ func TestSub(t *testing.T) {
|
|||
|
||||
subv = v.Sub("missing.key")
|
||||
assert.Equal(t, (*Viper)(nil), subv)
|
||||
|
||||
subv = v.Sub("clothing")
|
||||
assert.Equal(t, subv.parents[0], "clothing")
|
||||
|
||||
subv = v.Sub("clothing").Sub("pants")
|
||||
assert.Equal(t, len(subv.parents), 2)
|
||||
assert.Equal(t, subv.parents[0], "clothing")
|
||||
assert.Equal(t, subv.parents[1], "pants")
|
||||
}
|
||||
|
||||
var hclWriteExpected = []byte(`"foos" = {
|
||||
|
|
Loading…
Reference in New Issue