Last active
July 12, 2024 11:15
-
-
Save siredmar/75cce465659bc76d15daa91a53b114c1 to your computer and use it in GitHub Desktop.
kontemplate patch to support non-flat default values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
From 898d5a558ea6958d81509e5904093c0a02519a2d Mon Sep 17 00:00:00 2001 | |
From: Armin Schlegel <[email protected]> | |
Date: Fri, 12 Jul 2024 12:25:48 +0200 | |
Subject: [PATCH] feat: defaults can now have nested values | |
Signed-off-by: Armin Schlegel <[email protected]> | |
--- | |
util/util.go | 18 +++++++++++++++++- | |
util/util_test.go | 6 ++++++ | |
2 files changed, 23 insertions(+), 1 deletion(-) | |
diff --git a/util/util.go b/util/util.go | |
index 56fa1e3..f96f5c1 100644 | |
--- a/util/util.go | |
+++ b/util/util.go | |
@@ -29,13 +29,29 @@ func Merge(in1 *map[string]interface{}, in2 *map[string]interface{}) *map[string | |
return in1 | |
} | |
+ // The maps are map[string]interface{} with unknown depth. | |
+ // Loop over both maps into every level and merge them. | |
new := make(map[string]interface{}) | |
+ | |
for k, v := range *in1 { | |
new[k] = v | |
} | |
for k, v := range *in2 { | |
- new[k] = v | |
+ if existing, ok := new[k]; ok { | |
+ // If both values are maps, merge them recursively | |
+ if existingMap, ok := existing.(map[string]interface{}); ok { | |
+ if newMap, ok := v.(map[string]interface{}); ok { | |
+ new[k] = *Merge(&existingMap, &newMap) | |
+ } else { | |
+ new[k] = v | |
+ } | |
+ } else { | |
+ new[k] = v | |
+ } | |
+ } else { | |
+ new[k] = v | |
+ } | |
} | |
return &new | |
diff --git a/util/util_test.go b/util/util_test.go | |
index 53c5608..328add3 100644 | |
--- a/util/util_test.go | |
+++ b/util/util_test.go | |
@@ -47,6 +47,9 @@ func TestMergeWithNilMap(t *testing.T) { | |
func TestMergeMaps(t *testing.T) { | |
map1 := map[string]interface{}{ | |
"foo": "bar", | |
+ "baz": map[string]interface{}{ | |
+ "qux": "quux", | |
+ }, | |
} | |
map2 := map[string]interface{}{ | |
@@ -56,6 +59,9 @@ func TestMergeMaps(t *testing.T) { | |
result := Merge(&map1, &map2) | |
expected := map[string]interface{}{ | |
"foo": "bar", | |
+ "baz": map[string]interface{}{ | |
+ "qux": "quux", | |
+ }, | |
"bar": "baz", | |
} | |
-- | |
2.43.0 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment