Handle embedded and ignored fields in toml env override

One of the closed source copies of applyEnvOverrides needed this
behavior.
pull/9591/head
Mark Rushakoff 2018-03-16 08:38:56 -07:00
parent a65e51e295
commit 4dc92875ef
2 changed files with 30 additions and 2 deletions

View File

@ -180,9 +180,24 @@ func applyEnvOverrides(getenv func(string) string, prefix string, spec reflect.V
continue
}
fieldName := typeOfSpec.Field(i).Name
structField := typeOfSpec.Field(i)
fieldName := structField.Name
configName := structField.Tag.Get("toml")
if configName == "-" {
// Skip fields with tag `toml:"-"`.
continue
}
if configName == "" && structField.Anonymous {
// Embedded field without a toml tag.
// Don't modify prefix.
if err := applyEnvOverrides(getenv, prefix, field, fieldName); err != nil {
return err
}
continue
}
configName := typeOfSpec.Field(i).Tag.Get("toml")
// Replace hyphens with underscores to avoid issues with shells
configName = strings.Replace(configName, "-", "_", -1)

View File

@ -94,6 +94,8 @@ func TestEnvOverride_Builtins(t *testing.T) {
"X_FLOAT64": "12.5",
"X_NESTED_STRING": "a nested string",
"X_NESTED_INT": "13",
"X_ES": "an embedded string",
"X__": "-1", // This value should not be applied to the "ignored" field with toml tag -.
}
env := func(s string) string {
@ -104,6 +106,9 @@ func TestEnvOverride_Builtins(t *testing.T) {
Str string `toml:"string"`
Int int `toml:"int"`
}
type Embedded struct {
ES string `toml:"es"`
}
type all struct {
Str string `toml:"string"`
Dur itoml.Duration `toml:"duration"`
@ -121,6 +126,10 @@ func TestEnvOverride_Builtins(t *testing.T) {
Float32 float32 `toml:"float32"`
Float64 float64 `toml:"float64"`
Nested nested `toml:"nested"`
Embedded
Ignored int `toml:"-"`
}
var got all
@ -148,6 +157,10 @@ func TestEnvOverride_Builtins(t *testing.T) {
Str: "a nested string",
Int: 13,
},
Embedded: Embedded{
ES: "an embedded string",
},
Ignored: 0,
}
if diff := cmp.Diff(got, exp); diff != "" {