This repository has been archived by the owner on Jan 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bft.go
95 lines (89 loc) · 1.98 KB
/
bft.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
package goxic
import (
"fmt"
"reflect"
"strconv"
"strings"
)
const (
BftMarker = "$"
BftPathSep = "."
)
var zero = reflect.Value{}
func bftResolve(path string, data interface{}) (bindThis interface{}, err error) {
psegs := strings.Split(path, BftPathSep)
for si, seg := range psegs {
rval := reflect.ValueOf(data)
if idx, err := strconv.Atoi(seg); err == nil {
switch rval.Type().Kind() {
case reflect.Array, reflect.Slice:
if idx < 0 {
idx = rval.Len() + idx
}
if idx < 0 || idx >= rval.Len() {
return nil, nil
}
data = rval.Index(idx).Interface()
default:
return nil, fmt.Errorf("segemnt %d in path '%s' requires slice or array, got %s",
si,
path,
rval.Type().Kind())
}
} else {
switch rval.Type().Kind() {
case reflect.Map:
tmp := rval.MapIndex(reflect.ValueOf(seg))
if tmp == zero {
return nil, nil
} else {
data = tmp.Interface()
}
case reflect.Struct:
tmp := rval.FieldByName(seg)
if tmp == zero {
return nil, nil
} else {
data = tmp.Interface()
}
default:
return nil, fmt.Errorf("segemnt %d in path '%s' requires map or struct, got %s",
si,
path,
rval.Type().Kind())
}
}
}
return data, nil
}
func bftSplitSpec(specPh string) (fmt string, path string) {
sep := strings.Index(specPh, " ")
if sep > 0 {
return specPh[:sep], specPh[sep+1:]
}
return "", specPh
}
func (bt *BounT) Fill(data interface{}, overwrite bool) (missed int, err error) {
tpl := bt.Template()
for ph, idxs := range tpl.plhNm2Idxs {
if !strings.HasPrefix(ph, BftMarker) {
continue
}
ph := ph[1:]
// TODO maybe its efficient to 1st check if there is something to bind
// consider overwrite
fmt, path := bftSplitSpec(ph)
bv, err := bftResolve(path, data) // TODO slow?
if err != nil {
return -1, err
}
if bv == nil {
missed++
} else if len(fmt) == 0 {
bt.BindP(idxs, bv)
} else {
bt.BindFmt(idxs, fmt, bv)
}
}
return missed, nil
}