-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.go
256 lines (207 loc) · 6.11 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package goflat
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Options is used to configure the marshalling and unmarshalling processes.
type Options struct {
headersFromStruct bool
// ErrorIfTaglessField causes goflat to error out if any struct field is
// missing the `flat` tag.
ErrorIfTaglessField bool
// ErrorIfDuplicateHeaders causes goflat to error out if two struct fields
// share the same `flat` tag value.
ErrorIfDuplicateHeaders bool
// ErrorIfMissingHeaders causes goflat to error out at unmarshalling time if
// a header has no struct field with a corresponding `flat` tag.
ErrorIfMissingHeaders bool
// UnmarshalIgnoreEmpty causes the unmarshaller to skip any column which is
// an empty string. This is useful for instance if you have integer values
// and you are okay with empty string mapping to the zero value (0). For the
// same reason this will cause booleans to be false if the column is empty.
UnmarshalIgnoreEmpty bool
}
type structFactory[T any] struct {
structType reflect.Type
pointer bool
columnMap map[int]int
columnValues []any
columnNames []string
options Options
}
// FieldTag is the tag that must be used in the struct fields so that goflat can
// work with them.
const FieldTag = "flat"
//nolint:varnamelen,cyclop // Fine-ish here.
func newFactory[T any](headers []string, options Options) (*structFactory[T], error) {
var v T
t := reflect.TypeOf(v)
rv := reflect.ValueOf(v)
pointer := false
//nolint:exhaustive // Fine here, there's a default.
switch t.Kind() {
case reflect.Struct:
case reflect.Pointer:
pointer = true
t = t.Elem()
rv = reflect.New(t).Elem()
default:
return nil, fmt.Errorf("type %T: %w", v, ErrNotAStruct)
}
factory := &structFactory[T]{
structType: t,
pointer: pointer,
columnMap: make(map[int]int, len(headers)),
columnValues: make([]any, t.NumField()),
columnNames: make([]string, t.NumField()),
options: options,
}
covered := make([]bool, len(headers))
for i := range t.NumField() {
fieldT := t.Field(i)
fieldV := rv.Field(i)
factory.columnValues[i] = fieldV.Interface()
v, ok := fieldT.Tag.Lookup(FieldTag)
if !ok && options.ErrorIfTaglessField {
return nil, fmt.Errorf("field %q breaks strict mode: %w", fieldT.Name, ErrTaglessField)
}
if v == "" || v == "-" {
continue
}
factory.columnNames[i] = v
handledAt := -1
for j, header := range headers {
if covered[j] {
continue
}
if header != v {
continue
}
if handledAt >= 0 {
if options.ErrorIfDuplicateHeaders {
return nil, fmt.Errorf("header %q, index %d and %d: %w", header, j, handledAt, ErrDuplicatedHeader)
}
continue
}
handledAt = j
covered[j] = true
factory.columnMap[j] = i
}
if handledAt == -1 && options.ErrorIfMissingHeaders {
return nil, fmt.Errorf("header %q: %w", v, ErrMissingHeader)
}
}
return factory, nil
}
//nolint:forcetypeassert,gocyclo,cyclop,ireturn // Fine for now.
func (s *structFactory[T]) unmarshal(record []string) (T, error) {
var zero T
newStruct := reflect.New(s.structType).Elem()
var value any
var err error
//nolint:varnamelen // Fine here.
for i, column := range record {
mappedIndex, found := s.columnMap[i]
if !found {
continue
}
if column == "" && s.options.UnmarshalIgnoreEmpty {
continue
}
columnBaseValue := s.columnValues[mappedIndex]
// special case
if u, ok := columnBaseValue.(Unmarshaller); ok {
value, err = u.Unmarshal(column)
} else {
switch columnBaseValue.(type) {
case bool:
value, err = strconv.ParseBool(column)
case int:
value, err = strconv.Atoi(column)
case int8:
value, err = strconv.ParseInt(column, 10, 8)
value = int8(value.(int64)) //nolint:gosec // Safe.
case int16:
value, err = strconv.ParseInt(column, 10, 16)
value = uint16(value.(int64)) //nolint:gosec // Safe.
case int32:
value, err = strconv.ParseInt(column, 10, 32)
value = int32(value.(int64)) //nolint:gosec // Safe.
case int64:
value, err = strconv.ParseInt(column, 10, 64)
case uint:
value, err = strconv.Atoi(column)
value = uint(value.(int)) //nolint:gosec // Safe.
case uint8: // aka byte
value, err = strconv.ParseUint(column, 10, 8)
value = uint8(value.(uint64)) //nolint:gosec // Safe.
case uint16:
value, err = strconv.ParseUint(column, 10, 16)
value = uint16(value.(uint64)) //nolint:gosec // Safe.
case uint32:
value, err = strconv.ParseUint(column, 10, 32)
value = uint32(value.(uint64)) //nolint:gosec // Safe.
case uint64:
value, err = strconv.ParseUint(column, 10, 64)
case float32:
value, err = strconv.ParseFloat(column, 32)
value = float32(value.(float64))
case float64:
value, err = strconv.ParseFloat(column, 64)
case string:
value = column
default:
return zero, fmt.Errorf("type %T: %w", columnBaseValue, ErrUnsupportedType)
}
}
if err != nil {
return zero, fmt.Errorf("parse column %d: %w", i, err)
}
newStruct.Field(mappedIndex).Set(reflect.ValueOf(value))
}
if s.pointer {
newStruct = newStruct.Addr()
}
return newStruct.Interface().(T), nil
}
func (s *structFactory[T]) marshalHeaders() []string {
headers := []string{}
for _, name := range s.columnNames {
if name == "" {
continue
}
headers = append(headers, name)
}
return headers
}
func (s *structFactory[T]) marshal(t T, separator string) ([]string, error) {
reflectValue := reflect.ValueOf(t)
if s.pointer {
reflectValue = reflectValue.Elem()
}
record := make([]string, 0, len(s.columnNames))
var strValue string
var err error
//nolint:varnamelen // Fine here.
for i, name := range s.columnNames {
if name == "" {
continue
}
fieldV := reflectValue.Field(i)
// special case
if m, ok := fieldV.Interface().(Marshaller); ok {
strValue, err = m.Marshal()
if err != nil {
return nil, fmt.Errorf("marshal column %d: %w", i, err)
}
} else {
strValue = fmt.Sprintf("%v", fieldV.Interface())
}
strValue = strings.ReplaceAll(strValue, separator, "\\"+separator)
record = append(record, strValue)
}
record = record[0:len(record):len(record)]
return record, nil
}