-
Notifications
You must be signed in to change notification settings - Fork 20
/
unmarshal.go
433 lines (362 loc) · 8.96 KB
/
unmarshal.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package goq
import (
"bytes"
"reflect"
"strconv"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
)
// Unmarshaler allows for custom implementations of unmarshaling logic
type Unmarshaler interface {
UnmarshalHTML([]*html.Node) error
}
// NodeSelector is a quick utility function to get a goquery.Selection from a
// slice of *html.Node. Useful for performing unmarshaling, since the decision
// was made to use []*html.Node for maximum flexibility.
func NodeSelector(nodes []*html.Node) *goquery.Selection {
sel := &goquery.Selection{}
return sel.AddNodes(nodes...)
}
type valFunc func(*goquery.Selection) string
type goqueryTag string
const (
prePfx = '!'
tagName = "goquery"
ignoreTag = "!ignore"
)
func (tag goqueryTag) preprocess(s *goquery.Selection) *goquery.Selection {
arr := strings.Split(string(tag), ",")
var offset int
for len(arr)-1 > offset && arr[offset][0] == prePfx {
meth := arr[offset][1:]
v := reflect.ValueOf(s).MethodByName(meth)
if !v.IsValid() {
return s
}
result := v.Call(nil)
if sel, ok := result[0].Interface().(*goquery.Selection); ok {
s = sel
}
offset++
}
return s
}
func (tag goqueryTag) selector(which int) string {
arr := strings.Split(string(tag), ",")
if which > len(arr)-1 {
return ""
}
var offset int
for len(arr) > offset && arr[offset][0] == prePfx {
offset++
}
return arr[which+offset]
}
var (
textVal valFunc = func(s *goquery.Selection) string {
return strings.TrimSpace(s.Text())
}
htmlVal = func(s *goquery.Selection) string {
str, _ := s.Html()
return strings.TrimSpace(str)
}
vfCache sync.Map
)
func attrFunc(attr string) valFunc {
return func(s *goquery.Selection) string {
str, _ := s.Attr(attr)
return str
}
}
func (tag goqueryTag) valFunc() valFunc {
if fn, ok := vfCache.Load(tag); ok {
return fn.(valFunc)
}
srcArr := strings.Split(string(tag), ",")
if len(srcArr) < 2 {
vfCache.Store(tag, textVal)
return textVal
}
src := srcArr[1]
var f valFunc
switch {
case src[0] == '[':
// [someattr] will return value of .Attr("someattr")
attr := src[1 : len(src)-1]
f = attrFunc(attr)
case src == "html":
f = htmlVal
case src == "text":
f = textVal
default:
f = textVal
}
vfCache.Store(tag, f)
return f
}
// popVal should allow us to handle arbitrarily nested maps as well as the
// cleanly handling the possiblity of map[literal]literal by just delegating
// back to `unmarshalByType`.
func (tag goqueryTag) popVal() goqueryTag {
arr := strings.Split(string(tag), ",")
if len(arr) < 2 {
return tag
}
newA := []string{arr[0]}
newA = append(newA, arr[2:]...)
return goqueryTag(strings.Join(newA, ","))
}
// Unmarshal takes a byte slice and a destination pointer to any
// interface{}, and unmarshals the document into the destination based on the
// rules above. Any error returned here will likely be of type
// CannotUnmarshalError, though an initial goquery error will pass through
// directly.
func Unmarshal(bs []byte, v interface{}) error {
d, err := goquery.NewDocumentFromReader(bytes.NewReader(bs))
if err != nil {
return err
}
return UnmarshalSelection(d.Selection, v)
}
func wrapUnmErr(err error, v reflect.Value) error {
if err == nil {
return nil
}
return &CannotUnmarshalError{
V: v,
Reason: customUnmarshalError,
Err: err,
}
}
// UnmarshalSelection will unmarshal a goquery.goquery.Selection into an interface
// appropriately annoated with goquery tags.
func UnmarshalSelection(s *goquery.Selection, iface interface{}) error {
v := reflect.ValueOf(iface)
// Must come before v.IsNil() else IsNil panics on NonPointer value
if v.Kind() != reflect.Ptr {
return &CannotUnmarshalError{V: v, Reason: nonPointer}
}
if iface == nil || v.IsNil() {
return &CannotUnmarshalError{V: v, Reason: nilValue}
}
u, v := indirect(v)
if u != nil {
return wrapUnmErr(u.UnmarshalHTML(s.Nodes), v)
}
return unmarshalByType(s, v, "")
}
func unmarshalByType(s *goquery.Selection, v reflect.Value, tag goqueryTag) error {
u, v := indirect(v)
if u != nil {
return wrapUnmErr(u.UnmarshalHTML(s.Nodes), v)
}
// Handle special cases where we can just set the value directly
switch val := v.Interface().(type) {
case []*html.Node:
val = append(val, s.Nodes...)
v.Set(reflect.ValueOf(val))
return nil
}
t := v.Type()
switch t.Kind() {
case reflect.Struct:
return unmarshalStruct(s, v)
case reflect.Slice:
return unmarshalSlice(s, v, tag)
case reflect.Array:
return unmarshalArray(s, v, tag)
case reflect.Map:
return unmarshalMap(s, v, tag)
default:
vf := tag.valFunc()
str := vf(s)
err := unmarshalLiteral(str, v)
if err != nil {
return &CannotUnmarshalError{
V: v,
Reason: typeConversionError,
Err: err,
Val: str,
}
}
return nil
}
}
func unmarshalLiteral(s string, v reflect.Value) error {
t := v.Type()
switch t.Kind() {
case reflect.Interface:
if t.NumMethod() == 0 {
// For empty interfaces, just set to a string
nv := reflect.New(reflect.TypeOf(s)).Elem()
nv.Set(reflect.ValueOf(s))
v.Set(nv)
}
case reflect.Bool:
i, err := strconv.ParseBool(s)
if err != nil {
return err
}
v.SetBool(i)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
v.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return err
}
v.SetUint(i)
case reflect.Float32, reflect.Float64:
i, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
v.SetFloat(i)
case reflect.String:
v.SetString(s)
}
return nil
}
func unmarshalStruct(s *goquery.Selection, v reflect.Value) error {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
tag := goqueryTag(t.Field(i).Tag.Get(tagName))
if tag == ignoreTag {
continue
}
// If tag is empty and the object doesn't implement Unmarshaler, skip
if tag == "" {
if u, _ := indirect(v.Field(i)); u == nil {
continue
}
}
sel := tag.preprocess(s)
if tag != "" {
selStr := tag.selector(0)
sel = sel.Find(selStr)
}
err := unmarshalByType(sel, v.Field(i), tag)
if err != nil {
return &CannotUnmarshalError{
Reason: typeConversionError,
Err: err,
V: v,
FldOrIdx: t.Field(i).Name,
}
}
}
return nil
}
func unmarshalArray(s *goquery.Selection, v reflect.Value, tag goqueryTag) error {
if v.Type().Len() != len(s.Nodes) {
return &CannotUnmarshalError{
Reason: arrayLengthMismatch,
V: v,
}
}
for i := 0; i < v.Type().Len(); i++ {
err := unmarshalByType(s.Eq(i), v.Index(i), tag)
if err != nil {
return &CannotUnmarshalError{
Reason: typeConversionError,
Err: err,
V: v,
FldOrIdx: i,
}
}
}
return nil
}
func unmarshalSlice(s *goquery.Selection, v reflect.Value, tag goqueryTag) error {
slice := v
eleT := v.Type().Elem()
for i := 0; i < s.Length(); i++ {
newV := reflect.New(TypeDeref(eleT))
err := unmarshalByType(s.Eq(i), newV, tag)
if err != nil {
return &CannotUnmarshalError{
Reason: typeConversionError,
Err: err,
V: v,
FldOrIdx: i,
}
}
if eleT.Kind() != reflect.Ptr {
newV = newV.Elem()
}
v = reflect.Append(v, newV)
}
slice.Set(v)
return nil
}
func childrenUntilMatch(s *goquery.Selection, sel string) *goquery.Selection {
orig := s
s = s.Children()
for s.Length() != 0 && s.Filter(sel).Length() == 0 {
s = s.Children()
}
if s.Length() == 0 {
return orig
}
return s.Filter(sel)
}
func unmarshalMap(s *goquery.Selection, v reflect.Value, tag goqueryTag) error {
// Make new map here because indirect for some Reason doesn't help us out
if v.IsNil() {
v.Set(reflect.MakeMap(v.Type()))
}
keyT, eleT := v.Type().Key(), v.Type().Elem()
if tag.selector(1) == "" {
// We need minimum one value selector to determine the map key
return &CannotUnmarshalError{
Reason: missingValueSelector,
V: v,
}
}
valTag := tag
// Find children at the same level that match the given selector
s = childrenUntilMatch(s, tag.selector(1))
// Then augment the selector we will pass down to the next unmarshal step
valTag = valTag.popVal()
var err error
s.EachWithBreak(func(_ int, subS *goquery.Selection) bool {
newK, newV := reflect.New(TypeDeref(keyT)), reflect.New(TypeDeref(eleT))
err = unmarshalByType(subS, newK, tag)
if err != nil {
err = &CannotUnmarshalError{
Reason: mapKeyUnmarshalError,
V: v,
Err: err,
FldOrIdx: newK.Interface(),
Val: valTag.valFunc()(subS),
}
return false
}
err = unmarshalByType(subS, newV, valTag)
if err != nil {
return false
}
if eleT.Kind() != reflect.Ptr {
newV = newV.Elem()
}
if keyT.Kind() != reflect.Ptr {
newK = newK.Elem()
}
v.SetMapIndex(newK, newV)
return true
})
if err != nil {
return &CannotUnmarshalError{
Reason: typeConversionError,
Err: err,
V: v,
}
}
return nil
}