-
Notifications
You must be signed in to change notification settings - Fork 2
/
withopts.go
475 lines (427 loc) · 14.6 KB
/
withopts.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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package evendeep
import (
"encoding/json"
"github.com/hedzr/evendeep/flags"
"github.com/hedzr/evendeep/flags/cms"
)
// Opt options functor.
type Opt func(c *cpController)
// WithValueConverters gives a set of ValueConverter.
// The value converters will be applied on its Match returns ok.
func WithValueConverters(cvt ...ValueConverter) Opt {
return func(c *cpController) {
c.valueConverters = append(c.valueConverters, cvt...)
}
}
// WithValueCopiers gives a set of ValueCopier.
// The value copiers will be applied on its Match returns ok.
func WithValueCopiers(cvt ...ValueCopier) Opt {
return func(c *cpController) {
c.valueCopiers = append(c.valueCopiers, cvt...)
}
}
// WithTryApplyConverterAtFirst specifies which is first when
// trying/applying ValueConverters and ValueCopiers.
func WithTryApplyConverterAtFirst(b bool) Opt {
return func(c *cpController) {
c.tryApplyConverterAtFirst = b
}
}
// WithTryApplyConverterAtFirstOpt is shortcut of WithTryApplyConverterAtFirst(true).
var WithTryApplyConverterAtFirstOpt = WithTryApplyConverterAtFirst(true) //nolint:gochecknoglobals //i know that
// WithSourceValueExtractor specify a source field value extractor,
// which will be applied on each field being copied to target.
//
// Just work for non-nested struct.
//
// For instance:
//
// c := context.WithValue(context.TODO(), "Data", map[string]typ.Any{
// "A": 12,
// })
//
// tgt := struct {
// A int
// }{}
//
// evendeep.DeepCopy(c, &tgt,
// evendeep.WithSourceValueExtractor(func(targetName string) typ.Any {
// if m, ok := c.Value("Data").(map[string]typ.Any); ok {
// return m[targetName]
// }
// return nil
// }))
//
// if tgt.A != 12 {
// t.FailNow()
// }
func WithSourceValueExtractor(e SourceValueExtractor) Opt {
return func(c *cpController) {
c.sourceExtractor = e
}
}
// WithTargetValueSetter _
//
// In the TargetValueSetter you could return evendeep.ErrShouldFallback to
// call the evendeep standard processing.
//
// TargetValueSetter can work for struct and map.
//
// NOTE that the sourceNames[0] is current field name, and the whole
// sourceNames slice includes the path of the nested struct(s),
// in reversal order.
//
// For instance:
//
// type srcS struct {
// A int
// B bool
// C string
// }
//
// src := &srcS{
// A: 5,
// B: true,
// C: helloString,
// }
// tgt := map[string]typ.Any{
// "Z": "str",
// }
//
// err := evendeep.New().CopyTo(src, &tgt,
// evendeep.WithTargetValueSetter(
// func(value *reflect.Value, sourceNames ...string) (err error) {
// if value != nil {
// name := "Mo" + strings.Join(sourceNames, ".")
// tgt[name] = value.Interface()
// }
// return // ErrShouldFallback to call the evendeep standard processing
// }),
// )
//
// if err != nil || tgt["MoA"] != 5 || tgt["MoB"] != true || tgt["MoC"] != helloString || tgt["Z"] != "str" {
// t.Errorf("err: %v, tgt: %v", err, tgt)
// t.FailNow()
// }
func WithTargetValueSetter(e TargetValueSetter) Opt {
return func(c *cpController) {
c.targetSetter = e
}
}
// WithCloneStyle sets the cpController to clone mode.
// In this mode, source object will be cloned to a new
// object and returned as new target object.
func WithCloneStyle() Opt {
return func(c *cpController) {
c.makeNewClone = true
}
}
// WithCopyStyle sets the cpController to copier mode.
// In this mode, source object will be deepcopied to
// target object.
func WithCopyStyle() Opt {
return func(c *cpController) {
c.makeNewClone = false
}
}
// WithStrategies appends more flags into *cpController.
//
// For example:
//
// WithStrategies(cms.OmitIfZero, cms.OmitIfNil, cms.OmitIfEmpty, cms.NoOmit)
// WithStrategies(cms.ClearIfMissed, cms.ClearIfInvalid)
// WithStrategies(cms.KeepIfNotEq, cms.ClearIfEq)
func WithStrategies(flagsList ...cms.CopyMergeStrategy) Opt {
return func(c *cpController) {
if c.flags == nil {
c.flags = flags.New(flagsList...)
} else {
for _, f := range flagsList {
c.flags[f] = true
}
}
}
}
// WithCleanStrategies set the given flags into *cpController, older
// flags will be clear at first.
func WithCleanStrategies(flagsList ...cms.CopyMergeStrategy) Opt {
return func(c *cpController) {
c.flags = flags.New(flagsList...)
}
}
// WithByNameStrategyOpt is synonym of cms.ByName by calling WithCleanStrategies.
//
// If you're using WithByNameStrategyOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithByNameStrategyOpt = WithCleanStrategies(cms.ByName) //nolint:gochecknoglobals //i know that
// WithByOrdinalStrategyOpt is synonym of cms.ByOrdinal by calling WithCleanStrategies.
//
// If you're using WithByOrdinalStrategyOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithByOrdinalStrategyOpt = WithCleanStrategies(cms.ByOrdinal) //nolint:gochecknoglobals //i know that
// WithCopyStrategyOpt is synonym of cms.SliceCopy + cms.MapCopy by calling WithCleanStrategies.
//
// If you're using WithCopyStrategyOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithCopyStrategyOpt = WithCleanStrategies(cms.SliceCopy, cms.MapCopy) //nolint:gochecknoglobals //i know that
// WithMergeStrategyOpt is synonym of cms.SliceMerge + cms.MapMerge by calling WithCleanStrategies.
//
// If you're using WithMergeStrategyOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithMergeStrategyOpt = WithCleanStrategies(cms.SliceMerge, cms.MapMerge) //nolint:gochecknoglobals //i know that
// WithORMDiffOpt is synonym of cms.ClearIfEq + cms.KeepIfNotEq + cms.ClearIfInvalid by calling WithCleanStrategies.
//
// If you're using WithORMDiffOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithORMDiffOpt = WithCleanStrategies(cms.ClearIfEq, cms.KeepIfNotEq, cms.ClearIfInvalid) //nolint:gochecknoglobals,lll //i know that
// WithOmitEmptyOpt is synonym of cms.OmitIfEmpty by calling Clean.
//
// If you're using WithOmitEmptyOpt and WithStrategies(...) at same time, please notes it
// will clear any existent flags before setting.
var WithOmitEmptyOpt = WithCleanStrategies(cms.OmitIfEmpty) //nolint:gochecknoglobals //i know that
// WithStrategiesReset clears the exists flags in a *cpController.
// So that you can append new ones (with WithStrategies(flags...)).
//
// In generally, WithStrategiesReset is synonym of cms.SliceCopy +
// cms.MapCopy, since all strategies are cleared. A nothing Flags
// means that a set of default strategies will be applied,
// in other words, its include:
//
// cms.Default, cms.NoOmit, cms.NoOmitTarget,
// cms.SliceCopy, cms.MapCopy,
// cms.ByOrdinal,
//
// If a flagsList supplied, WithStrategiesReset will add them and
// set the state to false.
func WithStrategiesReset(flagsList ...cms.CopyMergeStrategy) Opt {
return func(c *cpController) {
c.flags = flags.New(flagsList...)
for _, fx := range flagsList {
if _, ok := c.flags[fx]; ok {
c.flags[fx] = false
}
}
}
}
// WithAutoExpandForInnerStruct does copy fields with flat struct.
// When autoExpandForInnerStruct is enabled, the iterator will go into
// any embedded struct and traverse its fields with a flatten mode.
//
// For instance, the iteration on struct:
//
// type A struct {
// F1 string
// F2 int
// }
// type B struct {
// F1 bool
// F2 A
// F3 float32
// }
//
// will produce the sequences:
//
// B.F1, B.F2, B.F2 - A.F1, B.F2 - A.F2, B.F3
//
// Default is true.
func WithAutoExpandForInnerStruct(autoExpand bool) Opt {
return func(c *cpController) {
c.autoExpandStruct = autoExpand
}
}
// WithAutoExpandStructOpt is synonym of WithAutoExpandForInnerStruct(true).
var WithAutoExpandStructOpt = WithAutoExpandForInnerStruct(true) //nolint:gochecknoglobals //i know that
// WithAutoNewForStructField does create new instance on ptr field of a struct.
//
// When cloning to a new target object, it might be helpful.
//
// Default is true.
func WithAutoNewForStructField(autoNew bool) Opt {
return func(c *cpController) {
c.autoNewStruct = autoNew
}
}
// WithAutoNewForStructFieldOpt is synonym of WithAutoNewForStructField(true).
var WithAutoNewForStructFieldOpt = WithAutoNewForStructField(true) //nolint:gochecknoglobals //i know that
// WithCopyUnexportedField try to copy the unexported fields
// with special way.
//
// This feature needs unsafe package present.
//
// Default is true.
func WithCopyUnexportedField(b bool) Opt {
return func(c *cpController) {
c.copyUnexportedFields = b
}
}
// WithCopyUnexportedFieldOpt is shortcut of WithCopyUnexportedField.
var WithCopyUnexportedFieldOpt = WithCopyUnexportedField(true) //nolint:gochecknoglobals //i know that
// WithCopyFunctionResultToTarget invoke source function member and
// pass the result to the responsible target field.
//
// It just works when target field is acceptable.
//
// Default is true.
func WithCopyFunctionResultToTarget(b bool) Opt {
return func(c *cpController) {
c.copyFunctionResultToTarget = b
}
}
// WithCopyFunctionResultToTargetOpt is shortcut of WithCopyFunctionResultToTarget.
var WithCopyFunctionResultToTargetOpt = WithCopyFunctionResultToTarget(true) //nolint:gochecknoglobals //i know that
// WithPassSourceToTargetFunction invoke target function member and
// pass the source as its input parameters.
//
// Default is true.
func WithPassSourceToTargetFunction(b bool) Opt {
return func(c *cpController) {
c.passSourceAsFunctionInArgs = b
}
}
// WithPassSourceToTargetFunctionOpt is shortcut of WithPassSourceToTargetFunction.
var WithPassSourceToTargetFunctionOpt = WithPassSourceToTargetFunction(true) //nolint:gochecknoglobals //i know that
// WithSyncAdvancing decides how to advance to next field especially
// a source field had been ignored.
// By default, (false), the target field won't be advanced while the
// source field had been ignored.
// For sync-advanced flag is true, the target field step to next.
//
// Just for cms.ByOrdinal mode.
func WithSyncAdvancing(syncAdvancing bool) Opt {
return func(c *cpController) {
c.advanceTargetFieldPointerEvenIfSourceIgnored = syncAdvancing
}
}
// WithSyncAdvancingOpt is synonym of WithAutoExpandForInnerStruct(true).
var WithSyncAdvancingOpt = WithSyncAdvancing(true) //nolint:gochecknoglobals //i know that
// WithWipeTargetSliceFirst enables the option which assumes the target
// Slice or Map will be wipe out at first before copying/merging from
// source field.
func WithWipeTargetSliceFirst(wipe bool) Opt {
return func(c *cpController) {
c.wipeSlice1st = wipe
}
}
// WithWipeTargetSliceFirstOpt is synonym of WithWipeTargetSliceFirst(true).
var WithWipeTargetSliceFirstOpt = WithWipeTargetSliceFirst(true) //nolint:gochecknoglobals //i know that
// WithIgnoreNames does specify the ignored field names list.
//
// Use the filename wildcard match characters (aka. '*' and '?', and '**')
// as your advantages, the algor is isWildMatch() and dir.IsWildMatch.
//
// These patterns will only be tested on struct fields.
func WithIgnoreNames(names ...string) Opt {
return func(c *cpController) {
c.ignoreNames = append(c.ignoreNames, names...)
}
}
// WithIgnoreNamesReset clear the ignored name list set.
func WithIgnoreNamesReset() Opt {
return func(c *cpController) {
c.ignoreNames = nil
}
}
// isWildMatch provides a filename wildcard matching algorithm
// by dir.IsWildMatch.
func isWildMatch(s, pattern string) bool {
runeInputArray := []rune(s)
runePatternArray := []rune(pattern)
if len(runeInputArray) > 0 && len(runePatternArray) > 0 {
if runePatternArray[len(runePatternArray)-1] != '*' &&
runePatternArray[len(runePatternArray)-1] != '?' &&
runeInputArray[len(runeInputArray)-1] != runePatternArray[len(runePatternArray)-1] {
return false
}
}
return isMatchUtil([]rune(s), []rune(pattern), 0, 0, len([]rune(s)), len([]rune(pattern)))
}
func isMatchUtil(input, pattern []rune, inputIndex, patternIndex, inputLength, patternLength int) bool { //nolint:revive
if inputIndex == inputLength && patternIndex == patternLength {
return true
} else if patternIndex == patternLength {
return false
} else if inputIndex == inputLength {
if pattern[patternIndex] == '*' && restPatternStar(pattern, patternIndex+1, patternLength) {
return true
}
return false
}
if pattern[patternIndex] == '*' {
return isMatchUtil(input, pattern, inputIndex, patternIndex+1, inputLength, patternLength) ||
isMatchUtil(input, pattern, inputIndex+1, patternIndex, inputLength, patternLength)
}
if pattern[patternIndex] == '?' {
return isMatchUtil(input, pattern, inputIndex+1, patternIndex+1, inputLength, patternLength)
}
if inputIndex < inputLength {
if input[inputIndex] == pattern[patternIndex] {
return isMatchUtil(input, pattern, inputIndex+1, patternIndex+1, inputLength, patternLength)
}
return false
}
return false
}
func restPatternStar(pattern []rune, patternIndex, patternLength int) bool { //nolint:revive
for patternIndex < patternLength {
if pattern[patternIndex] != '*' {
return false
}
patternIndex++ //nolint:revive
}
return true
}
// WithStructTagName set the name which is used for retrieve the struct tag pieces.
//
// Default is "copy", the corresponding struct with tag looks like:
//
// type AFT struct {
// flags flags.Flags `copy:",cleareq"`
// converter *ValueConverter
// wouldbe int `copy:",must,keepneq,omitzero,mapmerge"`
// ignored1 int `copy:"-"`
// ignored2 int `copy:",-"`
// }
func WithStructTagName(name string) Opt {
return func(c *cpController) {
c.tagKeyName = name
}
}
// WithoutPanic disable panic() call internally.
//
// Default is true.
func WithoutPanic() Opt {
return func(c *cpController) {
c.rethrow = false
}
}
// WithStringMarshaller provides a string marshaller which will
// be applied when a map is going to be copied to string.
//
// Default is json marshaller.
//
// If BinaryMarshaler has been implemented, the source.Marshal() will
// be applied.
//
// It's synonym of RegisterDefaultStringMarshaller.
func WithStringMarshaller(m TextMarshaller) Opt {
return func(c *cpController) { //nolint:revive
RegisterDefaultStringMarshaller(m)
}
}
// RegisterDefaultStringMarshaller provides a string marshaller which will
// be applied when a map is going to be copied to string.
//
// Default is json marshaller (json.MarshalIndent).
//
// If encoding.TextMarshaler/json.Marshaler have been implemented, the
// source.MarshalText/MarshalJSON() will be applied.
//
// It's synonym of WithStringMarshaller.
func RegisterDefaultStringMarshaller(m TextMarshaller) {
if m == nil {
m = json.Marshal //nolint:revive
}
textMarshaller = m
}
// TextMarshaller for string marshaling.
type TextMarshaller func(v interface{}) ([]byte, error) //nolint:revive