-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunmap.go
294 lines (236 loc) · 7.27 KB
/
unmap.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
package structmapper
import (
"errors"
"fmt"
"reflect"
"unicode"
"encoding"
"github.com/hashicorp/go-multierror"
)
// This file contains the map to struct functionality of Mapper
func (sm *Mapper) unmapPtr(in interface{}, out reflect.Value, t reflect.Type) error {
child := reflect.New(t.Elem())
if err := sm.unmapValue(in, child.Elem(), child.Elem().Type()); err != nil {
return err
}
out.Set(child)
return nil
}
func (sm *Mapper) unmapSlice(in interface{}, out reflect.Value, t reflect.Type) (err error) {
inSlice := reflect.ValueOf(in)
if inSlice.Kind() != reflect.Slice {
return errors.New("Not a slice")
}
outSlice := reflect.MakeSlice(t, inSlice.Len(), inSlice.Cap())
for i := 0; i < inSlice.Len(); i++ {
inElem := inSlice.Index(i)
outElem := outSlice.Index(i)
inV := reflect.ValueOf(inElem.Interface())
elemV := reflect.New(outElem.Type()).Elem()
if unmapErr := sm.unmapValue(inV.Interface(), elemV, elemV.Type()); unmapErr != nil {
err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%d", i)))
continue
}
outSlice.Index(i).Set(elemV)
}
if err == nil {
out.Set(outSlice)
}
return
}
func (sm *Mapper) unmapMap(in interface{}, out reflect.Value, t reflect.Type) (err error) {
inMap := reflect.ValueOf(in)
if inMap.Kind() != reflect.Map {
return errors.New("Not a map")
}
outMap := reflect.MakeMap(t)
for _, inKeyElem := range inMap.MapKeys() {
inKeyV := reflect.ValueOf(inKeyElem.Interface())
inKeyInterface := inKeyV.Interface()
outKey := reflect.New(inKeyV.Type()).Elem()
if unmapErr := sm.unmapValue(inKeyInterface, outKey, outKey.Type()); unmapErr != nil {
err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%+v (key)", inKeyInterface)))
continue
}
inValueElem := inMap.MapIndex(inKeyV)
inValueV := reflect.ValueOf(inValueElem.Interface())
inValueInterface := inValueV.Interface()
outValue := reflect.New(outMap.Type().Elem()).Elem()
if unmapErr := sm.unmapValue(inValueInterface, outValue, outValue.Type()); unmapErr != nil {
err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%+v (inValueInterface)",
inValueInterface)))
continue
}
outMap.SetMapIndex(outKey, outValue)
}
if err == nil {
// Special case: out may be a struct or struct pointer...
out.Set(outMap)
}
return
}
func (sm *Mapper) unmapArray(in interface{}, out reflect.Value, t reflect.Type) (err error) {
inArray := reflect.ValueOf(in)
if inArray.Kind() != reflect.Array && inArray.Kind() != reflect.Slice {
return errors.New("Not an array or slice")
}
outArray := reflect.New(t).Elem()
for i := 0; i < inArray.Len(); i++ {
outElem := outArray.Index(i)
inValue := inArray.Index(i)
if unmapErr := sm.unmapValue(inValue.Interface(), outElem, outElem.Type()); unmapErr != nil {
err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%d", i)))
continue
}
}
if err == nil {
out.Set(outArray)
}
return
}
func (sm *Mapper) unmapUnmarshal(in interface{}, out reflect.Value) (bool, error) {
inValue := reflect.ValueOf(in)
inType := inValue.Type()
str := ""
strValue := reflect.ValueOf(&str).Elem()
strType := strValue.Type()
if inType == strType {
str = in.(string)
} else if inType.AssignableTo(strType) {
strValue.Set(inValue)
} else if inType.ConvertibleTo(strType) {
strValue.Set(inValue.Convert(strType))
} else {
return false, nil
}
outI := out.Interface()
if unmarshaler, ok := outI.(encoding.TextUnmarshaler); ok {
return true, unmarshaler.UnmarshalText([]byte(str))
} else if out.CanAddr() {
return sm.unmapUnmarshal(in, out.Addr())
}
return false, nil
}
func (sm *Mapper) unmapValue(in interface{}, out reflect.Value, t reflect.Type) error {
// Check if the target implements encoding.TextUnmarshaler
if handled, err := sm.unmapUnmarshal(in, out); handled {
return err
}
switch out.Kind() {
case reflect.Ptr:
return sm.unmapPtr(in, out, t)
case reflect.Struct:
return sm.unmapStruct(in, out, t)
case reflect.Slice:
return sm.unmapSlice(in, out, t)
case reflect.Map:
return sm.unmapMap(in, out, t)
case reflect.Array:
return sm.unmapArray(in, out, t)
}
inValue := reflect.ValueOf(in)
inType := inValue.Type()
outType := reflect.ValueOf(out.Interface()).Type()
if inType == outType {
// Default case: copy the value over
out.Set(reflect.ValueOf(in))
return nil
} else if inType.AssignableTo(outType) {
// Types are assignable
out.Set(inValue)
return nil
} else if inType.ConvertibleTo(outType) {
// Types are convertible
out.Set(inValue.Convert(outType))
return nil
}
return fmt.Errorf("Type mismatch: %s and %s are incompatible", outType.String(), inType.String())
}
func (sm *Mapper) unmapStruct(in interface{}, out reflect.Value, t reflect.Type) (err error) {
if out.Kind() == reflect.Ptr {
// Target is a pointer to a struct: create a new instance
out.Set(reflect.New(out.Type().Elem()))
out = out.Elem()
t = out.Type()
}
if out.Kind() != reflect.Struct {
return ErrNotAStruct
}
// Check if we received any map
inValue := reflect.ValueOf(in)
if inValue.Kind() != reflect.Map {
return ErrInvalidMap
}
// Hold the values of the modified fields in a map, which will be applied shortly before
// this function returns.
// This ensures we do not modify the target struct at all in case of an error
modifiedFields := make(map[int]reflect.Value, t.NumField())
// Iterate over all fields of the passed struct
for i := 0; i < out.NumField(); i++ {
fieldD := t.Field(i)
fieldV := out.Field(i)
if fieldD.Anonymous {
// Call unmapStruct on anonymous field
if anonErr := sm.unmapStruct(in,
fieldV,
fieldD.Type); anonErr != nil {
err = multierror.Append(err, anonErr)
continue
}
continue
}
fieldName := fieldD.Name
if !unicode.IsUpper([]rune(fieldName)[0]) {
// Ignore private fields
continue
}
fieldName, _, tagErr := parseTagFromStructField(fieldD, sm.tagName)
if tagErr != nil {
// Parsing the tag failed, ignore the field and carry on
err = multierror.Append(err, tagErr)
continue
}
if fieldName == "-" {
// Tag defines that the field shall be ignored, so carry on
continue
}
// Look up value of "fieldName" in map
mapVal := inValue.MapIndex(reflect.ValueOf(fieldName))
if !mapVal.IsValid() {
// Value not in map, ignore it
continue
}
mapValue := mapVal.Interface()
if fieldV.Kind() == reflect.Interface {
// Setting interfaces is unsupported.
err = multierror.Append(err, multierror.Prefix(ErrFieldIsInterface, fieldName+":"))
continue
}
targetV := reflect.New(fieldD.Type).Elem()
if unmapErr := sm.unmapValue(mapValue, targetV, fieldD.Type); unmapErr != nil {
err = multierror.Append(err, multierror.Prefix(unmapErr, fieldName+":"))
continue
} else {
modifiedFields[i] = targetV
}
}
// Apply changes to all modified fields in case no error happened during processing.
if err == nil {
// Apply changes to all modified fields
for fieldIndex, fieldValue := range modifiedFields {
out.Field(fieldIndex).Set(fieldValue)
}
}
return
}
func (sm *Mapper) toStruct(m map[string]interface{}, s interface{}) error {
if m == nil {
return ErrMapIsNil
}
v := reflect.ValueOf(s)
if v.Kind() != reflect.Ptr {
return ErrNotAStructPointer
}
v = v.Elem()
return sm.unmapStruct(m, v, v.Type())
}