Skip to content

Commit

Permalink
Merge pull request #57 from imdario/fix/pr-56
Browse files Browse the repository at this point in the history
Pull request #56 merged after passing tests in Travis CI
  • Loading branch information
darccio committed Jan 19, 2018
2 parents 2b9c868 + a0d0279 commit dc972c8
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
6 changes: 6 additions & 0 deletions merge.go
Expand Up @@ -56,6 +56,12 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co

if config.transformers != nil {
if fn := config.transformers.Transformer(dst.Type()); fn != nil {
if isEmptyValue(dst) {
if dst.CanSet() && !isEmptyValue(src) {
dst.Set(src)
}
return
}
err = fn(dst, src)
return
}
Expand Down
50 changes: 50 additions & 0 deletions merge_test.go
@@ -0,0 +1,50 @@
package mergo

import (
"reflect"
"testing"
)

type transformer struct {
m map[reflect.Type]func(dst, src reflect.Value) error
}

func (s *transformer) Transformer(t reflect.Type) func(dst, src reflect.Value) error {
if fn, ok := s.m[t]; ok {
return fn
}
return nil
}

type foo struct {
s string
Bar *bar
}

type bar struct {
i int
s map[string]string
}

func TestMergeWithTransformerNilStruct(t *testing.T) {
a := foo{s: "foo"}
b := foo{Bar: &bar{i: 2, s: map[string]string{"foo": "bar"}}}
if err := Merge(&a, &b, WithOverride, WithTransformers(&transformer{
m: map[reflect.Type]func(dst, src reflect.Value) error{
reflect.TypeOf(&bar{}): func(dst, src reflect.Value) error {
// Do sthg with Elem
t.Log(dst.Elem().FieldByName("i"))
t.Log(src.Elem())
return nil
},
},
})); err != nil {
t.Fatal(err)
}
if a.s != "foo" {
t.Fatalf("b not merged in properly: a.s.Value(%s) != expected(%s)", a.s, "foo")
}
if a.Bar == nil {
t.Fatalf("b not merged in properly: a.Bar shouldn't be nil")
}
}
2 changes: 2 additions & 0 deletions mergo.go
Expand Up @@ -47,6 +47,8 @@ func isEmptyValue(v reflect.Value) bool {
return v.Float() == 0
case reflect.Interface, reflect.Ptr, reflect.Func:
return v.IsNil()
case reflect.Invalid:
return true
}
return false
}
Expand Down

0 comments on commit dc972c8

Please sign in to comment.