-
Notifications
You must be signed in to change notification settings - Fork 28
/
csv.go
319 lines (274 loc) · 6.91 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
package main
import (
"encoding/csv"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
"github.com/grafana/grafana-plugin-sdk-go/data"
)
type fieldSchema struct {
Name string `json:"name"`
Type string `json:"type"`
}
type csvOptions struct {
Delimiter string `json:"delimiter"`
Header bool `json:"header"`
IgnoreUnknown bool `json:"ignoreUnknown"`
Schema []fieldSchema `json:"schema"`
SkipRows int `json:"skipRows"`
DecimalSeparator string `json:"decimalSeparator"`
Timezone string `json:"timezone"`
}
func parseCSV(opts csvOptions, regex bool, r io.Reader, logger log.Logger) ([]*data.Field, error) {
header, rows, err := readCSV(opts, r)
if err != nil {
return nil, err
}
location, err := time.LoadLocation(opts.Timezone)
if err != nil {
panic(err)
}
fields := makeFieldsFromSchema(header, opts.Schema, len(rows), opts.IgnoreUnknown, regex)
wg := sync.WaitGroup{}
wg.Add(len(fields))
for fieldIdx := range fields {
go func(fieldIdx int) {
defer wg.Done()
f := fields[fieldIdx]
if f == nil {
// Ignoring unknown field.
return
}
var timeLayout string
if f.Type() == data.FieldTypeNullableTime {
layout, err := detectTimeLayoutNaive(rows[0][fieldIdx])
if err != nil {
// TODO: Handle error instead of sending it to the log.
logger.Error(err.Error())
return
}
timeLayout = layout
}
for rowIdx := 0; rowIdx < f.Len(); rowIdx++ {
if err := parseCell(rows[rowIdx][fieldIdx], opts, timeLayout, rowIdx, f, location); err != nil {
// Ignore any cells that couldn't be parsed.
f.Set(rowIdx, nil)
}
}
}(fieldIdx)
}
wg.Wait()
// Remove ignored fields from result.
var res []*data.Field
for _, f := range fields {
if f != nil {
res = append(res, f)
}
}
return res, nil
}
func readCSV(opts csvOptions, r io.Reader) ([]string, [][]string, error) {
// Read one byte at a time until we've counted newlines equal to the number
// of skipped rows.
for i := 0; i < opts.SkipRows; i++ {
buf := make([]byte, 1)
for {
_, err := r.Read(buf)
if err != nil || buf[0] == '\n' {
break
}
}
}
rd := csv.NewReader(r)
rd.LazyQuotes = true
if len(opts.Delimiter) == 1 {
rd.Comma = rune(opts.Delimiter[0])
}
records, err := rd.ReadAll()
if err != nil {
return nil, nil, err
}
var rows [][]string
var header []string
if opts.Header {
header = records[0]
rows = records[1:]
} else {
if len(records) > 0 {
for i := 0; i < len(records[0]); i++ {
header = append(header, fmt.Sprintf("Field %d", i+1))
}
}
rows = records
}
return header, rows, nil
}
func parseCell(value string, opts csvOptions, timeLayout string, rowIdx int, f *data.Field, tz *time.Location) error {
switch f.Type() {
case data.FieldTypeNullableFloat64:
intPart, fracPart := splitNumberParts(value, opts.DecimalSeparator)
// Only one separator is allowed.
if strings.Contains(intPart, opts.DecimalSeparator) {
return errors.New("multiple decimal separators")
}
converted := strings.Map(func(r rune) rune {
switch r {
case ',', '.', ' ':
if string(r) == opts.DecimalSeparator {
return r
}
// Returning a negative value removes the character.
return -1
default:
return r
}
}, intPart) + "." + fracPart
n, err := strconv.ParseFloat(converted, 64)
if err != nil {
return err
}
f.Set(rowIdx, &n)
case data.FieldTypeNullableBool:
n, err := strconv.ParseBool(value)
if err != nil {
return err
}
f.Set(rowIdx, &n)
case data.FieldTypeNullableTime:
n, err := strconv.ParseInt(value, 10, 64)
if err == nil {
t := time.Unix(n, 0)
f.Set(rowIdx, &t)
return nil
}
if timeLayout != "" {
t, err := time.ParseInLocation(timeLayout, value, tz)
if err == nil {
f.Set(rowIdx, &t)
return nil
}
}
return errors.New("unsupported time format")
default:
f.Set(rowIdx, &value)
}
return nil
}
// makeFieldsFromSchema returns a field for every column defined in the header.
func makeFieldsFromSchema(header []string, schema []fieldSchema, size int, ignoreUnknown bool, regex bool) []*data.Field {
fields := make([]*data.Field, len(header))
for i, name := range header {
t, ok := typeFromName(name, schema, regex)
if !ok {
if ignoreUnknown {
continue
}
t = data.FieldTypeNullableString
}
f := data.NewFieldFromFieldType(t, size)
f.Name = name
fields[i] = f
}
return fields
}
func typeFromName(name string, schemas []fieldSchema, regex bool) (data.FieldType, bool) {
sch, ok := findSchema(schemas, name, regex)
if !ok {
return data.FieldTypeUnknown, false
}
return fieldType(sch.Type), true
}
func fieldType(str string) data.FieldType {
switch str {
case "number":
return data.FieldTypeNullableFloat64
case "boolean":
return data.FieldTypeNullableBool
case "time":
return data.FieldTypeNullableTime
default:
return data.FieldTypeNullableString
}
}
func findSchema(fields []fieldSchema, name string, regex bool) (res fieldSchema, ok bool) {
for _, sch := range fields {
if sch.Name == "" {
continue
}
if regex {
re, err := regexp.Compile(sch.Name)
if err != nil {
return
}
if re.MatchString(name) {
res = sch
ok = true
}
} else {
if sch.Name == name {
res = sch
ok = true
}
}
}
return
}
func splitNumberParts(str string, sep string) (string, string) {
idx := strings.LastIndex(str, sep)
if idx < 0 {
return str, "0"
}
return str[:idx], str[idx+1:]
}
// detectTimeLayoutNaive attempts to parse the string from a set of layouts, and
// returns the first one that matched.
func detectTimeLayoutNaive(str string) (string, error) {
layouts := []string{
"2006-01-02",
"2006-01-02 15:04",
"2006-01-02 15:04:05 MST",
"2006-01-02 15:04:05.999999",
"2006-01-02 15:04:05.999999 -07:00",
"2006-01-02 15:04:05.999999Z07:00",
"2006-01-02T15:04",
"2006-01-02T15:04:05 MST",
"2006-01-02T15:04:05.999999",
"2006-01-02T15:04:05.999999 -07:00",
"2006-01-02T15:04:05.999999Z07:00",
"2006/1/2",
"2006/01/02",
"2006/01/02 15:04",
"2006/01/02 15:04:05 MST",
"2006/01/02 15:04:05.999999",
"2006/01/02 15:04:05.999999 -07:00",
"2006/01/02 15:04:05.999999Z07:00",
"2006/01/02T15:04",
"2006/01/02T15:04:05 MST",
"2006/01/02T15:04:05.999999",
"2006/01/02T15:04:05.999999 -07:00",
"2006/01/02T15:04:05.999999Z07:00",
"01/02/2006",
"01/02/2006 15:04",
"01/02/2006 15:04:05 MST",
"01/02/2006 15:04:05.999999",
"01/02/2006 15:04:05.999999 -07:00",
"01/02/2006 15:04:05.999999Z07:00",
"01/02/2006T15:04",
"01/02/2006T15:04:05 MST",
"01/02/2006T15:04:05.999999",
"01/02/2006T15:04:05.999999 -07:00",
"01/02/2006T15:04:05.999999Z07:00",
}
for _, layout := range layouts {
if _, err := time.Parse(layout, str); err == nil {
return layout, nil
}
}
return "", errors.New("unsupported time format")
}