-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv.go
408 lines (343 loc) · 9.6 KB
/
csv.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
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
package csvx
import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
var (
ErrDataIsNil = errors.New("data is nil")
ErrOnlyOneRowIsAllowedForStringArray = errors.New("only one row is allowed for type 'string,array'")
ErrOnlyOneRowIsAllowedForInt64Array = errors.New("only one row is allowed for type 'int64,array'")
ErrOnlyOneRowIsAllowedForFloat64Array = errors.New("only one row is allowed for type 'float64,array'")
ErrOnlyOneRowIsAllowedForBoolArray = errors.New("only one row is allowed for type 'bool,array'")
ErrInEmbeddedJSON = errors.New("unable to parse json in csv")
ErrUnsupportedType = errors.New("unsupported type format type")
)
type field struct {
Name string
Type string
}
type CSVParser struct {
// Comma defines the rune with which the entries in the csv file are separated from each other.
Comma rune
// Comment defines the rune used to mark comment strings within the CSV.
// If the line starts with this rune, the whole line is ignored.
Comment rune
// TrimLeadingSpace specifies whether leading spaces should be trimmed or not.
TrimLeadingSpace bool
// SkipEmptyColumns defines whether empty rows should be ignored or not.
SkipEmptyColumns bool
// isTyped defines whether the user expected to receive a typed or untyped response.
isTyped bool
}
// Untyped unmarshals the data into a slice of map[string]interface{}
func (c *CSVParser) Untyped(data []byte) ([]map[string]interface{}, error) {
c.isTyped = false
return c.parseToCSV(data)
}
// Typed unmarshals the typed data into a slice of map[string]interface{}
//
// In this case, the second column of the csv must contain the field types, otherwise it will throw an error
func (c *CSVParser) Typed(data []byte) ([]map[string]interface{}, error) {
c.isTyped = true
return c.parseToCSV(data)
}
// checkForNilOrDefault checks if the runes are set.
// If the runes are not set, the default values are used.
//
// Default values:
// comma: ','
// comment: '#'
func (c *CSVParser) checkForNilOrDefault() {
if c.Comma == *new(rune) {
c.Comma = ','
}
if c.Comment == *new(rune) {
c.Comment = '#'
}
}
// readCSV delegates the read command to csv.NewReader (stdlib) and writes it to a two-dimensional string slice that is returned.
func (c *CSVParser) readCSV(data []byte) ([][]string, error) {
csvR := csv.NewReader(bytes.NewReader(data))
csvR.Comma = c.Comma
csvR.Comment = c.Comment
csvR.TrimLeadingSpace = c.TrimLeadingSpace
csvR.FieldsPerRecord = -1
csvR.LazyQuotes = true
records, err := csvR.ReadAll()
if err != nil {
return nil, err
}
return records, nil
}
// parseToCSV extracts the header information from the byte slice and generates a map based on the format (typed or untyped).
func (c *CSVParser) parseToCSV(data []byte) ([]map[string]interface{}, error) {
c.checkForNilOrDefault()
records, err := c.readCSV(data)
if err != nil {
return nil, err
}
var headerInfo map[int]field
if c.isTyped {
if len(records) < 2 {
return nil, ErrDataIsNil
}
headerInfo = c.extractHeaderInformation(records[0], records[1])
records = records[2:]
} else {
if len(records) < 1 {
return nil, ErrDataIsNil
}
headerInfo = c.extractHeaderInformation(records[0], nil)
records = records[1:]
}
return c.csvToMap(headerInfo, records)
}
// extractHeaderInformation reads the header information and returns it as map of field
func (c *CSVParser) extractHeaderInformation(names, types []string) map[int]field {
headFields := map[int]field{}
// extract field names
for idx, value := range names {
headFields[idx] = field{
Name: value,
}
}
// extract field types
for idx, value := range types {
field := headFields[idx]
field.Type = value
headFields[idx] = field
}
return headFields
}
// csvToMap builds the data columns based on the typed or untyped fields
func (c *CSVParser) csvToMap(headerInfo map[int]field, records [][]string) ([]map[string]interface{}, error) {
rslt := []map[string]interface{}{}
// skip first row
for _, value := range records {
skipColumn := true
myColumn := make(map[string]interface{})
for idx, v2 := range value {
if len(headerInfo) < idx {
// the column contains more data than we expected, break out of it
break
}
// checks if the first entry of the row and the first character of the string matches the comment character.
// If it matches, this row is skipped.
// This is necessary because csvR.ReadAll() ignores some cases that contain such a comment rune
if idx == 0 && len(v2) > 0 {
if rune(v2[0]) == c.Comment {
// the column contains the comment rune, skip it
break
}
}
// check whether v2 contains a value or not
// set skip column to false, if a value was set
if len(v2) > 0 {
skipColumn = false
}
// check whether isTyped is true, the header info is not set and skip columns is set
// then this row should be skipped
if c.isTyped && headerInfo[idx].Type == "" && c.SkipEmptyColumns {
continue
}
// check whether the type was set for the row
if headerInfo[idx].Type != "" {
// toTyped returns the
typed, err := c.toTyped(v2, strings.TrimPrefix(headerInfo[idx].Type, "*"), strings.HasPrefix(headerInfo[idx].Type, "*"))
if err != nil {
return nil, err
}
// type is not a pointer
myColumn[headerInfo[idx].Name] = typed
continue
}
myColumn[headerInfo[idx].Name] = v2
}
if !skipColumn {
rslt = append(rslt, myColumn)
}
}
return rslt, nil
}
// toTyped takes the value and the format and converts the value into the desired format.
func (c *CSVParser) toTyped(value, format string, isPointer bool) (interface{}, error) {
switch format {
case "string":
if value == "" && !isPointer {
return "", nil
} else if value == "" && isPointer {
return nil, nil
}
if isPointer {
return &value, nil
}
return value, nil
case "int64":
if value == "" && !isPointer {
return int64(0), nil
} else if value == "" && isPointer {
return nil, nil
}
val, err := strconv.ParseInt(value, 10, 64)
if isPointer {
return &val, err
}
return val, err
case "int":
if value == "" && !isPointer {
return int(0), nil
} else if value == "" && isPointer {
return nil, nil
}
val, err := strconv.Atoi(value)
if isPointer {
return &val, err
}
return val, err
case "float64":
if value == "" && !isPointer {
return float64(0), nil
} else if value == "" && isPointer {
return nil, nil
}
val, err := strconv.ParseFloat(value, 64)
if isPointer {
return &val, err
}
return val, err
case "bool":
if value == "" && !isPointer {
return false, nil
} else if value == "" && isPointer {
return nil, nil
}
val, err := strconv.ParseBool(value)
if isPointer {
return &val, err
}
return val, err
case "string,array":
if value == "" && !isPointer {
return []string{}, nil
} else if value == "" && isPointer {
return nil, nil
}
records, err := c.readCSV([]byte(value))
if err != nil {
return nil, err
}
//Check if we only have one row. If not return error
if len(records) > 1 {
return nil, ErrOnlyOneRowIsAllowedForStringArray
}
retArray := make([]string, 0)
retArray = append(retArray, records[0]...)
if isPointer {
return &retArray, nil
}
return retArray, nil
case "int64,array":
if value == "" && !isPointer {
return []int64{}, nil
} else if value == "" && isPointer {
return nil, nil
}
records, err := c.readCSV([]byte(value))
if err != nil {
return nil, err
}
//Check if we only have one row. If not return error
if len(records) > 1 {
return nil, ErrOnlyOneRowIsAllowedForInt64Array
}
retArray := make([]int64, 0)
for _, v := range records[0] {
vi := int64(0)
if v != "" {
vi, err = strconv.ParseInt(strings.TrimSpace(v), 10, 64)
if err != nil {
return nil, err
}
}
retArray = append(retArray, vi)
}
if isPointer {
return &retArray, nil
}
return retArray, nil
case "float64,array":
if value == "" && !isPointer {
return []float64{}, nil
} else if value == "" && isPointer {
return nil, nil
}
records, err := c.readCSV([]byte(value))
if err != nil {
return nil, err
}
//Check if we only have one row. If not return error
if len(records) > 1 {
return nil, ErrOnlyOneRowIsAllowedForFloat64Array
}
retArray := make([]float64, 0)
for _, v := range records[0] {
vi := float64(0)
if v != "" {
vi, err = strconv.ParseFloat(strings.TrimSpace(v), 64)
if err != nil {
return nil, err
}
}
retArray = append(retArray, vi)
}
if isPointer {
return &retArray, nil
}
return retArray, nil
case "bool,array":
if value == "" && !isPointer {
return []bool{}, nil
} else if value == "" && isPointer {
return nil, nil
}
records, err := c.readCSV([]byte(value))
if err != nil {
return nil, err
}
//Check if we only have one row. If not return error
if len(records) > 1 {
return nil, ErrOnlyOneRowIsAllowedForBoolArray
}
retArray := make([]bool, 0)
for _, v := range records[0] {
retArray = append(retArray, strings.TrimSpace(v) == "true")
}
if isPointer {
return &retArray, nil
}
return retArray, nil
case "json":
if value == "" {
return nil, nil
}
var data interface{}
err := json.Unmarshal([]byte(value), &data)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInEmbeddedJSON, err)
}
if isPointer {
p := reflect.New(reflect.TypeOf(data))
p.Elem().Set(reflect.ValueOf(data))
return p.Interface(), nil
}
return data, nil
default:
return nil, fmt.Errorf("%w: %s", ErrUnsupportedType, format)
}
}