Skip to content

Commit

Permalink
Add (*MapStr).DeepUpdate (#4090)
Browse files Browse the repository at this point in the history
Add DeepUpdate to MapStr for recursive-deep updating an event.
  • Loading branch information
Steffen Siering authored and ruflin committed Apr 23, 2017
1 parent d351c91 commit 65a6d77
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
34 changes: 34 additions & 0 deletions libbeat/common/mapstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,40 @@ func (m MapStr) Update(d MapStr) {
}
}

// DeepUpdate recursively copies the key-value pairs from d to this map.
// If the key is present and a map as well, the sub-map will be updated recursively
// via DeepUpdate.
func (m MapStr) DeepUpdate(d MapStr) {
for k, v := range d {
switch val := v.(type) {
case map[string]interface{}:
m[k] = deepUpdateValue(m[k], MapStr(val))
case MapStr:
m[k] = deepUpdateValue(m[k], val)
default:
m[k] = v
}
}
}

func deepUpdateValue(old interface{}, val MapStr) interface{} {
if old == nil {
return val
}

switch sub := old.(type) {
case MapStr:
sub.DeepUpdate(val)
return sub
case map[string]interface{}:
tmp := MapStr(sub)
tmp.DeepUpdate(val)
return tmp
default:
return val
}
}

// Delete deletes the given key from the map.
func (m MapStr) Delete(key string) error {
_, err := walkMap(key, m, opDelete)
Expand Down
43 changes: 43 additions & 0 deletions libbeat/common/mapstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package common

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -25,6 +26,48 @@ func TestMapStrUpdate(t *testing.T) {
assert.Equal(a, MapStr{"a": 1, "b": 3, "c": 4})
}

func TestMapStrDeepUpdate(t *testing.T) {
tests := []struct {
a, b, expected MapStr
}{
{
MapStr{"a": 1},
MapStr{"b": 2},
MapStr{"a": 1, "b": 2},
},
{
MapStr{"a": 1},
MapStr{"a": 2},
MapStr{"a": 2},
},
{
MapStr{"a": 1},
MapStr{"a": MapStr{"b": 1}},
MapStr{"a": MapStr{"b": 1}},
},
{
MapStr{"a": MapStr{"b": 1}},
MapStr{"a": MapStr{"c": 2}},
MapStr{"a": MapStr{"b": 1, "c": 2}},
},
{
MapStr{"a": MapStr{"b": 1}},
MapStr{"a": 1},
MapStr{"a": 1},
},
}

for i, test := range tests {
a, b, expected := test.a, test.b, test.expected
name := fmt.Sprintf("%v: %v + %v = %v", i, a, b, expected)

t.Run(name, func(t *testing.T) {
a.DeepUpdate(b)
assert.Equal(t, expected, a)
})
}
}

func TestMapStrUnion(t *testing.T) {
assert := assert.New(t)

Expand Down

0 comments on commit 65a6d77

Please sign in to comment.