-
Notifications
You must be signed in to change notification settings - Fork 2
/
extract.go
323 lines (257 loc) · 7.35 KB
/
extract.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
package structextract
import (
"errors"
"reflect"
"strings"
)
const omitEmptyOption = "omitempty"
// Extractor holds the struct that we want to extract data from
type Extractor struct {
StructAddr interface{} // StructAddr: struct address
ignoredFields []string // ignoredFields: an array with all the fields to be ignored
useEmbeddedStructs bool
}
// New returns a new Extractor struct
// the parameter have to be a pointer to a struct
func New(s interface{}) *Extractor {
return &Extractor{
StructAddr: s,
ignoredFields: nil,
useEmbeddedStructs: false,
}
}
// Names returns an array with all the field names (with the same order) as defined on the struct
func (e *Extractor) Names() (out []string, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
out = append(out, field.name)
}
return
}
// NamesFromTag returns an array with all the tag names for each field
// omitempty tag option will ignore empty fields
func (e *Extractor) NamesFromTag(tag string) (out []string, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
if val, ok := field.tags.Lookup(tag); ok {
key, omit := e.parseOmitempty(val, field.value)
if omit {
continue
}
out = append(out, key)
}
}
return
}
// NamesFromTagWithPrefix returns an array with all the tag names for each field including the given prefix
// omitempty tag option will ignore empty fields
func (e *Extractor) NamesFromTagWithPrefix(tag string, prefix string) (out []string, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
val, ok := field.tags.Lookup(tag)
if !ok {
continue
}
key, omit := e.parseOmitempty(val, field.value)
if omit {
continue
}
out = append(out, strings.TrimSpace(prefix+key))
}
return
}
// Values returns an interface array with all the values
func (e *Extractor) Values() (out []interface{}, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
out = append(out, field.value.Interface())
}
return
}
// ValuesFromTag returns an interface array with all the values of fields with the given tag
// omitempty tag option will ignore empty fields
func (e *Extractor) ValuesFromTag(tag string) (out []interface{}, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
if val, ok := field.tags.Lookup(tag); ok {
if _, omit := e.parseOmitempty(val, field.value); omit {
continue
}
out = append(out, field.value.Interface())
}
}
return
}
// FieldValueMap returns a string to interface map,
// key: field as defined on the struct
// value: the value of the field
func (e *Extractor) FieldValueMap() (out map[string]interface{}, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
out = make(map[string]interface{})
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
out[field.name] = field.value.Interface()
}
return
}
// FieldValueFromTagMap returns a string to interface map that uses as key the tag name,
// key: tag name for the given field
// value: the value of the field
// omitempty tag option will ignore empty fields
func (e *Extractor) FieldValueFromTagMap(tag string) (out map[string]interface{}, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
out = make(map[string]interface{})
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
if val, ok := field.tags.Lookup(tag); ok {
key, omit := e.parseOmitempty(val, field.value)
if omit {
continue
}
out[key] = field.value.Interface()
}
}
return
}
// TagMapping returns a map that maps tagged fields from one tag to another.
// This can help with mapping partial JSON objects to some other kind of a
// mapping, such as SQL. It only maps existing field pairs, if either field
// does not have a tag, it's left out.
func (e *Extractor) TagMapping(from, to string) (out map[string]string, err error) {
if err := e.isValidStruct(); err != nil {
return nil, err
}
out = make(map[string]string)
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
fromTag, fromOk := field.tags.Lookup(from)
toTag, toOk := field.tags.Lookup(to)
if toOk && fromOk {
out[fromTag] = toTag
}
}
return
}
// IgnoreField checks if the given fields are valid based on the given struct,
// then append them on the ignore list
// e.g. ext := structextract.New(&business).IgnoreField("ID","DateModified")
func (e *Extractor) IgnoreField(fd ...string) *Extractor {
if err := e.isValidStruct(); err != nil {
return e
}
for _, field := range fd {
if e.isFieldNameValid(field) {
e.ignoredFields = append(e.ignoredFields, field)
}
}
return e
}
// UseEmbeddedStructs toggles the usage of embedded structs
func (e *Extractor) UseEmbeddedStructs(use bool) *Extractor {
e.useEmbeddedStructs = use
return e
}
func (e *Extractor) isFieldNameValid(fn string) bool {
s := reflect.ValueOf(e.StructAddr).Elem()
fields := e.fields(s)
for _, field := range fields {
if field.name == fn {
return true
}
}
return false
}
func isIgnored(a string, list []string) bool {
for _, l := range list {
if l == a {
return true
}
}
return false
}
func (e *Extractor) isValidStruct() error {
stVal := reflect.ValueOf(e.StructAddr)
if stVal.Kind() != reflect.Ptr || stVal.IsNil() {
return errors.New("struct passed is not valid, a pointer was expected")
}
structVal := stVal.Elem()
if structVal.Kind() != reflect.Struct {
return errors.New("struct passed is not valid, a pointer to struct was expected")
}
return nil
}
type field struct {
value reflect.Value
name string
tags reflect.StructTag
}
// This function returns a slice of fields of a struct
// as reflect.Value, even fields of embedded structs
func (e *Extractor) fields(s reflect.Value) []field {
fields := make([]field, 0, s.NumField())
for i := 0; i < s.NumField(); i++ {
if isIgnored(s.Type().Field(i).Name, e.ignoredFields) {
continue
}
if s.Type().Field(i).Anonymous {
if e.useEmbeddedStructs {
fields = append(fields, e.fields(s.Field(i))...)
}
continue
}
tag := s.Type().Field(i).Tag
name := s.Type().Field(i).Name
value := s.Field(i)
fields = append(fields, field{value, name, tag})
}
return fields
}
func (e *Extractor) parseOptions(tag string) (string, tagOptions) {
res := strings.Split(tag, ",")
return res[0], res[1:]
}
func (e *Extractor) parseOmitempty(tag string, val reflect.Value) (string, bool) {
tagValue, options := e.parseOptions(tag)
if !options.has(omitEmptyOption) {
return tagValue, false
}
zero := reflect.Zero(val.Type()).Interface()
current := val.Interface()
return tagValue, reflect.DeepEqual(current, zero)
}
type tagOptions []string
func (t tagOptions) has(opt string) bool {
for _, option := range t {
if option == opt {
return true
}
}
return false
}