Skip to content

Commit

Permalink
Merge pull request #231 from rquitales/fix-merge-maps
Browse files Browse the repository at this point in the history
fix: Respect overwriteWithEmptySrc when merging maps
  • Loading branch information
darccio authored Mar 15, 2023
2 parents 7d709f7 + 81666e0 commit 68ed330
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 4 deletions.
85 changes: 85 additions & 0 deletions issue230_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package mergo_test

import (
"testing"

"github.com/imdario/mergo"
)

var testDataM = []struct {
M1 mapTest
M2 mapTest
WithOverrideEmptyValue bool
ExpectedMap map[int]int
}{
{
M1: mapTest{
M: map[int]int{1: 1, 3: 3},
},
M2: mapTest{
M: map[int]int{1: 2, 2: 2},
},
WithOverrideEmptyValue: true,
ExpectedMap: map[int]int{1: 1, 3: 3},
},
{
M1: mapTest{
M: map[int]int{1: 1, 3: 3},
},
M2: mapTest{
M: map[int]int{1: 2, 2: 2},
},
WithOverrideEmptyValue: false,
ExpectedMap: map[int]int{1: 1, 2: 2, 3: 3},
},
{
M1: mapTest{
M: map[int]int{},
},
M2: mapTest{
M: map[int]int{1: 2, 2: 2},
},
WithOverrideEmptyValue: true,
ExpectedMap: map[int]int{},
},
{
M1: mapTest{
M: map[int]int{},
},
M2: mapTest{
M: map[int]int{1: 2, 2: 2},
},
WithOverrideEmptyValue: false,
ExpectedMap: map[int]int{1: 2, 2: 2},
},
}

func withOverrideEmptyValue(enable bool) func(*mergo.Config) {
if enable {
return mergo.WithOverwriteWithEmptyValue
}

return mergo.WithOverride
}

func TestMergeMapWithOverride(t *testing.T) {
t.Parallel()

for _, data := range testDataM {
err := mergo.Merge(&data.M2, data.M1, withOverrideEmptyValue(data.WithOverrideEmptyValue))
if err != nil {
t.Errorf("Error while merging %s", err)
}

if len(data.M2.M) != len(data.ExpectedMap) {
t.Errorf("Got %d elements in map, but expected %d", len(data.M2.M), len(data.ExpectedMap))
return
}

for i, val := range data.M2.M {
if val != data.ExpectedMap[i] {
t.Errorf("Expected value: %d, but got %d while merging map", data.ExpectedMap[i], val)
}
}
}
}
4 changes: 0 additions & 4 deletions issue89_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ func TestIssue89MergeWithEmptyValue(t *testing.T) {
expected interface{}
key string
}{
{
3,
"A",
},
{
"",
"B",
Expand Down
10 changes: 10 additions & 0 deletions merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
dst.SetMapIndex(key, srcElement)
}
}

// Ensure that all keys in dst are deleted if they are not in src.
if overwriteWithEmptySrc {
for _, key := range dst.MapKeys() {
srcElement := src.MapIndex(key)
if !srcElement.IsValid() {
dst.SetMapIndex(key, reflect.Value{})
}
}
}
case reflect.Slice:
if !dst.CanSet() {
break
Expand Down

0 comments on commit 68ed330

Please sign in to comment.