-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplystruct.go
More file actions
422 lines (372 loc) · 12.4 KB
/
applystruct.go
File metadata and controls
422 lines (372 loc) · 12.4 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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package structdiff
import (
"fmt"
"reflect"
"strconv"
"time"
)
// ApplyToStruct applies a patch map to a struct, modifying the struct in-place.
// The patch should be generated by Diff or follow the same format.
//
// Rules:
// - nil values in patch: delete/zero the field if possible, error if field is not nillable
// - Type mismatches: attempt conversion for compatible types, error otherwise
// - JSON tags: honored for field mapping
// - any fields: accept any value type
// - Numeric conversions: attempted (like JSON deserialization)
//
// Returns an error if the patch cannot be applied due to type incompatibilities
// or structural constraints.
func ApplyToStruct(target any, patch map[string]any) error {
if patch == nil {
return nil
}
targetVal := reflect.ValueOf(target)
if !targetVal.IsValid() {
return fmt.Errorf("target is nil")
}
// Target must be a pointer to a struct so we can modify it
if targetVal.Kind() != reflect.Pointer {
return fmt.Errorf("target must be a pointer to a struct, got %T", target)
}
structVal := targetVal.Elem()
if structVal.Kind() != reflect.Struct {
return fmt.Errorf("target must point to a struct, got pointer to %s", structVal.Kind())
}
structType := structVal.Type()
// Apply each change in the patch
for patchKey, patchValue := range patch {
if err := applyFieldPatch(structVal, structType, patchKey, patchValue); err != nil {
return fmt.Errorf("failed to apply patch for field %q: %w", patchKey, err)
}
}
return nil
}
func applyFieldPatch(structVal reflect.Value, structType reflect.Type, fieldName string, patchValue any) error {
// Find the field by JSON name
fieldIndex, field, err := findFieldByJSONName(structType, fieldName)
if err != nil {
return err
}
fieldVal := structVal.Field(fieldIndex)
if !fieldVal.CanSet() {
return fmt.Errorf("field %q is not settable", fieldName)
}
// Handle nil patch values (deletions/zeroing)
if patchValue == nil {
return setFieldToNil(fieldVal, field, fieldName)
}
// Handle nested map patches for struct fields
if patchMap, isPatchMap := patchValue.(map[string]any); isPatchMap && fieldVal.Kind() == reflect.Struct {
// For struct fields, recursively apply the patch
if !fieldVal.CanAddr() {
return fmt.Errorf("cannot get address of struct field %q for nested patching", fieldName)
}
fieldPtr := fieldVal.Addr().Interface()
return ApplyToStruct(fieldPtr, patchMap)
}
// Handle pointer fields
if fieldVal.Kind() == reflect.Pointer {
return setPointerField(fieldVal, patchValue, fieldName)
}
// Convert and set the value
return setFieldValue(fieldVal, patchValue, fieldName)
}
func findFieldByJSONName(structType reflect.Type, jsonName string) (int, reflect.StructField, error) {
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
if !field.IsExported() {
continue
}
tag := field.Tag.Get("json")
if tag == "-" {
continue
}
fieldJSONName := parseName(tag, field.Name)
if fieldJSONName == jsonName {
return i, field, nil
}
}
return -1, reflect.StructField{}, fmt.Errorf("field %q not found", jsonName)
}
func setFieldToNil(fieldVal reflect.Value, field reflect.StructField, fieldName string) error {
switch fieldVal.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Map, reflect.Interface:
// These types can be set to nil
fieldVal.Set(reflect.Zero(fieldVal.Type()))
return nil
default:
// Cannot set non-pointer/slice/map/interface fields to nil
return fmt.Errorf("cannot set non-nillable field %q (type %s) to nil", fieldName, fieldVal.Type())
}
}
func setPointerField(fieldVal reflect.Value, patchValue any, fieldName string) error {
elemType := fieldVal.Type().Elem()
// Create new instance of the element type
newElem := reflect.New(elemType)
// Special case: if patch is a map and element type is a struct, apply patch to struct
if patchMap, isPatchMap := patchValue.(map[string]any); isPatchMap && elemType.Kind() == reflect.Struct {
if err := ApplyToStruct(newElem.Interface(), patchMap); err != nil {
return err
}
} else {
// Set the value to the dereferenced element
if err := setFieldValue(newElem.Elem(), patchValue, fieldName); err != nil {
return err
}
}
// Set the pointer to point to the new element
fieldVal.Set(newElem)
return nil
}
func setFieldValue(fieldVal reflect.Value, patchValue any, fieldName string) error {
patchVal := reflect.ValueOf(patchValue)
fieldType := fieldVal.Type()
patchType := patchVal.Type()
// Special case: If this is a map[string]any field and the patch is also a map[string]any,
// use ApplyToMap for merging instead of direct assignment
if fieldType == reflect.TypeOf(map[string]any{}) && isMap(patchValue) {
var originalMap map[string]any
if !fieldVal.IsNil() {
originalMap = fieldVal.Interface().(map[string]any)
}
patchMap := patchValue.(map[string]any)
resultMap := ApplyToMap(originalMap, patchMap)
fieldVal.Set(reflect.ValueOf(resultMap))
return nil
}
// Direct assignment if types match
if patchType.AssignableTo(fieldType) {
fieldVal.Set(patchVal)
return nil
}
// Handle any/interface{} fields - accept any value
if fieldType.Kind() == reflect.Interface && fieldType.NumMethod() == 0 {
fieldVal.Set(patchVal)
return nil
}
// Handle time.Time specially
if fieldType == reflect.TypeOf(time.Time{}) {
return setTimeField(fieldVal, patchValue, fieldName)
}
// Handle type conversions
switch fieldType.Kind() {
case reflect.String:
return setStringField(fieldVal, patchValue, fieldName)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return setIntField(fieldVal, patchValue, fieldName)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return setUintField(fieldVal, patchValue, fieldName)
case reflect.Float32, reflect.Float64:
return setFloatField(fieldVal, patchValue, fieldName)
case reflect.Bool:
return setBoolField(fieldVal, patchValue, fieldName)
case reflect.Slice:
return setSliceField(fieldVal, patchValue, fieldName)
case reflect.Map:
return setMapField(fieldVal, patchValue, fieldName)
default:
return fmt.Errorf("cannot convert %T to %s for field %q", patchValue, fieldType, fieldName)
}
}
func setTimeField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case time.Time:
fieldVal.Set(reflect.ValueOf(v))
return nil
case string:
// Try to parse common time formats
formats := []string{
time.RFC3339,
time.RFC3339Nano,
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, format := range formats {
if t, err := time.Parse(format, v); err == nil {
fieldVal.Set(reflect.ValueOf(t))
return nil
}
}
return fmt.Errorf("cannot parse time string %q for field %q", v, fieldName)
default:
return fmt.Errorf("cannot convert %T to time.Time for field %q", patchValue, fieldName)
}
}
func setStringField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case string:
fieldVal.SetString(v)
case []byte:
fieldVal.SetString(string(v))
default:
// Convert other types to string
fieldVal.SetString(fmt.Sprintf("%v", patchValue))
}
return nil
}
func setIntField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case int:
fieldVal.SetInt(int64(v))
case int8:
fieldVal.SetInt(int64(v))
case int16:
fieldVal.SetInt(int64(v))
case int32:
fieldVal.SetInt(int64(v))
case int64:
fieldVal.SetInt(v)
case uint, uint8, uint16, uint32, uint64:
uintVal := reflect.ValueOf(v).Uint()
fieldVal.SetInt(int64(uintVal))
case float32:
fieldVal.SetInt(int64(v))
case float64:
fieldVal.SetInt(int64(v))
case string:
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
fieldVal.SetInt(i)
} else {
return fmt.Errorf("cannot convert string %q to int for field %q", v, fieldName)
}
default:
return fmt.Errorf("cannot convert %T to int for field %q", patchValue, fieldName)
}
return nil
}
func setUintField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case uint:
fieldVal.SetUint(uint64(v))
case uint8:
fieldVal.SetUint(uint64(v))
case uint16:
fieldVal.SetUint(uint64(v))
case uint32:
fieldVal.SetUint(uint64(v))
case uint64:
fieldVal.SetUint(v)
case int, int8, int16, int32, int64:
intVal := reflect.ValueOf(v).Int()
if intVal < 0 {
return fmt.Errorf("cannot convert negative value %d to uint for field %q", intVal, fieldName)
}
fieldVal.SetUint(uint64(intVal))
case float32:
if v < 0 {
return fmt.Errorf("cannot convert negative value %f to uint for field %q", v, fieldName)
}
fieldVal.SetUint(uint64(v))
case float64:
if v < 0 {
return fmt.Errorf("cannot convert negative value %f to uint for field %q", v, fieldName)
}
fieldVal.SetUint(uint64(v))
case string:
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
fieldVal.SetUint(u)
} else {
return fmt.Errorf("cannot convert string %q to uint for field %q", v, fieldName)
}
default:
return fmt.Errorf("cannot convert %T to uint for field %q", patchValue, fieldName)
}
return nil
}
func setFloatField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case float32:
fieldVal.SetFloat(float64(v))
case float64:
fieldVal.SetFloat(v)
case int, int8, int16, int32, int64:
intVal := reflect.ValueOf(v).Int()
fieldVal.SetFloat(float64(intVal))
case uint, uint8, uint16, uint32, uint64:
uintVal := reflect.ValueOf(v).Uint()
fieldVal.SetFloat(float64(uintVal))
case string:
if f, err := strconv.ParseFloat(v, 64); err == nil {
fieldVal.SetFloat(f)
} else {
return fmt.Errorf("cannot convert string %q to float for field %q", v, fieldName)
}
default:
return fmt.Errorf("cannot convert %T to float for field %q", patchValue, fieldName)
}
return nil
}
func setBoolField(fieldVal reflect.Value, patchValue any, fieldName string) error {
switch v := patchValue.(type) {
case bool:
fieldVal.SetBool(v)
case string:
if b, err := strconv.ParseBool(v); err == nil {
fieldVal.SetBool(b)
} else {
return fmt.Errorf("cannot convert string %q to bool for field %q", v, fieldName)
}
case int, int8, int16, int32, int64:
intVal := reflect.ValueOf(v).Int()
fieldVal.SetBool(intVal != 0)
case uint, uint8, uint16, uint32, uint64:
uintVal := reflect.ValueOf(v).Uint()
fieldVal.SetBool(uintVal != 0)
case float32, float64:
floatVal := reflect.ValueOf(v).Float()
fieldVal.SetBool(floatVal != 0)
default:
return fmt.Errorf("cannot convert %T to bool for field %q", patchValue, fieldName)
}
return nil
}
func setSliceField(fieldVal reflect.Value, patchValue any, fieldName string) error {
patchVal := reflect.ValueOf(patchValue)
if patchVal.Kind() != reflect.Slice && patchVal.Kind() != reflect.Array {
return fmt.Errorf("cannot convert %T to slice for field %q", patchValue, fieldName)
}
newSlice := reflect.MakeSlice(fieldVal.Type(), patchVal.Len(), patchVal.Len())
for i := 0; i < patchVal.Len(); i++ {
elemVal := newSlice.Index(i)
patchElem := patchVal.Index(i).Interface()
if err := setFieldValue(elemVal, patchElem, fmt.Sprintf("%s[%d]", fieldName, i)); err != nil {
return err
}
}
fieldVal.Set(newSlice)
return nil
}
func setMapField(fieldVal reflect.Value, patchValue any, fieldName string) error {
patchVal := reflect.ValueOf(patchValue)
if patchVal.Kind() != reflect.Map {
return fmt.Errorf("cannot convert %T to map for field %q", patchValue, fieldName)
}
mapType := fieldVal.Type()
// For all map types, use the original behavior (complete replacement)
// Note: map[string]any is handled in setFieldValue() with ApplyToMap
newMap := reflect.MakeMap(mapType)
keyType := mapType.Key()
valueType := mapType.Elem()
for _, key := range patchVal.MapKeys() {
mapKey := key
mapValue := reflect.New(valueType).Elem()
// Convert key if necessary
if !key.Type().AssignableTo(keyType) {
convertedKey := reflect.New(keyType).Elem()
if err := setFieldValue(convertedKey, key.Interface(), fmt.Sprintf("%s[key]", fieldName)); err != nil {
return fmt.Errorf("cannot convert map key: %w", err)
}
mapKey = convertedKey
}
// Convert value
patchMapValue := patchVal.MapIndex(key).Interface()
if err := setFieldValue(mapValue, patchMapValue, fmt.Sprintf("%s[%v]", fieldName, key.Interface())); err != nil {
return err
}
newMap.SetMapIndex(mapKey, mapValue)
}
fieldVal.Set(newMap)
return nil
}