Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dict/merge: Add ability to merge multiple dicts, update test and docs #49

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ func dict(v ...interface{}) map[string]interface{} {
return dict
}

func merge(dst map[string]interface{}, src map[string]interface{}) interface{} {
if err := mergo.Merge(&dst, src); err != nil {
// Swallow errors inside of a template.
return ""
func merge(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} {
for _, src := range srcs {
if err := mergo.Merge(&dst, src); err != nil {
// Swallow errors inside of a template.
return ""
}
}
return dst
}
17 changes: 14 additions & 3 deletions dict_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,20 @@ func TestCompact(t *testing.T) {

func TestMerge(t *testing.T) {
dict := map[string]interface{}{
"src": map[string]interface{}{
"src2": map[string]interface{}{
"h": 10,
"i": "i",
"j": "j",
},
"src1": map[string]interface{}{
"a": 1,
"b": 2,
"d": map[string]interface{}{
"e": "four",
},
"g": []int{6, 7},
"i": "aye",
"j": "jay",
},
"dst": map[string]interface{}{
"a": "one",
Expand All @@ -153,22 +160,26 @@ func TestMerge(t *testing.T) {
"f": 5,
},
"g": []int{8, 9},
"i": "eye",
},
}
tpl := `{{merge .dst .src}}`
tpl := `{{merge .dst .src1 .src2}}`
_, err := runRaw(tpl, dict)
if err != nil {
t.Error(err)
}
expected := map[string]interface{}{
"a": "one", // key overridden
"b": 2, // merged from src
"b": 2, // merged from src1
"c": 3, // merged from dst
"d": map[string]interface{}{ // deep merge
"e": "four",
"f": 5,
},
"g": []int{8, 9}, // overridden - arrays are not merged
"h": 10, // merged from src2
"i": "eye", // overridden twice
"j": "jay", // overridden and merged
}
assert.Equal(t, expected, dict["dst"])
}
4 changes: 2 additions & 2 deletions docs/dicts.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ matching key out of a collection of dictionaries.

## merge

Merge two dictionaries into one, giving precedence to the dest dictionary:
Merge two or more dictionaries into one, giving precedence to the dest dictionary:

```
$newdict := merge $dest $source
$newdict := merge $dest $source1 $source2
```

This is a deep merge operation.
Expand Down