-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
409 lines (386 loc) · 11.9 KB
/
Copy pathcache.go
File metadata and controls
409 lines (386 loc) · 11.9 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
package csv
import (
"encoding"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/weisbartb/rcache"
)
// various reflection marshalling methods
var tOfMarshalCSV = reflect.TypeFor[MarshalCSV]()
var tOfTextMarshaller = reflect.TypeFor[encoding.TextMarshaler]()
var tOfStringer = reflect.TypeFor[Stringer]()
var tOfUnmarshalCSV = reflect.TypeFor[UnmarshalCSV]()
var tOfTextUnmarshaler = reflect.TypeFor[encoding.TextUnmarshaler]()
var tOfZeroer = reflect.TypeFor[Zeroer]()
// encoderFunction is what is used to take a value and encode it into a string response for the CSV
type encoderFunction func(val reflect.Value) (string, error)
// decoderFunction is a what is used to decode a value from a string into a response for the CSV.
// isNull is calculated by the instruction set;
// however, it will always generate a false positive for strings that do not use empty double quotes.
type decoderFunction func(val string, isNull bool) (any, error)
// zeroValueFunction is a helper stub to hold which isZero detection to use.
type zeroValueFunction func(value reflect.Value) bool
func isZero(value reflect.Value) bool {
return value.IsZero()
}
func isZeroZeroer(value reflect.Value) bool {
return value.Interface().(Zeroer).IsZero()
}
// getEncoderProvider returns a memoized function for encoding values based on their scalar types.
// structs, slices, and maps are not supported natively and should implement a MarshalCSV interface.
func getEncoderProvider(fieldType reflect.Type, omitEmpty bool) encoderFunction {
var zeroerFunc zeroValueFunction = isZero
if fieldType.Implements(tOfZeroer) {
// Use the interface resolver rather than the reflection library
zeroerFunc = isZeroZeroer
}
// Check to see if MarshalCSV is implemented
if fieldType.Implements(tOfMarshalCSV) {
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
return val.Interface().(MarshalCSV).MarshalCSV()
}
// Check to see if encoding.TextMarshaler is implemented
} else if fieldType.Implements(tOfTextMarshaller) {
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
out, err := val.Interface().(encoding.TextMarshaler).MarshalText()
return string(out), err
}
// Check to see if Stringer is implemented
} else if fieldType.Implements(tOfStringer) {
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
out, err := val.Interface().(encoding.TextMarshaler).MarshalText()
return string(out), err
}
}
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
switch fieldType.Kind() {
case reflect.String:
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
// This value should not be pre-quoted, the go CSV writer will automatically quote this.
// Empty quotes are determined to be "less useful" than a null field.
// See <stdlib>/src/encoding/csv/writer.go:148
return val.String(), nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
// All ints can be accessed via Int()
return strconv.FormatInt(val.Int(), 10), nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
// All uints can be accessed via Unit
return strconv.FormatUint(val.Uint(), 10), nil
}
case reflect.Float32, reflect.Float64:
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
return strconv.FormatFloat(val.Float(), 'f', -1, 64), nil
}
case reflect.Bool:
return func(val reflect.Value) (string, error) {
if omitEmpty && zeroerFunc(val) {
return "", nil
}
if val.Bool() {
return "TRUE", nil
}
return "FALSE", nil
}
default:
return func(val reflect.Value) (string, error) {
return "", fmt.Errorf("can not serialize type %v", fieldType.Kind())
}
}
}
// getDecoderProvider returns a memoized function for decoding values based on their scalar types.
// structs, slices, and maps are not supported natively and should implement an UnmarshalCSV interface.
func getDecoderProvider(fieldType reflect.Type, fieldName string, required bool) decoderFunction {
var errFieldRequired = fmt.Errorf("%v is a required field", fieldName)
if fieldType.Kind() != reflect.Ptr {
// Create a pointer for a value type to assert if an interface can be applied
fieldType = reflect.New(fieldType).Type()
}
if fieldType.Implements(tOfUnmarshalCSV) {
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
data := reflect.New(fieldType.Elem()).Interface()
err := data.(UnmarshalCSV).UnmarshalCSV(s)
ref := reflect.ValueOf(data)
if ref.Kind() == reflect.Ptr {
// Unmarshalling creates a new value for store the result (data)
// When data is unmarshalled it is always the addressable version
// This (and above) reflect the value again to get it to a value rather than a pointer.
// Failure to do this result in errors such as
// reflect.Set: value of type *csv.NullableField[int] is not assignable to type csv.NullableField[int]
ref = ref.Elem()
}
return ref.Interface(), err
}
} else if fieldType.Implements(tOfTextUnmarshaler) {
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
data := reflect.New(fieldType.Elem()).Interface()
err := data.(encoding.TextUnmarshaler).UnmarshalText([]byte(s))
ref := reflect.ValueOf(data)
if ref.Kind() == reflect.Ptr {
// See comments for fieldType.Implements(tOfUnmarshalCSV)
ref = ref.Elem()
}
return ref.Interface(), err
}
}
switch fieldType.Elem().Kind() {
case reflect.String:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
return s, nil
}
case reflect.Int:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseInt(s, 10, strconv.IntSize)
return int(val), err
}
case reflect.Int8:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseInt(s, 10, 8)
return int8(val), err
}
case reflect.Int16:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseInt(s, 10, 16)
return int16(val), err
}
case reflect.Int32:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseInt(s, 10, 32)
return int32(val), err
}
case reflect.Int64:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
return strconv.ParseInt(s, 10, 64)
}
case reflect.Uint:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseUint(s, 10, strconv.IntSize)
return uint(val), err
}
case reflect.Uint8:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseUint(s, 10, 8)
return uint8(val), err
}
case reflect.Uint16:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseUint(s, 10, 16)
return uint16(val), err
}
case reflect.Uint32:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
val, err := strconv.ParseUint(s, 10, 32)
return uint32(val), err
}
case reflect.Uint64:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
return strconv.ParseUint(s, 10, 64)
}
case reflect.Float32:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
f, err := strconv.ParseFloat(s, 32)
return float32(f), err
}
case reflect.Float64:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return 0, nil
}
f, err := strconv.ParseFloat(s, 64)
return f, err
}
case reflect.Bool:
return func(s string, isNull bool) (any, error) {
if required && isNull {
return nil, errFieldRequired
}
if len(s) == 0 {
return false, nil
}
return strconv.ParseBool(s)
}
default:
return func(s string, isNull bool) (any, error) {
return "", fmt.Errorf("can not unserialize type %v", fieldType.Kind())
}
}
}
// tagParts is a quick helper type for parsing the extra tag arguments.
type tagParts []string
func (tp tagParts) Find(key string) (string, bool) {
for _, v := range tp {
// Loop through to find the sub tag
if strings.HasPrefix(v, key) {
kv := strings.SplitN(v, "=", 2)
if len(kv) == 1 {
// Present but has no value
return "", true
}
// Present with a value
return kv[1], true
}
}
return "", false
}
// Ensure that the csvInstruction can be used by rcache.
var _ rcache.InstructionSet = (*csvInstruction)(nil)
// csvInstruction provides instructions on how to extract data from structs for CSV parsing.
type csvInstruction struct {
encoder encoderFunction
decoder decoderFunction
exportedFieldName string
}
// GetCSVHeaderIdentifier gets the mapping identifier for the CSV header.
func (c csvInstruction) GetCSVHeaderIdentifier() string {
return c.exportedFieldName
}
// FieldName gets the name of the field from the given tag, this is needed by InstructionSet.
func (c csvInstruction) FieldName(tag string) string {
return strings.SplitN(tag, ",", 2)[0]
}
// TagNamespace gets the namespace for the tag this instruction set wants to use
func (c csvInstruction) TagNamespace() string {
return "csv"
}
// Skip determines if the potential field should be skipped based on its tag.
func (c csvInstruction) Skip(tag string) bool {
if strings.SplitN(tag, ",", 2)[0] == "-" {
return true
}
return false
}
// GetMetadata is a method for calculating metadata for a given field;
// this will return a new instruction set from the base instruction for how to parse the field.
func (c csvInstruction) GetMetadata(field reflect.StructField, tag string) rcache.InstructionSet {
var omitEmpty bool
var required bool
parts := tagParts(strings.Split(tag, ","))
if len(parts) > 1 {
// Skip past the field name declaration.
parts = parts[1:]
_, omitEmpty = parts.Find("omitempty")
_, required = parts.Find("required")
}
var instruction csvInstruction
fieldName := c.FieldName(tag)
instruction.encoder = getEncoderProvider(field.Type, omitEmpty)
instruction.decoder = getDecoderProvider(field.Type, fieldName, required)
c.exportedFieldName = fieldName
return instruction
}
// GetDecoder gets the decoder for a given field.
func (c csvInstruction) GetDecoder() decoderFunction {
return c.decoder
}
// GetEncoder gets the encoder for a given field.
func (c csvInstruction) GetEncoder() encoderFunction {
return c.encoder
}
// Setup the cache
var fieldCache = rcache.NewCache[csvInstruction]()