Skip to content

Commit

Permalink
fix patch assignment to pointer values
Browse files Browse the repository at this point in the history
  • Loading branch information
purehyperbole committed Dec 14, 2021
1 parent ad087c2 commit 314e509
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion change_value.go
Expand Up @@ -108,8 +108,10 @@ func (c *ChangeValue) Set(value reflect.Value, convertCompatibleTypes bool) {
if r := recover(); r != nil {
c.AddError(NewError(r.(string)))
c.SetFlag(FlagFailed)

}
}()

if c.HasFlag(OptionImmutable) {
c.SetFlag(FlagIgnored)
return
Expand All @@ -124,7 +126,13 @@ func (c *ChangeValue) Set(value reflect.Value, convertCompatibleTypes bool) {
c.target.Set(value.Convert(c.target.Type()))
} else {
if value.IsValid() {
c.target.Set(value)
if c.target.Kind() == reflect.Ptr && value.Kind() != reflect.Ptr {
tv := reflect.New(value.Type())
tv.Elem().Set(value)
c.target.Set(tv)
} else {
c.target.Set(value)
}
} else if !c.target.IsZero() {
t := c.target.Elem()
t.Set(reflect.Zero(t.Type()))
Expand Down
18 changes: 18 additions & 0 deletions patch_test.go
Expand Up @@ -285,3 +285,21 @@ func TestPatch(t *testing.T) {
require.Equal(t, len(cl), len(pl))
})
}

func TestPatchPointer(t *testing.T) {
type tps struct {
S *string
}

str1 := "before"
str2 := "after"

t1 := tps{S: &str1}
t2 := tps{S: &str2}

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

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

0 comments on commit 314e509

Please sign in to comment.