forked from r3labs/diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_struct.go
More file actions
105 lines (79 loc) · 1.89 KB
/
diff_struct.go
File metadata and controls
105 lines (79 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package diff
import (
"reflect"
"time"
)
func (d *Differ) diffStruct(path []string, a, b reflect.Value) error {
if AreType(a, b, reflect.TypeOf(time.Time{})) {
return d.diffTime(path, a, b)
}
if a.Kind() == reflect.Invalid {
if d.DisableStructValues {
d.cl.Add(CREATE, path, nil, b.Interface())
return nil
}
return d.structValues(CREATE, path, b)
}
if b.Kind() == reflect.Invalid {
if d.DisableStructValues {
d.cl.Add(DELETE, path, a.Interface(), nil)
return nil
}
return d.structValues(DELETE, path, a)
}
for i := 0; i < a.NumField(); i++ {
field := a.Type().Field(i)
tname := tagName(d.TagName, field)
if tname == "-" || hasTagOption(d.TagName, field, "immutable") {
continue
}
if tname == "" {
tname = field.Name
}
af := a.Field(i)
bf := b.FieldByName(field.Name)
fpath := copyAppend(path, tname)
err := d.diff(fpath, af, bf)
if err != nil {
return err
}
}
return nil
}
func (d *Differ) structValues(t string, path []string, a reflect.Value) error {
var nd Differ
if t != CREATE && t != DELETE {
return ErrInvalidChangeType
}
if a.Kind() == reflect.Ptr {
a = reflect.Indirect(a)
}
if a.Kind() != reflect.Struct {
return ErrTypeMismatch
}
x := reflect.New(a.Type()).Elem()
for i := 0; i < a.NumField(); i++ {
field := a.Type().Field(i)
tname := tagName(d.TagName, field)
if tname == "-" {
continue
}
if tname == "" {
tname = field.Name
}
af := a.Field(i)
xf := x.FieldByName(field.Name)
fpath := copyAppend(path, tname)
err := nd.diff(fpath, xf, af)
if err != nil {
return err
}
}
for i := 0; i < len(nd.cl); i++ {
(d.cl) = append(d.cl, swapChange(t, nd.cl[i]))
}
return nil
}