Skip to content

Commit

Permalink
fix pointers when convert types is enabled
Browse files Browse the repository at this point in the history
  • Loading branch information
purehyperbole committed Dec 16, 2021
1 parent 314e509 commit be3229d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
25 changes: 20 additions & 5 deletions change_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,27 @@ func (c *ChangeValue) Set(value reflect.Value, convertCompatibleTypes bool) {
}

if convertCompatibleTypes {
if !value.Type().ConvertibleTo(c.target.Type()) {
c.AddError(fmt.Errorf("Value of type %s is not convertible to %s", value.Type().String(), c.target.Type().String()))
c.SetFlag(FlagFailed)
return
if c.target.Kind() == reflect.Ptr && value.Kind() != reflect.Ptr {
if !value.Type().ConvertibleTo(c.target.Elem().Type()) {
c.AddError(fmt.Errorf("Value of type %s is not convertible to %s", value.Type().String(), c.target.Type().String()))
c.SetFlag(FlagFailed)
return
}

fmt.Println(c.target.Elem().Type())

tv := reflect.New(c.target.Elem().Type())
tv.Elem().Set(value.Convert(c.target.Elem().Type()))
c.target.Set(tv)
} else {
if !value.Type().ConvertibleTo(c.target.Type()) {
c.AddError(fmt.Errorf("Value of type %s is not convertible to %s", value.Type().String(), c.target.Type().String()))
c.SetFlag(FlagFailed)
return
}

c.target.Set(value.Convert(c.target.Type()))
}
c.target.Set(value.Convert(c.target.Type()))
} else {
if value.IsValid() {
if c.target.Kind() == reflect.Ptr && value.Kind() != reflect.Ptr {
Expand Down
30 changes: 30 additions & 0 deletions patch_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package diff_test

import (
"encoding/json"
"testing"
"time"

Expand Down Expand Up @@ -303,3 +304,32 @@ func TestPatchPointer(t *testing.T) {
patchLog := diff.Patch(changelog, &t1)
assert.False(t, patchLog.HasErrors())
}

func TestPatchPointerConvertTypes(t *testing.T) {
type tps struct {
S *int
}

val1 := 1
val2 := 2

t1 := tps{S: &val1}
t2 := tps{S: &val2}

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

js, err := json.Marshal(changelog)
assert.NoError(t, err)

assert.NoError(t, json.Unmarshal(js, &changelog))

d, err := diff.NewDiffer(diff.ConvertCompatibleTypes())
assert.NoError(t, err)

assert.Equal(t, 1, *t1.S)

patchLog := d.Patch(changelog, &t1)
assert.False(t, patchLog.HasErrors())
assert.Equal(t, 2, *t1.S)
}

0 comments on commit be3229d

Please sign in to comment.