-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparse.go
324 lines (295 loc) · 6.85 KB
/
parse.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
package jsonpath
import (
"errors"
"io"
"reflect"
"sort"
"strconv"
"strings"
)
type Applicator interface {
Apply(v interface{}) (interface{}, error)
}
type node interface {
Applicator
SetNext(v node)
}
var (
MapTypeError = errors.New("Expected Type to be a Map.")
ArrayTypeError = errors.New("Expected Type to be an Array.")
SyntaxError = errors.New("Bad Syntax.")
NotSupportedError = errors.New("Not Supported")
NotFound = errors.New("Not Found")
IndexOutOfBounds = errors.New("Out of Bounds")
)
func applyNext(nn node, v interface{}) (interface{}, error) {
if nn == nil {
return v, nil
}
return nn.Apply(v)
}
// RootNode is always the top node. It does not really do anything other then
// delegate to the next node, and acts as a starting point.
// Every other node type embeds this node To get the NextNode functions.
type RootNode struct {
// The next Node in the sequence.
NextNode node
}
// Set the next node.
func (r *RootNode) SetNext(n node) {
r.NextNode = n
}
// Apply is the main workhourse, each node type will apply it's filtering rules
// to the provided value, returning the filtered result.
// It is expected that the node will call's it's Next Nodes Apply method as
// need by the rules of the Node.
func (r *RootNode) Apply(v interface{}) (interface{}, error) {
return applyNext(r.NextNode, v)
}
// MapSelection is a the basic filter for a Map type key. It will look at the
// in coming v and try to turn it into a map[string]interface{} value. If it
// successeeds it will then apply the NextNode to that interface value, or it
// will return the value if it has no NextNode.
type MapSelection struct {
Key string
RootNode
}
func (m *MapSelection) Apply(v interface{}) (interface{}, error) {
mv, ok := v.(map[string]interface{})
if !ok {
return v, MapTypeError
}
nv, ok := mv[m.Key]
if !ok {
return nil, NotFound
}
return applyNext(m.NextNode, nv)
}
// ArrySelection is a the basic filter for a Array type key. It is like MapSelection but for Arrays.
type ArraySelection struct {
Key int
RootNode
}
func (a *ArraySelection) Apply(v interface{}) (interface{}, error) {
arv, ok := v.([]interface{})
if !ok {
return v, ArrayTypeError
}
// Check to see if the value is in bounds for the array.
if a.Key < 0 || a.Key >= len(arv) {
return nil, IndexOutOfBounds
}
return applyNext(a.NextNode, arv[a.Key])
}
// WildCardSelection is a filter that grabs all the values and returns an Array of them
// It applies it's NextNode on each value.
type WildCardSelection struct {
RootNode
}
func (w *WildCardSelection) Apply(v interface{}) (interface{}, error) {
switch tv := v.(type) {
case map[string]interface{}:
var ret []interface{}
var keys []string
for key, _ := range tv {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
rval, err := applyNext(w.NextNode, tv[key])
// Don't add anything that causes an error or returns nil.
if err == nil || rval != nil {
ret = append(ret, rval)
}
}
return ret, nil
case []interface{}:
var ret []interface{}
for _, val := range tv {
rval, err := applyNext(w.NextNode, val)
// Don't add anything that causes an error or returns nil.
if err == nil || rval != nil {
ret = append(ret, rval)
}
}
return ret, nil
default:
return applyNext(w.NextNode, v)
}
}
// DescentSelection is a filter that recursively descends applying it's NextNode and
// corrlating the results.
type DescentSelection struct {
RootNode
}
func isNil(i interface{}) bool {
vi := reflect.ValueOf(i)
if !vi.IsValid() {
return true
}
switch vi.Kind() {
case reflect.Chan, reflect.Interface, reflect.Func, reflect.Slice, reflect.Map, reflect.Ptr:
return vi.IsNil()
default:
return false
}
}
func flattenAppend(src []interface{}, values ...interface{}) []interface{} {
for _, value := range values {
av, ok := value.([]interface{})
if ok {
if len(av) > 0 {
src = flattenAppend(src, av...)
}
} else {
src = append(src, value)
}
}
return src
}
func (d *DescentSelection) Apply(v interface{}) (interface{}, error) {
var ret []interface{}
rval, err := applyNext(d.NextNode, v)
// Ignore errors here.
if err == nil && !isNil(rval) {
ret = flattenAppend(ret, rval)
}
switch tv := v.(type) {
default:
return ret, nil
case map[string]interface{}:
var keys []string
for key, _ := range tv {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
rval, err := d.Apply(tv[key])
// Don't add anything that causes an error or returns nil.
if err == nil && !isNil(rval) {
ret = flattenAppend(ret, rval)
}
}
return ret, nil
case []interface{}:
for _, val := range tv {
rval, err := d.Apply(val)
// Don't add anything that causes an error or returns nil.
if err == nil && !isNil(rval) {
ret = flattenAppend(ret, rval)
}
}
return ret, nil
}
}
// The first thing we need to do is transform a dot–notation to a bracket–notation.
func minNotNeg1(a int, bs ...int) int {
m := a
for _, b := range bs {
if a == -1 || (b != -1 && b < m) {
m = b
}
}
return m
}
func normalize(s string) string {
if s == "" || s == "$." {
return "$"
}
r := "$"
// first thing to do is read passed the $
if s[0] == '$' {
s = s[1:]
}
for len(s) > 0 {
// Grab all the bracketed entries
for len(s) > 0 && s[0] == '[' {
n := strings.Index(s, "]")
r += s[0 : n+1]
s = s[n+1:]
}
if len(s) <= 0 || s == "." {
break
}
if s[0] == '.' {
if s[1] == '.' {
r += "[..]"
s = s[2:]
} else {
s = s[1:]
}
}
if len(s) == 0 {
break
}
if s[0] == '*' {
r += "[*]"
if len(s) == 1 {
break
}
s = s[1:]
}
n := minNotNeg1(strings.Index(s, "["), strings.Index(s, "."))
if n == 0 {
continue
}
if n != -1 {
r += `["` + s[:n] + `"]`
s = s[n:]
} else {
r += `["` + s + `"]`
s = ""
}
}
return r
}
func getNode(s string) (node, string, error) {
var rs string
if len(s) == 0 {
return nil, s, io.EOF
}
n := strings.Index(s, "]")
if n == -1 {
return nil, s, SyntaxError
}
if len(s) > n {
rs = s[n+1:]
}
switch s[:2] {
case "[\"":
return &MapSelection{Key: s[2 : n-1]}, rs, nil
case "[*":
return &WildCardSelection{}, rs, nil
case "[.":
return &DescentSelection{}, rs, nil
case "[?", "[(":
return nil, rs, NotSupportedError
default: // Assume it's a array index otherwise.
i, err := strconv.Atoi(s[1:n])
if err != nil {
return nil, rs, SyntaxError
}
return &ArraySelection{Key: i}, rs, nil
}
}
// Parse parses the JSONPath and returns a object that can be applied to
// a structure to filter it down.
func Parse(s string) (Applicator, error) {
var nn node
var err error
s = normalize(s)
rt := RootNode{}
// Remove the starting '$'
s = s[1:]
var c node
c = &rt
for len(s) > 0 {
nn, s, err = getNode(s)
if err != nil {
return nil, err
}
c.SetNext(nn)
c = nn
}
return &rt, nil
}