Skip to content

Commit

Permalink
fix: Respect overwriteWithEmptySrc when merging maps
Browse files Browse the repository at this point in the history
  • Loading branch information
rquitales committed Mar 8, 2023
1 parent 7d709f7 commit 69d18dc
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 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)
}
}
}
}
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 69d18dc

Please sign in to comment.