-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
424 lines (368 loc) · 9.75 KB
/
decoder.go
File metadata and controls
424 lines (368 loc) · 9.75 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package excelstruct
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type InvalidUnmarshalError struct {
Type reflect.Type
}
func (e *InvalidUnmarshalError) Error() string {
if e.Type == nil {
return "excelstruct: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Pointer {
return "excelstruct: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "excelstruct: Unmarshal(nil " + e.Type.String() + ")"
}
// An UnmarshalTypeError describes a EXCEL value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
Value string // description of string value - "bool", "array", "number -5"
Type reflect.Type // type of Go value it could not be assigned to
Field string // the full path from root node to the field
Err error // the error returns convert function string to type
}
func (e *UnmarshalTypeError) Error() string {
return fmt.Sprintf("excelstruct: cannot unmarshal %q into Go struct field %q of type %s: %v", e.Value, e.Field, e.Type, e.Err)
}
// An ConvertValueError describes a value that was cannot convert to a specific user value.
type ConvertValueError struct {
Value string
Field string
Err error
}
func (e *ConvertValueError) Error() string {
return fmt.Sprintf("excelstruct: cannot convert value %q into Go struct field %q: %v", e.Value, e.Field, e.Err)
}
// An UnmarshalError describes an error that was occurred during unmarshal.
type UnmarshalError struct {
Row int
Err []error
}
func (e *UnmarshalError) saveError(err error) {
e.Err = append(e.Err, err)
}
// AsTypeError returns the all UnmarshalTypeError in UnmarshalError.
func (e *UnmarshalError) AsTypeError() []UnmarshalTypeError {
var res []UnmarshalTypeError
for _, v := range e.Err {
if err := new(UnmarshalTypeError); errors.As(v, &err) {
res = append(res, *err)
}
}
return res
}
// AsConvertValueError returns the all ConvertValueError in UnmarshalError.
func (e *UnmarshalError) AsConvertValueError() []ConvertValueError {
var res []ConvertValueError
for _, v := range e.Err {
if err := new(ConvertValueError); errors.As(v, &err) {
res = append(res, *err)
}
}
return res
}
// Error returns the all error in UnmarshalError.
func (e *UnmarshalError) Error() string {
causes := make([]string, 0, 2)
for _, v := range e.Err {
causes = append(causes, v.Error())
}
message := "excelstruct: unmarshal error: "
if len(causes) == 0 {
return message + "no causes"
}
return message + strings.Join(causes, ", ")
}
type decOpts struct {
tag string
stringConv ReadStringConv
boolConv ReadBoolConv
timeConv ReadTimeConv
}
type decodeState struct {
opts decOpts
title *title
field string
row int
colIndex int
col []int
}
func (d *decodeState) unmarshal(item []string, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(v)}
}
if err := d.value(item, rv); err != nil {
return err
}
d.row++
return nil
}
func (d *decodeState) value(item []string, v reflect.Value) error {
if len(item) == 0 {
return nil
}
u, pv := indirect(v)
if u != nil {
return u.UnmarshalXLSXValue(item)
}
v = pv
switch v.Kind() {
case reflect.Slice, reflect.Array:
return d.array(item, v)
case reflect.Struct:
return d.object(item, v)
case
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Float32,
reflect.Float64,
reflect.Bool,
reflect.String:
return d.literalStore(item[0], v)
default:
return &UnmarshalTypeError{Value: item[0], Type: v.Type(), Field: d.field}
}
}
// literalStore decodes a literal stored in item into v.
func (d *decodeState) literalStore(item string, v reflect.Value) error {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(item, 10, 64)
if err != nil {
return &UnmarshalTypeError{
Value: item,
Type: v.Type(),
Field: d.field,
Err: err,
}
}
v.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(item, 10, 64)
if err != nil {
return &UnmarshalTypeError{
Value: item,
Type: v.Type(),
Field: d.field,
Err: err,
}
}
v.SetUint(n)
case reflect.Float32, reflect.Float64:
n, err := strconv.ParseFloat(item, 64)
if err != nil {
return &UnmarshalTypeError{
Value: item,
Type: v.Type(),
Field: d.field,
Err: err,
}
}
v.SetFloat(n)
case reflect.Bool:
if d.opts.boolConv != nil {
b, err := d.opts.boolConv(d.field, item)
if err != nil {
return &ConvertValueError{
Value: item,
Field: d.field,
Err: err,
}
}
v.SetBool(b)
return nil
}
b, err := strconv.ParseBool(item)
if err != nil {
return &UnmarshalTypeError{
Value: item,
Type: v.Type(),
Field: d.field,
Err: err,
}
}
v.SetBool(b)
case reflect.String:
if d.opts.stringConv != nil {
s, err := d.opts.stringConv(d.field, item)
if err != nil {
return &ConvertValueError{
Value: item,
Field: d.field,
Err: err,
}
}
v.SetString(s)
return nil
}
v.SetString(item)
default:
return fmt.Errorf("unsupported type %q", v.Type().String())
}
return nil
}
func (d *decodeState) time(item string, v reflect.Value) error {
et, err := d.opts.timeConv(item)
if err != nil {
return &UnmarshalTypeError{
Value: item,
Type: v.Type(),
Field: d.field,
Err: err,
}
}
v.Set(reflect.ValueOf(et))
return nil
}
// array consumes an array from d.data decoding into v.
func (d *decodeState) array(item []string, v reflect.Value) error {
if v.Kind() == reflect.Slice {
s := reflect.MakeSlice(v.Type(), len(item), len(item))
v.Set(s)
}
for i := range item {
d.colIndex = i
if err := d.value([]string{item[i]}, v.Index(i)); err != nil {
return fmt.Errorf("decode array: %w", err)
}
}
return nil
}
// object consumes an object from d.data[d.off-1:], decoding into v.
func (d *decodeState) object(data []string, v reflect.Value) error {
t := v.Type()
if t == timeType {
return d.time(data[0], v)
}
unmarshalError := &UnmarshalError{Row: d.row}
fields := cachedTypeFields(t, typeOpts{structTag: d.opts.tag})
for i := range fields.list {
col, ok := d.title.columnIndex(fields.list[i].name)
if !ok {
continue
}
item := make([]string, 0, len(col))
for _, v := range col {
// empty value doesn't include item column, so skip index out of range
if v-1 >= len(data) {
continue
}
d := strings.TrimSpace(data[v-1])
if isEmptyString(d) {
continue
}
item = append(item, d)
}
subv := v
f := &fields.list[i]
for _, i := range f.index {
if subv.Kind() == reflect.Pointer {
if subv.IsNil() {
// If a struct embeds a pointer to an unexported type,
// it is not possible to set a newly allocated value
// since the field is unexported.
//
// See https://golang.org/issue/21357
if !subv.CanSet() {
unmarshalError.saveError(fmt.Errorf("exelstruct: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem()))
// Invalidate subv to ensure d.value(subv) skips over
// the value without assigning it to subv.
subv = reflect.Value{}
break
}
subv.Set(reflect.New(subv.Type().Elem()))
}
subv = subv.Elem()
}
subv = subv.Field(i)
}
d.field = f.name
d.col = col
if err := d.value(item, subv); err != nil {
unmarshalError.saveError(err)
}
}
if len(unmarshalError.Err) > 0 {
return unmarshalError
}
return nil
}
// indirect walks down v allocating pointers as needed, until it gets to a non-pointer.
// If it encounters an Unmarshaler, indirect stops and returns that.
func indirect(v reflect.Value) (ValueUnmarshaler, reflect.Value) {
// Issue #24153 indicates that it is generally not a guaranteed property
// that you may round-trip a reflect.Value by calling Value.Addr().Elem()
// and expect the value to still be settable for values derived from
// unexported embedded struct fields.
//
// The logic below effectively does this when it first addresses the value
// (to satisfy possible pointer methods) and continues to dereference
// subsequent pointers as necessary.
//
// After the first round-trip, we set v back to the original value to
// preserve the original RW flags contained in reflect.Value.
v0 := v
haveAddr := false
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() {
haveAddr = true
v = v.Addr()
}
for {
// Load value from interface, but only if the result will be usefully addressable.
if v.Kind() == reflect.Interface && !v.IsNil() {
e := v.Elem()
if e.Kind() == reflect.Pointer && !e.IsNil() {
haveAddr = false
v = e
continue
}
}
if v.Kind() != reflect.Pointer {
break
}
// Prevent infinite loop if v is an interface pointing to its own address:
// var v interface{}
// v = &v
if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
v = v.Elem()
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if v.Type().NumMethod() > 0 && v.CanInterface() {
if u, ok := v.Interface().(ValueUnmarshaler); ok {
return u, reflect.Value{}
}
}
if haveAddr {
v = v0 // restore original value after round-trip Value.Addr().Elem()
haveAddr = false
} else {
v = v.Elem()
}
}
return nil, v
}
func isEmptyString(v string) bool {
return v == ""
}