Skip to content

Commit

Permalink
dict/merge: Add ability to merge multiple dicts, update test and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
binoculars committed Jul 26, 2017
1 parent e039e20 commit 7e5486c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 9 deletions.
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

0 comments on commit 7e5486c

Please sign in to comment.