Skip to content

Commit

Permalink
add merge function to dict
Browse files Browse the repository at this point in the history
  • Loading branch information
Adnan Abdulhussein committed May 2, 2017
1 parent 4fd5bcb commit 72e8912
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 4 deletions.
10 changes: 10 additions & 0 deletions dict.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package sprig

import "github.com/imdario/mergo"

func set(d map[string]interface{}, key string, value interface{}) map[string]interface{} {
d[key] = value
return d
Expand Down Expand Up @@ -72,3 +74,11 @@ 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 ""
}
return dst
}
37 changes: 37 additions & 0 deletions dict_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,40 @@ func TestCompact(t *testing.T) {
assert.NoError(t, runt(tpl, expect))
}
}

func TestMerge(t *testing.T) {
dict := map[string]interface{}{
"src": map[string]interface{}{
"a": 1,
"b": 2,
"d": map[string]interface{}{
"e": "four",
},
"g": []int{6, 7},
},
"dst": map[string]interface{}{
"a": "one",
"c": 3,
"d": map[string]interface{}{
"f": 5,
},
"g": []int{8, 9},
},
}
tpl := `{{merge .dst .src}}`
_, err := runRaw(tpl, dict)
if err != nil {
t.Error(err)
}
expected := map[string]interface{}{
"a": "one", // key overridden
"b": 2, // merged from src
"c": 3, // merged from dst
"d": map[string]interface{}{ // deep merge
"e": "four",
"f": 5,
},
"g": []int{8, 9}, // overridden - arrays are not merged
}
assert.Equal(t, expected, dict["dst"])
}
1 change: 1 addition & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ var genericMap = map[string]interface{}{
"keys": keys,
"pick": pick,
"omit": omit,
"merge": merge,

"append": push, "push": push,
"prepend": prepend,
Expand Down
20 changes: 16 additions & 4 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions glide.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ import:
- package: github.com/Masterminds/semver
version: v1.2.2
- package: github.com/stretchr/testify
- package: github.com/imdario/mergo
version: ~0.2.2

0 comments on commit 72e8912

Please sign in to comment.