mennanov / fieldmask-utils

Protobuf Field Mask Go utils
MIT License
229 stars 26 forks source link

Preserve field values in dst #1

Closed hypnoglow closed 5 years ago

hypnoglow commented 5 years ago

Hi, thanks for the lib.

Currently, when copying structs, the behavior of preserving fields in dst not consistent. Top-level struct fields are always preserved, but nested struct fields are always zeroed (if mask targets other fields).

Example test case:


func TestStructToStruct(t *testing.T) {
    type (
        Author struct {
            FirstName string
            LastName string
        }
        Document struct {
            Title string
            Date string
            Author Author
        }
    )

    dst := &Document{
        Title:  "Hello, World!",
        Date: "2019-05-01",
        Author: Author{
            FirstName: "John",
            LastName:  "Doe",
        },
    }
    src := &Document{
        Title: "Hello, updated World!",
        Author: Author{
            FirstName: "Johnny",
        },
    }
    expected := &Document{
        Title:  "Hello, updated World!",
        Date: "2019-05-01",
        Author: Author{
            FirstName: "Johnny",
            LastName:  "Doe",
        },
    }

    mask := fieldmask_utils.MaskFromString("Title,Author{FirstName}")
    err := fieldmask_utils.StructToStruct(mask, src, dst)
    require.NoError(t, err)

    assert.Equal(t, expected, dst)
}

In the result of this example, field "Date" is preserved in dst, but field "Author.LastName" is not.

mennanov commented 5 years ago

Thanks for reporting, i'm working on a fix.

mennanov commented 5 years ago

Try this updated code, please: https://github.com/mennanov/fieldmask-utils/commit/f2a0c0d9beac5c71904a954e3d8cc5777d50d5cb And let me know if it fixes the bug you mentioned.

Thanks

mennanov commented 5 years ago

The master branch is now updated and has that fix.