Skip to content

Commit

Permalink
fix: add map with pointer value support (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
23doors authored Jan 31, 2022
1 parent b723d66 commit b53a548
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions diff_pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@ func (d *Differ) diffPtr(path []string, a, b reflect.Value, parent interface{})
if !b.IsNil() {
return d.diff(path, reflect.ValueOf(nil), reflect.Indirect(b), parent)
}

d.cl.Add(CREATE, path, nil, exportInterface(b), parent)
return nil
}

if b.Kind() == reflect.Invalid {
if !a.IsNil() {
return d.diff(path, reflect.Indirect(a), reflect.ValueOf(nil), parent)
}

d.cl.Add(DELETE, path, exportInterface(a), nil, parent)
return nil
}

return ErrTypeMismatch
Expand Down
8 changes: 8 additions & 0 deletions patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ func (d *Differ) renderChangeTarget(c *ChangeValue) {

//walking a path means dealing with real elements
case reflect.Interface, reflect.Ptr:
if c.target.IsNil() {
n := reflect.New(c.target.Type().Elem())
c.target.Set(n)
c.target = &n
d.renderChangeTarget(c)
return
}

el := c.target.Elem()
c.target = &el
c.ClearFlag(FlagInvalidTarget)
Expand Down
28 changes: 28 additions & 0 deletions patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,34 @@ func TestPatch(t *testing.T) {
assert.False(t, patchLog.HasErrors())
})

t.Run("map-to-pointer", func(t *testing.T) {
t1 := make(map[string]*tmstruct)
t2 := map[string]*tmstruct{"after": {Foo: "val"}}

changelog, err := diff.Diff(t1, t2)
assert.NoError(t, err)

patchLog := diff.Patch(changelog, &t1)
assert.False(t, patchLog.HasErrors())

assert.True(t, len(t2) == len(t1))
assert.Equal(t, t1["after"], &tmstruct{Foo: "val"})
})

t.Run("map-to-nil-pointer", func(t *testing.T) {
t1 := make(map[string]*tmstruct)
t2 := map[string]*tmstruct{"after": nil}

changelog, err := diff.Diff(t1, t2)
assert.NoError(t, err)

patchLog := diff.Patch(changelog, &t1)
assert.False(t, patchLog.HasErrors())

assert.Equal(t, len(t2), len(t1))
assert.Nil(t, t1["after"])
})

t.Run("pointer-with-converted-type", func(t *testing.T) {
type tps struct {
S *int
Expand Down

0 comments on commit b53a548

Please sign in to comment.