-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.go
More file actions
59 lines (48 loc) · 1.6 KB
/
patch.go
File metadata and controls
59 lines (48 loc) · 1.6 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
package tinymapper
import (
"reflect"
"github.com/imthatgin/tinymapper/structs"
)
// This is grabbed from https://github.com/geraldo-labs/merge-struct
// and is meant to be a simple way to map fields from A to B.
// patchStruct 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.
// Skips fields with incorrect type, rather than erroring.
// Returns true if any value has been changed.
func patchStruct(target, patch interface{}) {
dst := structs.New(target)
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 these are not the same, we skip, and add them to the "skipped list"
if skind, dkind := srcValue.Kind(), dstField.Kind(); skind != dkind {
continue
}
srcType := reflect.TypeOf(srcValue.Interface())
dstType := reflect.TypeOf(dstField.Value())
if srcType != dstType {
continue
}
_ = dstField.Set(srcValue.Interface())
}
}