-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
328 lines (304 loc) · 7.57 KB
/
parser.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
package googlesheetsparser
import (
"errors"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"time"
"github.com/gertd/go-pluralize"
"google.golang.org/api/sheets/v4"
)
var pluralizeClient = pluralize.NewClient()
var (
ErrNoSpreadSheetID = errors.New("no spreadsheet id provided")
ErrNoSheetName = errors.New("no sheet name provided")
ErrUnsupportedType = errors.New("unsupported type")
ErrFieldNotFoundInStruct = errors.New("field not found in struct")
ErrInvalidDateTimeFormat = errors.New("invalid datetime format")
)
var dateTimeFormats = []string{
"2006-01-02",
"2006-01-02 15:04:05",
"2006-01-02 15:04:05 -0700",
}
type Options struct {
Service *sheets.Service
SpreadsheetID string
SheetName string
DatetimeFormats []string
built bool
}
func (o Options) Build() Options {
if o.built {
return o
}
o.built = true
o.DatetimeFormats = append(o.DatetimeFormats, dateTimeFormats...)
return o
}
// ParseSheetIntoStructCb parses a sheet page and calls the callback for each object.
func ParseSheetIntoStructCb[K any](options Options, cb func(K)) (err error) {
if !options.built {
log.Println("googlesheetsparser: Warning: Using options that are not built")
}
// Set Params
var k K
spreadSheetId := options.SpreadsheetID
sheetName := pluralizeClient.Plural(reflect.TypeOf(k).Name())
if options.SheetName != "" {
sheetName = options.SheetName
}
// Validate Params
if spreadSheetId == "" {
return ErrNoSpreadSheetID
}
if sheetName == "" {
return ErrNoSheetName
}
resp, err := options.Service.Spreadsheets.Values.Get(spreadSheetId, sheetName).Do()
if err != nil {
return err
}
mappings, err := createMappings[K](resp)
if err != nil {
return err
}
fillEmptyValues(resp)
for rowIdx, row := range resp.Values[1:] {
var k K
for i := range mappings {
field := mappings[i]
val, err := reflectParseString(field.Type, row[i].(string), options.DatetimeFormats, rowIdx, i)
if err != nil {
return fmt.Errorf("%s: %s%d: %w", sheetName, getColumnName(i), rowIdx+2, err)
}
reflect.ValueOf(&k).Elem().FieldByName(field.Name).Set(val)
}
cb(k)
}
return nil
}
// ParseSheetIntoStructSlice parses a sheet page and returns a slice of structs with the give type.
func ParseSheetIntoStructSlice[K any](options Options) ([]K, error) {
var res []K
err := ParseSheetIntoStructCb(options, func(k K) {
res = append(res, k)
})
return res, err
}
func fillEmptyValues(data *sheets.ValueRange) {
var maxWidth int
for _, row := range data.Values {
if len(row) > maxWidth {
maxWidth = len(row)
}
}
for rowIdx, row := range data.Values {
for colIdx := len(row); colIdx < maxWidth; colIdx++ {
data.Values[rowIdx] = append(data.Values[rowIdx], "")
}
}
}
func reflectParseString(pReflectType reflect.Type, cell string, dateTimeFormats []string, rowIdx, colIdx int) (reflect.Value, error) {
reflectType := pReflectType
var isPointer bool
isEmpty := cell == ""
if reflectType.Kind() == reflect.Pointer {
reflectType = reflectType.Elem()
isPointer = true
}
if isPointer && isEmpty {
return reflect.Zero(pReflectType), nil
}
switch reflectType.Kind() {
case reflect.String:
if isPointer {
return reflect.ValueOf(&cell), nil
}
return reflect.ValueOf(cell), nil
case reflect.Int:
i, err := strconv.Atoi(cell)
if err != nil {
return reflect.ValueOf(0), err
}
if isPointer {
return reflect.ValueOf(&i), nil
}
return reflect.ValueOf(i), nil
case reflect.Int8:
i, err := strconv.ParseInt(cell, 10, 8)
if err != nil {
return reflect.ValueOf(0), err
}
res := int8(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Int16:
i, err := strconv.ParseInt(cell, 10, 16)
if err != nil {
return reflect.ValueOf(0), err
}
res := int16(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Int32:
i, err := strconv.ParseInt(cell, 10, 32)
if err != nil {
return reflect.ValueOf(0), err
}
res := int32(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Int64:
i, err := strconv.ParseInt(cell, 10, 64)
if err != nil {
return reflect.ValueOf(0), err
}
res := int64(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Uint:
i, err := strconv.ParseUint(cell, 10, 0)
if err != nil {
return reflect.ValueOf(0), err
}
res := uint(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Uint8:
i, err := strconv.ParseUint(cell, 10, 8)
if err != nil {
return reflect.ValueOf(0), err
}
res := uint8(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Uint16:
i, err := strconv.ParseUint(cell, 10, 16)
if err != nil {
return reflect.ValueOf(0), err
}
res := uint16(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Uint32:
i, err := strconv.ParseUint(cell, 10, 32)
if err != nil {
return reflect.ValueOf(0), err
}
res := uint32(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Uint64:
i, err := strconv.ParseUint(cell, 10, 64)
if err != nil {
return reflect.ValueOf(0), err
}
res := uint64(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Float32:
i, err := strconv.ParseFloat(cell, 32)
if err != nil {
return reflect.ValueOf(0), err
}
res := float32(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Float64:
i, err := strconv.ParseFloat(cell, 64)
if err != nil {
return reflect.ValueOf(0), err
}
res := float64(i)
if isPointer {
return reflect.ValueOf(&res), nil
}
return reflect.ValueOf(res), nil
case reflect.Bool:
i, err := strconv.ParseBool(cell)
if err != nil {
return reflect.ValueOf(false), err
}
if isPointer {
return reflect.ValueOf(&i), nil
}
return reflect.ValueOf(i), nil
case reflect.Struct:
if reflectType.String() == "time.Time" {
for _, dateTimeFormat := range dateTimeFormats {
t, err := time.Parse(dateTimeFormat, cell)
if err == nil {
if isPointer {
return reflect.ValueOf(&t), nil
}
return reflect.ValueOf(t), nil
}
}
return reflect.ValueOf(time.Time{}), fmt.Errorf("%w: %s", ErrInvalidDateTimeFormat, cell)
}
}
return reflect.ValueOf(nil), fmt.Errorf("%w: %s", ErrUnsupportedType, reflectType.Kind().String())
}
func createMappings[K any](data *sheets.ValueRange) (mappings []reflect.StructField, err error) {
firstRow := data.Values[0]
for colIdx, cellIf := range firstRow {
cell := cellIf.(string)
if cell == "" {
break
}
field := reflectGetFieldByTagOrName[K](cell)
if field == nil {
err = fmt.Errorf("%w: %s%d: %s", ErrFieldNotFoundInStruct, getColumnName(colIdx), 1, cell)
return
}
mappings = append(mappings, *field)
}
return
}
func reflectGetFieldByTagOrName[K any](name string) *reflect.StructField {
var k K
typeOfK := reflect.TypeOf(k)
for i := 0; i < typeOfK.NumField(); i++ {
field := typeOfK.Field(i)
if sheetName, ok := field.Tag.Lookup("sheets"); ok && sheetName == name {
return &field
}
}
if field, ok := typeOfK.FieldByName(name); ok {
return &field
}
return nil
}
func getColumnName(index int) string {
index += 1
var res string
for index > 0 {
index--
res = string(rune(index%26+97)) + res
index /= 26
}
return strings.ToUpper(res)
}