-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
94 lines (76 loc) · 2.59 KB
/
util.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
package csvx
import (
"fmt"
"reflect"
)
func traverseFields(target interface{}, createMissingStructs bool, fn func(fieldCsvTag string, field reflect.Value) error) error {
rv := reflect.ValueOf(target)
rt := reflect.TypeOf(target)
if rt.Kind() == reflect.Pointer {
rv = rv.Elem()
rt = rt.Elem()
}
for i := 0; i < rt.NumField(); i++ {
fieldV := rv.Field(i)
fieldT := rt.Field(i)
err := processField(fieldV, fieldT, createMissingStructs, fn)
if err != nil {
return err
}
}
return nil
}
func processField(fieldV reflect.Value, fieldT reflect.StructField, createMissingStructs bool, fn func(fieldCsvTag string, field reflect.Value) error) error {
const csvTagName = "csv"
csvTag := fieldT.Tag.Get(csvTagName)
if csvTag != "" {
err := fn(csvTag, fieldV)
if err != nil {
return err
}
return nil
}
fieldUnderlyingKind := getUnderlyingObject(fieldV).Kind()
// reflect.Invalid for a anonymous pointer field to another struct.
// Can't get the information about that struct so instead insist it is already set when sending in the `target`.
if fieldUnderlyingKind == reflect.Invalid {
return fmt.Errorf("csvx: invalid type found for field %q. If an anonymous struct, please ensure this field is already created before passing in to decode", fieldT.Name)
}
// if field is a struct, go into that struct and look for tags there
if fieldUnderlyingKind == reflect.Struct {
if csvTag != "" {
return fmt.Errorf("csvx: %q tag on struct-type field not supported, with encoding.TextMarshaler/encoding/TextUnmarshaler set. Field name: %s", csvTagName, fieldT.Type.String())
}
fieldOrCreatedObjectV := fieldV
if createMissingStructs {
// create a settable field. Links to understand this concept:
// https://github.com/robertkrimen/otto/issues/83
// https: //go.dev/blog/laws-of-reflection
fieldOrCreatedObjectV = reflect.New(
reflect.Indirect(
reflect.ValueOf(fieldV.Interface()),
).Type(),
)
}
err := traverseFields(fieldOrCreatedObjectV.Interface(), createMissingStructs, fn)
if err != nil {
return err
}
if createMissingStructs {
// set the struct.
// Do this after filling in the values, as we need to send pointer fields to `traverseFields` so they are retained after function exit,
// but non-pointer fields must be converted to their plain type
if fieldV.Kind() != reflect.Pointer {
fieldOrCreatedObjectV = fieldOrCreatedObjectV.Elem()
}
fieldV.Set(fieldOrCreatedObjectV)
}
}
return nil
}
func getUnderlyingObject(rv reflect.Value) reflect.Value {
if rv.Kind() == reflect.Pointer {
return rv.Elem()
}
return rv
}