forked from gocarina/gocsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.go
242 lines (206 loc) · 7.05 KB
/
reflect.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
package gocsv
import (
"fmt"
"reflect"
"strconv"
"strings"
"sync"
)
// --------------------------------------------------------------------------
// Reflection helpers
type structInfo struct {
Fields []fieldInfo
}
// fieldInfo is a struct field that should be mapped to a CSV column, or vice-versa
// Each IndexChain element before the last is the index of an the embedded struct field
// that defines Key as a tag
type fieldInfo struct {
keys []string
omitEmpty bool
IndexChain []int
defaultValue string
}
func (f fieldInfo) getFirstKey() string {
return f.keys[0]
}
func (f fieldInfo) matchesKey(key string) bool {
for _, k := range f.keys {
if key == k || strings.TrimSpace(key) == k {
return true
}
}
return false
}
var structInfoCache sync.Map
var structMap = make(map[reflect.Type]*structInfo)
var structMapMutex sync.RWMutex
func getStructInfoNoCache(rType reflect.Type) *structInfo {
fieldsList := getFieldInfos(rType, []int{}, []string{})
return &structInfo{fieldsList}
}
func getStructInfo(rType reflect.Type) *structInfo {
stInfo, ok := structInfoCache.Load(rType)
if ok {
return stInfo.(*structInfo)
}
fieldsList := getFieldInfos(rType, []int{}, []string{})
stInfo = &structInfo{fieldsList}
structInfoCache.Store(rType, stInfo)
return stInfo.(*structInfo)
}
func getFieldInfos(rType reflect.Type, parentIndexChain []int, parentKeys []string) []fieldInfo {
fieldsCount := rType.NumField()
fieldsList := make([]fieldInfo, 0, fieldsCount)
for i := 0; i < fieldsCount; i++ {
field := rType.Field(i)
if field.PkgPath != "" {
continue
}
var cpy = make([]int, len(parentIndexChain))
copy(cpy, parentIndexChain)
indexChain := append(cpy, i)
var currFieldInfo *fieldInfo
if !field.Anonymous {
filteredTags := []string{}
currFieldInfo, filteredTags = filterTags(TagName, indexChain, field)
if len(filteredTags) == 1 && filteredTags[0] == "-" {
// ignore nested structs with - tag
continue
} else if len(filteredTags) > 0 && filteredTags[0] != "" {
currFieldInfo.keys = filteredTags
} else {
currFieldInfo.keys = []string{normalizeName(field.Name)}
}
if len(parentKeys) > 0 && currFieldInfo != nil && !canMarshal(field.Type) {
// create cartesian product of keys
// eg: parent keys x field keys
keys := make([]string, 0, len(parentKeys)*len(currFieldInfo.keys))
for _, pkey := range parentKeys {
for _, ckey := range currFieldInfo.keys {
keys = append(keys, normalizeName(fmt.Sprintf("%s.%s", pkey, ckey)))
}
}
currFieldInfo.keys = keys
}
}
// handle struct
fieldType := field.Type
// if the field is a pointer, follow the pointer
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
// if the field is a struct, create a fieldInfo for each of its fields
if fieldType.Kind() == reflect.Struct {
// Structs that implement any of the text or CSV marshaling methods
// should result in one value and not have their fields exposed
if !(canMarshal(fieldType)) {
// if the field is an embedded struct, pass along parent keys
keys := parentKeys
if currFieldInfo != nil {
keys = currFieldInfo.keys
}
fieldsList = append(fieldsList, getFieldInfos(fieldType, indexChain, keys)...)
continue
}
}
// if the field is an embedded struct, ignore the csv tag
if currFieldInfo == nil {
continue
}
if field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Array {
var arrayLength = -1
if arrayTag, ok := field.Tag.Lookup(TagName + "[]"); ok {
arrayLength, _ = strconv.Atoi(arrayTag)
}
// When the field is a slice/array of structs, create a fieldInfo for each index and each field
if field.Type.Elem().Kind() == reflect.Struct {
fieldInfos := getFieldInfos(field.Type.Elem(), []int{}, []string{})
for idx := 0; idx < arrayLength; idx++ {
// copy index chain and append array index
var cpy2 = make([]int, len(indexChain))
copy(cpy2, indexChain)
arrayIndexChain := append(cpy2, idx)
for _, childFieldInfo := range fieldInfos {
// copy array index chain and append array index
var cpy3 = make([]int, len(arrayIndexChain))
copy(cpy3, arrayIndexChain)
arrayFieldInfo := fieldInfo{
IndexChain: append(cpy3, childFieldInfo.IndexChain...),
omitEmpty: childFieldInfo.omitEmpty,
defaultValue: childFieldInfo.defaultValue,
}
// create cartesian product of keys
// eg: array field keys x struct field keys
for _, akey := range currFieldInfo.keys {
for _, fkey := range childFieldInfo.keys {
arrayFieldInfo.keys = append(arrayFieldInfo.keys, normalizeName(fmt.Sprintf("%s[%d].%s", akey, idx, fkey)))
}
}
fieldsList = append(fieldsList, arrayFieldInfo)
}
}
} else if arrayLength > 0 {
// When the field is a slice/array of primitives, create a fieldInfo for each index
for idx := 0; idx < arrayLength; idx++ {
// copy index chain and append array index
var cpy2 = make([]int, len(indexChain))
copy(cpy2, indexChain)
arrayFieldInfo := fieldInfo{
IndexChain: append(cpy2, idx),
omitEmpty: currFieldInfo.omitEmpty,
defaultValue: currFieldInfo.defaultValue,
}
for _, akey := range currFieldInfo.keys {
arrayFieldInfo.keys = append(arrayFieldInfo.keys, normalizeName(fmt.Sprintf("%s[%d]", akey, idx)))
}
fieldsList = append(fieldsList, arrayFieldInfo)
}
} else {
fieldsList = append(fieldsList, *currFieldInfo)
}
} else {
fieldsList = append(fieldsList, *currFieldInfo)
}
}
return fieldsList
}
func filterTags(tagName string, indexChain []int, field reflect.StructField) (*fieldInfo, []string) {
currFieldInfo := fieldInfo{IndexChain: indexChain}
fieldTag := field.Tag.Get(tagName)
fieldTags := strings.Split(fieldTag, TagSeparator)
filteredTags := []string{}
for _, fieldTagEntry := range fieldTags {
trimmedFieldTagEntry := strings.TrimSpace(fieldTagEntry) // handles cases like `csv:"foo, omitempty, default=test"`
if trimmedFieldTagEntry == "omitempty" {
currFieldInfo.omitEmpty = true
} else if strings.HasPrefix(trimmedFieldTagEntry, "default=") {
currFieldInfo.defaultValue = strings.TrimPrefix(trimmedFieldTagEntry, "default=")
} else {
filteredTags = append(filteredTags, normalizeName(trimmedFieldTagEntry))
}
}
return &currFieldInfo, filteredTags
}
func getConcreteContainerInnerType(in reflect.Type) (inInnerWasPointer bool, inInnerType reflect.Type) {
inInnerType = in.Elem()
inInnerWasPointer = false
if inInnerType.Kind() == reflect.Ptr {
inInnerWasPointer = true
inInnerType = inInnerType.Elem()
}
return inInnerWasPointer, inInnerType
}
func getConcreteReflectValueAndType(in interface{}) (reflect.Value, reflect.Type) {
value := reflect.ValueOf(in)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
return value, value.Type()
}
var errorInterface = reflect.TypeOf((*error)(nil)).Elem()
func isErrorType(outType reflect.Type) bool {
if outType.Kind() != reflect.Interface {
return false
}
return outType.Implements(errorInterface)
}