Skip to content

Commit

Permalink
Fixes #21: incorrect behavior with Anypb.
Browse files Browse the repository at this point in the history
  • Loading branch information
mennanov committed Sep 3, 2021
1 parent ef73172 commit 45198b5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
21 changes: 12 additions & 9 deletions copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,33 +84,36 @@ func structToStruct(filter FieldFilter, src, dst *reflect.Value, userOptions *op
}

if srcAny, ok := src.Interface().(*anypb.Any); ok {
dstAny, ok := src.Interface().(*anypb.Any)
dstAny, ok := dst.Interface().(*anypb.Any)
if !ok {
return errors.Errorf("dst type is %s, expected: %s ", dst.Type(), "*any.Any")
}

newSrcProto, err := srcAny.UnmarshalNew()
srcProto, err := srcAny.UnmarshalNew()
if err != nil {
return errors.WithStack(err)
}
newSrc := reflect.ValueOf(newSrcProto)
srcProtoValue := reflect.ValueOf(srcProto)

newDstProto, err := dstAny.UnmarshalNew()
if dstAny.GetTypeUrl() == "" {
dstAny.TypeUrl = srcAny.GetTypeUrl()
}
dstProto, err := dstAny.UnmarshalNew()
if err != nil {
return errors.WithStack(err)
}
newDst := reflect.ValueOf(newDstProto)
dstProtoValue := reflect.ValueOf(dstProto)

if err := structToStruct(filter, &newSrc, &newDst, userOptions); err != nil {
if err := structToStruct(filter, &srcProtoValue, &dstProtoValue, userOptions); err != nil {
return err
}

newSrcAny := new(anypb.Any)
if err := newSrcAny.MarshalFrom(newDst.Interface().(proto.Message)); err != nil {
newDstAny := new(anypb.Any)
if err := newDstAny.MarshalFrom(dstProtoValue.Interface().(proto.Message)); err != nil {
return errors.WithStack(err)
}

dst.Set(reflect.ValueOf(newSrcAny))
dst.Set(reflect.ValueOf(newDstAny))
break
}

Expand Down
6 changes: 4 additions & 2 deletions copy_proto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ func TestStructToStruct_Proto(t *testing.T) {
func TestStructToStruct_ExistingAnyPreserved(t *testing.T) {
existingExtraUser := &testproto.User{
Id: 42,
Username: "username",
Username: "emily",
Role: testproto.Role_REGULAR,
}
existingExtraUserAny, err := anypb.New(existingExtraUser)
require.NoError(t, err)
Expand All @@ -145,7 +146,8 @@ func TestStructToStruct_ExistingAnyPreserved(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, testUserFull.Id, extraUser.Id)
assert.Equal(t, testUserFull.Avatar.OriginalUrl, extraUser.Avatar.OriginalUrl)
assert.Equal(t, "username", extraUser.Username)
assert.Equal(t, existingExtraUser.Username, extraUser.Username)
assert.Equal(t, existingExtraUser.Role, extraUser.Role)
}

func TestStructToStruct_PartialProtoSuccess(t *testing.T) {
Expand Down

0 comments on commit 45198b5

Please sign in to comment.