r3labs / diff

A library for diffing golang structures
Mozilla Public License 2.0
895 stars 84 forks source link

Fix flagging change as immutable when finding a field that has "-" ta… #45

Closed cdennig closed 3 years ago

cdennig commented 3 years ago

…g before the actual field

There is an error when flagging a field with a "-" tag in combination with patching, so that a patch to a field is not applied although it should be. Here's an example of the current behavior:

package main

import (
    "fmt"

    "github.com/r3labs/diff/v2"
)

type A struct {
    F1 string `diff:"-"`
    F2 string
}

type B struct {
    F1 string
    F2 string
}

func main() {
    a1 := A{
        F1: "test",
        F2: "value1",
    }
    a2 := A{
        F1: "test",
        F2: "value2",
    }

    la, _ := diff.Diff(&a1, &a2)
    diff.Patch(la, &a1)
    fmt.Printf("%s\n", a1.F2) // should print "value2", but prints "value1"

    b1 := B{
        F1: "test",
        F2: "value1",
    }
    b2 := B{
        F1: "test",
        F2: "value2",
    }

    lb, _ := diff.Diff(&b1, &b2)
    diff.Patch(lb, &b1)
    fmt.Printf("%s", b1.F2) // works as expected
}

The problem is: when the field tagged with "-" is found before the actual field to patch, the whole change is flagged "immutable", see patch_struct.go

The PR fixes that behavior.

purehyperbole commented 3 years ago

Hi @cdennig

Thanks for sending the fix! I'll get this merged now and cut a release.

cdennig commented 3 years ago

I think v2 is still missing the fixes, @purehyperbole.

purehyperbole commented 3 years ago

@cdennig My bad, I forgot to check the branch I was merging into :facepalm:

I'll fix this now and create a new tag

purehyperbole commented 3 years ago

@cdennig Your fix should now be available on v2.9.1. Thanks again!

go get github.com/r3labs/diff/v2@v2.9.1
cdennig commented 3 years ago

Thanks a lot! 🙏