Skip to content

Commit

Permalink
Recurse into arrays when converting keys to lowercase
Browse files Browse the repository at this point in the history
Fixes #1386

Signed-off-by: Andrew Richardson <[email protected]>
  • Loading branch information
awrichar committed Jun 23, 2022
1 parent 0add84c commit 4652c93
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
33 changes: 23 additions & 10 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,25 @@ func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
return nm
}

func insensitiviseVal(val interface{}) interface{} {
switch val.(type) {
case map[interface{}]interface{}:
// nested map: cast and recursively insensitivise
val = cast.ToStringMap(val)
insensitiviseMap(val.(map[string]interface{}))
case map[string]interface{}:
// nested map: recursively insensitivise
insensitiviseMap(val.(map[string]interface{}))
case []interface{}:
// nested array: recursively insensitivise
insensitiveArray(val.([]interface{}))
}
return val
}

func insensitiviseMap(m map[string]interface{}) {
for key, val := range m {
switch val.(type) {
case map[interface{}]interface{}:
// nested map: cast and recursively insensitivise
val = cast.ToStringMap(val)
insensitiviseMap(val.(map[string]interface{}))
case map[string]interface{}:
// nested map: recursively insensitivise
insensitiviseMap(val.(map[string]interface{}))
}

val = insensitiviseVal(val)
lower := strings.ToLower(key)
if key != lower {
// remove old key (not lower-cased)
Expand All @@ -86,6 +93,12 @@ func insensitiviseMap(m map[string]interface{}) {
}
}

func insensitiveArray(a []interface{}) {
for _, val := range a {
insensitiviseVal(val)
}
}

func absPathify(logger Logger, inPath string) string {
logger.Info("trying to resolve absolute path", "path", inPath)

Expand Down
2 changes: 2 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2517,6 +2517,7 @@ func TestKeyDelimiter(t *testing.T) {

var yamlDeepNestedSlices = []byte(`TV:
- title: "The expanse"
originalNetwork: "syfy"
seasons:
- first_released: "December 14, 2015"
episodes:
Expand Down Expand Up @@ -2547,6 +2548,7 @@ func TestSliceIndexAccess(t *testing.T) {
require.NoError(t, err)

assert.Equal(t, "The expanse", v.GetString("tv.0.title"))
assert.Equal(t, "syfy", v.GetString("tv.0.originalNetwork"))
assert.Equal(t, "February 1, 2017", v.GetString("tv.0.seasons.1.first_released"))
assert.Equal(t, "Static", v.GetString("tv.0.seasons.1.episodes.2.title"))
assert.Equal(t, "December 15, 2015", v.GetString("tv.0.seasons.0.episodes.1.air_date"))
Expand Down

0 comments on commit 4652c93

Please sign in to comment.