-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpatcher.go
284 lines (217 loc) · 9.06 KB
/
patcher.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package gopatch
import(
"reflect"
"strings"
)
// Patcher is a configurable structure patcher.
type Patcher struct {
config PatcherConfig
}
// New creates a new Patcher instance with the specified configuration. See `patcher_config.go`.
func New(config PatcherConfig) *Patcher {
return &Patcher{
config: config,
}
}
// Patch performs a patch operation on "dest", using the data in "patch". Patch returns a PatchResult if successful, or an error if not. Patch can
// also patch embedded structs and pointers to embedded structs. If a patch exists for a nil embedded struct pointer, the pointer will be assigned a
// new zero-value struct before it is patched.
func (p Patcher) Patch(dest interface{}, patch map[string]interface{}) (*PatchResult, error) {
// Error on invalid dest.
if reflect.ValueOf(dest).Kind() != reflect.Ptr ||
reflect.ValueOf(dest).IsNil() ||
reflect.ValueOf(dest).Elem().Kind() != reflect.Struct {
return nil, errDestInvalid
}
return p.patch(dest, patch, p.config.PermittedFields, true)
}
func (p Patcher) patch(dest interface{}, patch map[string]interface{}, permitted []string, root bool) (*PatchResult, error) {
// Get the actual struct data from the pointer and its type data.
valueOfDest := reflect.ValueOf(dest).Elem()
typeOfDest := valueOfDest.Type()
// Initialize and allocate space for the results.
results := PatchResult{
Fields: make([]string, 0, len(patch)*100),
Unpermitted: make([]string, 0, len(patch)*100),
Map: make(map[string]interface{}, len(patch)*100),
}
// For each field in the destination struct,
for i := 0; i < typeOfDest.NumField(); i++ {
fieldT := typeOfDest.Field(i)
fieldV := valueOfDest.Field(i)
// Skip this field if it can't be set.
if !valueOfDest.Field(i).CanSet() {
continue
}
// Get the name of the field to check for in the patch map, defaulting to the field's struct field name.
fieldName := fieldT.Name
if p.config.PatchSource != "" && p.config.PatchSource != "struct" {
testFieldName := fieldT.Tag.Get(p.config.PatchSource)
if testFieldName != "" {
fieldName = testFieldName
} else if p.config.PatchErrors {
return nil, errFieldMissingTag(fieldName, p.config.PatchSource)
}
}
// Get the patch value based on the fieldName.
if val, ok := patch[fieldName]; ok {
// Check that the field isn't unpermitted by tag. Doing this before checking the permitted list placed priority on the tag.
if fieldT.Tag.Get("gopatch") == "-" {
if p.config.UnpermittedErrors { return nil, errFieldUnpermitted(fieldName, "gopatch tag") }
results.Unpermitted = append(results.Unpermitted, fieldName)
continue
}
// Check that the field is permitted by the array, or the permitted array is empty.
if p.config.PermittedFields != nil && len(p.config.PermittedFields) > 0 {
allowed := false
for _, permit := range(permitted) {
// Break if it's an asterisk. It's auto-permitted.
if permit == "*" {
allowed = true
break
}
// Permit if exact match or "match.*".
if permit == fieldName || permit == fieldName+".*" {
allowed = true
break
}
}
// Skip field or error if it wasn't permitted.
if !allowed {
if p.config.UnpermittedErrors { return nil, errFieldUnpermitted(fieldName, "permitted array") }
results.Unpermitted = append(results.Unpermitted, fieldName)
continue
}
}
v := reflect.ValueOf(val)
// Easily assign the value if both ends' kinds are the same
if fieldV.Kind() == v.Kind() && fieldV.Kind() != reflect.Map {
fieldV.Set(v)
// Add data about the successful update to the results.
if err := p.saveToResults(&results, fieldT, val, root); err != nil { return nil, err }
// Next!
continue
}
// Check updater functions for a match.
updateSuccess := false
for _, updater := range Updaters {
// Try to update, breaking if successful
if updateSuccess = updater(fieldV, v); updateSuccess { break }
}
if updateSuccess {
// Add data about the successful update to the results.
if err := p.saveToResults(&results, fieldT, val, root); err != nil { return nil, err }
// Next!
continue
}
// Dereference the value if it's a pointer.
if fieldV.Kind() == reflect.Ptr {
// Ensure it's not nil, initializing to zero-value if needed.
if fieldV.IsNil() {
fieldV.Set(reflect.New(fieldV.Type().Elem()))
}
fieldV = fieldV.Elem()
}
// If the value is a struct, attempt to deep-patch it.
if fieldV.Kind() == reflect.Struct {
// If the map field's kind isn't map[string]interface{}, skip it.
if v.Kind() != reflect.Map || v.Type().Key().Kind() != reflect.String || v.Type().Elem().Kind() != reflect.Interface { continue }
// If the gopatch tag specifies "replace", reset the current field value to its zero value.
replace := fieldT.Tag.Get("gopatch") == "replace"
if replace {
fieldV.Set(reflect.Zero(fieldT.Type))
}
// Patch the field, even if it was reset, by recursion.
if !fieldV.CanAddr() { continue }
deep, err := p.patch(fieldV.Addr().Interface(), val.(map[string]interface{}), getPermittedInEmbedded(permitted, fieldName), false)
// If an error occurred while deep-patching, bubble up immediately.
if err != nil { return nil, err }
// Merge deep-patched results into the current results.
if err := p.mergeResults(&results, deep, fieldT, replace, root); err != nil { return nil, err }
}
}
}
return &results, nil
}
func (p *Patcher) saveToResults(r *PatchResult, dest reflect.StructField, patch interface{}, root bool) error {
// Get a field name for the fields array.
fieldName := dest.Name
if p.config.UpdatedFieldSource != "" && p.config.UpdatedFieldSource != "struct" {
testFieldName := dest.Tag.Get(p.config.UpdatedFieldSource)
if testFieldName != "" {
fieldName = testFieldName
} else if p.config.UpdatedFieldErrors {
return errFieldMissingTag(fieldName, p.config.UpdatedFieldSource)
}
}
// Prepend the embed path if this is root and there is an embed path.
if root && p.config.EmbedPath != "" { fieldName = p.config.EmbedPath+"."+fieldName }
// Append.
r.Fields = append(r.Fields, fieldName)
// Get a field name for the map.
fieldName = dest.Name
if p.config.UpdatedMapSource != "" && p.config.UpdatedMapSource != "struct" {
testFieldName := dest.Tag.Get(p.config.UpdatedMapSource)
if testFieldName != "" {
fieldName = testFieldName
} else if p.config.UpdatedMapErrors {
return errFieldMissingTag(fieldName, p.config.UpdatedMapSource)
}
}
// Prepend the embed path if this is root and there is an embed path.
if root && p.config.EmbedPath != "" { fieldName = p.config.EmbedPath+"."+fieldName }
// Add to map.
r.Map[fieldName] = patch
return nil
}
func (p *Patcher) mergeResults(top, deep *PatchResult, dest reflect.StructField, replace, root bool) error {
// Get a field name for the fields array.
fieldName := dest.Name
if p.config.UpdatedFieldSource != "" && p.config.UpdatedFieldSource != "struct" {
testFieldName := dest.Tag.Get(p.config.UpdatedFieldSource)
if testFieldName != "" {
fieldName = testFieldName
} else if p.config.UpdatedFieldErrors {
return errFieldMissingTag(fieldName, p.config.UpdatedFieldSource)
}
}
// Prepend the embed path if this is root and there is an embed path.
if root && p.config.EmbedPath != "" { fieldName = p.config.EmbedPath+"."+fieldName }
// Map field names to path and append.
if replace {
top.Fields = append(top.Fields, fieldName)
} else {
for _, field := range(deep.Fields) {
top.Fields = append(top.Fields, fieldName+"."+field)
}
}
// Get a field name for the map.
fieldName = dest.Name
if p.config.UpdatedMapSource != "" && p.config.UpdatedMapSource != "struct" {
testFieldName := dest.Tag.Get(p.config.UpdatedMapSource)
if testFieldName != "" {
fieldName = testFieldName
} else if p.config.UpdatedMapErrors {
return errFieldMissingTag(fieldName, p.config.UpdatedMapSource)
}
}
// Prepend the embed path if this is root.
if root && p.config.EmbedPath != "" { fieldName = p.config.EmbedPath+"."+fieldName }
if replace {
top.Map[fieldName] = deep.Map
} else {
for k, v := range(deep.Map) {
top.Map[fieldName+"."+k] = v
}
}
return nil
}
func getPermittedInEmbedded(permitted []string, fieldName string) []string {
if len(permitted) == 0 { return []string{ "*" } }
out := make([]string, 0, len(permitted))
for _, permitted := range(permitted) {
if permitted == fieldName+".*" { return []string{ "*" } }
if strings.HasPrefix(permitted, fieldName+".") { out = append(out, permitted[len(fieldName)+1:])}
}
return out
}