From 14948fab0014b51f997e10a48690274f385b0d05 Mon Sep 17 00:00:00 2001 From: Kailash Nadh Date: Sat, 9 Mar 2024 12:39:59 +0530 Subject: [PATCH] Fix incorrect map unflatten behaviour on no delim. Closes #275. --- maps/maps.go | 8 +++++++- tests/maps_test.go | 12 ++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/maps/maps.go b/maps/maps.go index 0a409f9a..bdb9d62b 100644 --- a/maps/maps.go +++ b/maps/maps.go @@ -74,10 +74,16 @@ func Unflatten(m map[string]interface{}, delim string) map[string]interface{} { // Iterate through the flat conf map. for k, v := range m { var ( - keys = strings.Split(k, delim) + keys []string next = out ) + if delim != "" { + keys = strings.Split(k, delim) + } else { + keys = []string{k} + } + // Iterate through key parts, for eg:, parent.child.key // will be ["parent", "child", "key"] for _, k := range keys[:len(keys)-1] { diff --git a/tests/maps_test.go b/tests/maps_test.go index c3acd0db..9b52b3c2 100644 --- a/tests/maps_test.go +++ b/tests/maps_test.go @@ -101,7 +101,7 @@ var testMap3 = map[string]interface{}{ } func TestFlatten(t *testing.T) { - f, k := maps.Flatten(testMap, nil, ".") + f, k := maps.Flatten(testMap, nil, delim) assert.Equal(t, map[string]interface{}{ "parent.child.key": 123, "parent.child.key.with.dot": 456, @@ -118,17 +118,17 @@ func TestFlatten(t *testing.T) { func BenchmarkFlatten(b *testing.B) { for n := 0; n < b.N; n++ { - maps.Flatten(testMap3, nil, ".") + maps.Flatten(testMap3, nil, delim) } } func TestUnflatten(t *testing.T) { - m, _ := maps.Flatten(testMap, nil, ".") - um := maps.Unflatten(m, ".") + m, _ := maps.Flatten(testMap, nil, delim) + um := maps.Unflatten(m, delim) assert.NotEqual(t, um, testMap) - m, _ = maps.Flatten(testMap2, nil, ".") - um = maps.Unflatten(m, ".") + m, _ = maps.Flatten(testMap2, nil, delim) + um = maps.Unflatten(m, delim) assert.Equal(t, um, testMap2) }