-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstruct.go
61 lines (49 loc) · 1.67 KB
/
struct.go
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
package patch
import (
"fmt"
"reflect"
"github.com/fatih/structs"
)
// Struct updates the target struct in-place with non-zero values from the patch struct.
// Only fields with the same name and type get updated. Fields in the patch struct can be
// pointers to the target's type.
//
// Returns true if any value has been changed.
func Struct(target, patch interface{}) (changed bool, err error) {
var dst = structs.New(target)
var fields = structs.New(patch).Fields() // work stack
for N := len(fields); N > 0; N = len(fields) {
var srcField = fields[N-1] // pop the top
fields = fields[:N-1]
if ! srcField.IsExported() {
continue // skip unexported fields
}
if srcField.IsEmbedded() {
// add the embedded fields into the work stack
fields = append(fields, srcField.Fields()...)
continue
}
if srcField.IsZero() {
continue // skip zero-value fields
}
var name = srcField.Name()
var dstField, ok = dst.FieldOk(name)
if !ok {
continue // skip non-existing fields
}
var srcValue = reflect.ValueOf(srcField.Value())
srcValue = reflect.Indirect(srcValue)
if skind, dkind := srcValue.Kind(), dstField.Kind(); skind != dkind {
err = fmt.Errorf("field `%v` types mismatch while patching: %v vs %v", name, dkind, skind)
return
}
if ! reflect.DeepEqual(srcValue.Interface(), dstField.Value()) {
changed = true
}
err = dstField.Set(srcValue.Interface())
if err != nil {
return
}
}
return
}