Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new WithSliceDeepMerge config option #222

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
75 changes: 74 additions & 1 deletion merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ type Config struct {
overwriteWithEmptyValue bool
overwriteSliceWithEmptyValue bool
sliceDeepCopy bool
sliceDeepMerge bool
OverwriteNilInMaps bool
debug bool
}

Expand All @@ -57,10 +59,12 @@ type Transformers interface {
// short circuiting on recursive types.
func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
overwriteNilInMaps := config.OverwriteNilInMaps
typeCheck := config.TypeCheck
overwriteWithEmptySrc := config.overwriteWithEmptyValue
overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue
sliceDeepCopy := config.sliceDeepCopy
sliceDeepMerge := config.sliceDeepMerge

if !src.IsValid() {
return
Expand Down Expand Up @@ -125,7 +129,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
switch srcElement.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice:
if srcElement.IsNil() {
if overwrite {
if overwrite || overwriteNilInMaps {
dst.SetMapIndex(key, srcElement)
}
continue
Expand Down Expand Up @@ -189,7 +193,39 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
return
}
}
} else if sliceDeepMerge {
if srcSlice.Len() > dstSlice.Len() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar blocks of code found in 2 locations. Consider refactoring.

newSlice := reflect.MakeSlice(srcSlice.Type(), srcSlice.Len(), srcSlice.Len())

for i := 0; i < dstSlice.Len(); i++ {
newSlice.Index(i).Set(dstSlice.Index(i))
}

dstSlice = newSlice
}

for i := 0; i < srcSlice.Len(); i++ {
srcElem := srcSlice.Index(i)
dstElem := dstSlice.Index(i)

if srcElem.CanInterface() {
srcElem = reflect.ValueOf(srcElem.Interface())
}

if dstElem.CanInterface() {
dstElem = reflect.ValueOf(dstElem.Interface())
}

if dstSlice.Index(i).IsZero() && dstSlice.Index(i).IsValid() && srcElem.IsValid() {
dstSlice.Index(i).Set(srcElem)
} else {
if err = deepMerge(dstElem, srcElem, visited, depth+1, config); err != nil {
return
} else if dstSlice.Index(i).IsValid() && dstElem.IsValid() {
dstSlice.Index(i).Set(dstElem)
}
}
}
}
dst.SetMapIndex(key, dstSlice)
}
Expand Down Expand Up @@ -231,6 +267,38 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
return
}
}
} else if sliceDeepMerge {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid deeply nested control flow statements.

if src.Len() > dst.Len() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar blocks of code found in 2 locations. Consider refactoring.

newSlice := reflect.MakeSlice(dst.Type(), src.Len(), src.Len())

for i := 0; i < dst.Len(); i++ {
newSlice.Index(i).Set(dst.Index(i))
}

dst = newSlice
}

for i := 0; i < src.Len(); i++ {
srcElem := src.Index(i)
dstElem := dst.Index(i)

if srcElem.CanInterface() {
srcElem = reflect.ValueOf(srcElem.Interface())
}

if dstElem.CanInterface() {
dstElem = reflect.ValueOf(dstElem.Interface())
}

if dst.Index(i).IsZero() {
dst.Index(i).Set(srcElem)
} else {
if err = deepMerge(dstElem, srcElem, visited, depth+1, config); err != nil {
return
}
dst.Index(i).Set(dstElem)
}
}
}
case reflect.Ptr:
fallthrough
Expand Down Expand Up @@ -342,6 +410,11 @@ func WithSliceDeepCopy(config *Config) {
config.Overwrite = true
}

// WithSliceDeepMerge will make merge deep merge slice elements pairwise (resizing dst slice if needed)
func WithSliceDeepMerge(config *Config) {
config.sliceDeepMerge = true
}

func merge(dst, src interface{}, opts ...func(*Config)) error {
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerAgument
Expand Down
56 changes: 56 additions & 0 deletions pr180_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package mergo_test

import (
"encoding/json"
"fmt"
"testing"

"github.com/imdario/mergo"
)

func pp(i interface{}) string {
b, _ := json.MarshalIndent(i, "", " ")
return string(b)
}

func TestIssue121WithSliceDeepMerge(t *testing.T) {
dst := map[string]interface{}{
"a": "1",
"b": []map[string]interface{}{
{"c": "2"},
},
}

src := map[string]interface{}{
"b": []map[string]interface{}{
{"c": "3", "d": "1"},
{"e": "1", "f": "1", "g": []string{"1", "2"}},
},
}

if err := mergo.Merge(&dst, src, mergo.WithSliceDeepMerge); err != nil {
t.Fatalf("Error during the merge: %v", err)
}

fmt.Println(pp(dst))

if dst["a"].(string) != "1" {
t.Error("a should equal '1'")
}

if dst["b"].([]map[string]interface{})[0]["c"] != "2" {
t.Error("b.[0].c should equal '2'")
}

if dst["b"].([]map[string]interface{})[0]["d"] != "1" {
t.Error("b.[0].d should equal '2'")
}

if dst["b"].([]map[string]interface{})[1]["e"] != "1" {
t.Error("b.[1].e should equal '1'")
}

if dst["b"].([]map[string]interface{})[1]["g"].([]string)[0] != "1" {
t.Error("b.[1].g[0] should equal '1'")
}
}