r3labs / diff

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

Show entire struct data in From/To even though it's only partially updated #75

Open domluna opened 2 years ago

domluna commented 2 years ago
package main

import (
    "fmt"

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

type Data struct {
    ID    int32  `json:"id" diff:"ID"`
    Value string `json:"value" diff:"Value"`
}

type Order struct {
    Items []Data `diff:"Items,ID"`
}

func main() {
    a := Order{
        Items: []Data{Data{ID: 1, Value: "foo"}},
    }

    b := Order{
        Items: []Data{Data{ID: 1, Value: "bar"}, Data{ID: 2, Value: "paper"}},
    }

    changelog, err := diff.Diff(a, b, diff.DisableStructValues())
    if err != nil {
        fmt.Println("ERROR", err)
        return
    }
    fmt.Printf("%+v\n", changelog)

}

Output

[{Type:update Path:[Items 0 Value] From:foo To:bar parent:{ID:1 Value:foo}} {Type:create Path:[Items 1] From:<nil> To:{ID:2 Value:paper} parent:<nil>}]

What I would like is a way so that instead of

{Type:update Path:[Items 0 Value] From:foo To:bar parent:{ID:1 Value:foo}}

I get

{Type:update Path:[Items 0 Value] From:{ID: 1 Value: foo} To:{ID: 1 Value: bar} parent:{ID:1 Value:foo}}
fdmsantos commented 2 years ago

Hello,

See if this PR helps you.

Regards

domluna commented 2 years ago

I tried editing based on the example in the PR but It doesn't seem to do what I want and I don't think it will at least from my understanding. Basically it will stop delving into a type or field but that's not want I want. I want it to delve into the fields but return the entire struct as the diff rather than just the field that changed.

ryskiz commented 2 years ago

I also think this would be pretty useful to include. I'm diffing nested structs inside of slices and it would be nice to also have the entire struct that changed instead of just the path and the exact value that changed. I know that the parent field exists but it's not a public field. Maybe making parent public is the way to go here?