-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointer.go
More file actions
314 lines (290 loc) · 8 KB
/
Copy pathpointer.go
File metadata and controls
314 lines (290 loc) · 8 KB
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
package jsonptr
import (
"fmt"
"net/url"
"strconv"
"strings"
)
// Pointer represents a JSON Pointer
type Pointer struct {
path []string
}
// New returns a new JSON Pointer from the given string. The string can be a pointer, or a URI Fragment encoded pointer.
func New(ptr string) (*Pointer, error) {
var path []string
if looksLikeURIFragment(ptr) {
p, err := decodeURIFragmentIdent(ptr)
if err != nil {
return nil, err
}
path = p
} else {
p, err := decodePointer(ptr)
if err != nil {
return nil, err
}
path = p
}
return &Pointer{path}, nil
}
// MustConstruct returns a new JSON Pointer from the given string, or panics if the pointer is not valid, like regexp.MustCompile.
func MustConstruct(ptr string) *Pointer {
p, err := New(ptr)
if err != nil {
panic(err)
}
return p
}
// Get returns the value for the specified location in the document.
func (p *Pointer) Get(document interface{}) (interface{}, error) {
node := document
for _, seg := range p.path {
switch v := node.(type) {
case map[string]interface{}:
n, ok := v[seg]
if !ok {
return nil, fmt.Errorf("Map had no key when evaluating path segment '%s'", seg)
}
node = n
break
case []interface{}:
if seg == "-" {
return nil, fmt.Errorf("Cannot return '%s' index from JSON array", seg)
}
i, err := strconv.Atoi(seg)
if err != nil {
return nil, fmt.Errorf("Could not index when evaluating path segment '%s': %v", seg, err)
}
if i < 0 || i > len(v)-1 {
return nil, fmt.Errorf("Slice index %d is out of range (slice len=%d)", i, len(v))
}
node = v[i]
break
default:
return nil, fmt.Errorf("Unsupported node type %T when evaluating path segment '%s'", node)
}
}
return node, nil
}
// GetBool returns the value for the specified location in the document as a string, or false if not accessible.
func (p *Pointer) GetBool(document interface{}) bool {
node, _ := p.Get(document)
if b, ok := node.(bool); ok {
return b
}
return false
}
// GetString returns the value for the specified location in the document as a string, or an empty string if not accessible.
func (p *Pointer) GetString(document interface{}) string {
node, _ := p.Get(document)
if s, ok := node.(string); ok {
return s
}
if node != nil {
return fmt.Sprintf("%v", node)
}
return ""
}
// GetNumber returns the value for the specified location in the document as a string, or 0 if not accessible.
func (p *Pointer) GetNumber(document interface{}) float64 {
node, _ := p.Get(document)
if f, ok := node.(float64); ok {
return f
}
return 0
}
/*
Set sets the specified location in the document to the provided value,
returning an error if the value cannot be set. Set requires all segments in
the path to exist except for the final segment, and returns an error if
they do not.
Set cannot set the root pointer ("")
Set will return an error if it encounters a node in the path that is not of the
type map[string]interface{} or []interface{}, or if it cannot index into an
array with the provided path segment.
*/
func (p *Pointer) Set(document interface{}, val interface{}) error {
return set(p.path, document, val, false)
}
/*
Force sets the specified location in the document to the provided value,
returning an error if the value cannot be set. Force will create new
map[string]interface{} for segments that do not exist in the document
Force cannot set the root pointer ("")
Force will return an error if it encounters a node in the path that is not of the
type map[string]interface{} or []interface{}, or if it cannot index into an
array with the provided path segment.
*/
func (p *Pointer) Force(document interface{}, val interface{}) error {
return set(p.path, document, val, true)
}
func set(path []string, document interface{}, val interface{}, force bool) error {
node := document
if len(path) == 0 {
return fmt.Errorf("Cannot set root object, set it directly instead")
}
for i, seg := range path {
isLast := i == len(path)-1
switch v := node.(type) {
case map[string]interface{}:
n, ok := v[seg]
if !ok {
if !isLast {
if force {
n = map[string]interface{}{}
v[seg] = n
} else {
return fmt.Errorf("Map had no key when evaluating path segment '%s'", seg)
}
}
}
node = n
if isLast {
v[seg] = val
return nil
}
break
case []interface{}:
if seg == "-" {
if !isLast {
if force {
node = map[string]interface{}{}
if err := set(path[:i], document, append(v, node), false); err != nil {
return err
}
continue
} else {
return fmt.Errorf("Cannot append to JSON array when not forcing")
}
} else {
return set(path[:i], document, append(v, val), false) // set the immediate parent to the appended slice
}
}
i, err := strconv.Atoi(seg)
if err != nil {
return fmt.Errorf("Could not index when evaluating path segment '%s': %v", seg, err)
}
if i < 0 || (!force && i > len(v)-1) {
return fmt.Errorf("Slice index %d is out of range (slice len=%d): %v", i, len(v), err)
}
if force && i > len(v)-1 {
sl := make([]interface{}, i+1, i+1)
copy(sl, v)
if !isLast {
v[i] = map[string]interface{}{}
}
v = sl
if err := set(path[:i], document, sl, false); err != nil {
return err
}
}
if isLast {
v[i] = val
return nil
}
node = v[i]
break
default:
return fmt.Errorf("Unsupported node type %T when evaluating path segment '%s'", node)
}
}
return fmt.Errorf("Could not set value in path")
}
// Exists returns a boolean indicating whether the pointer location exists in
// the provided document.
func (p *Pointer) Exists(document interface{}) bool {
node := document
for _, seg := range p.path {
switch v := node.(type) {
case map[string]interface{}:
n, ok := v[seg]
if !ok {
return false
}
node = n
break
case []interface{}:
if seg == "-" {
return false
}
i, err := strconv.Atoi(seg)
if err != nil {
return false
}
if i < 0 || i > len(v)-1 {
return false
}
node = v[i]
break
default:
return false
}
}
return true
}
// Path returns the path segments of the pointer, as a slice of strings.
func (p *Pointer) Path() []string {
return p.path
}
// String returns the RFC 6901 string representation of the JSON pointer
func (p *Pointer) String() string {
if len(p.path) == 0 {
return ""
}
segments := make([]string, len(p.path))
copy(segments, p.path)
for i, seg := range segments {
segments[i] = strings.Replace(strings.Replace(seg, "~", "~0", -1), "/", "~1", -1)
}
return fmt.Sprintf("/%s", strings.Join(segments, "/"))
}
// URIFragmentIdent returns the RFC 6901 URI Fragment representation of the JSON pointer
func (p *Pointer) URIFragmentIdent() string {
if len(p.path) == 0 {
return "#"
}
segments := make([]string, len(p.path))
copy(segments, p.path)
for i, seg := range segments {
segments[i] = url.QueryEscape(strings.Replace(strings.Replace(seg, "~", "~0", -1), "/", "~1", -1))
}
return fmt.Sprintf("#/%s", strings.Join(segments, "/"))
}
func looksLikeURIFragment(ptr string) bool {
return strings.HasPrefix(ptr, "#")
}
func unescape(str string) string {
res, _ := url.QueryUnescape(str)
if res == "" {
return str
}
return res
}
func decodeURIFragmentIdent(ptr string) ([]string, error) {
if len(ptr) == 1 {
return []string{}, nil
}
if !strings.HasPrefix(ptr, "#/") {
return nil, fmt.Errorf("Invalid JSON Pointer syntax")
}
segments := strings.Split(ptr, "/")
result := make([]string, len(segments)-1)
for i, seg := range segments[1:] {
result[i] = strings.Replace(strings.Replace(unescape(seg), "~1", "/", -1), "~0", "~", -1)
}
return result, nil
}
func decodePointer(ptr string) ([]string, error) {
if len(ptr) == 0 {
return []string{}, nil
}
if !strings.HasPrefix(ptr, "/") {
return nil, fmt.Errorf("Invalid JSON Pointer syntax")
}
segments := strings.Split(ptr, "/")
result := make([]string, len(segments)-1)
for i, seg := range segments[1:] {
result[i] = strings.Replace(strings.Replace(seg, "~1", "/", -1), "~0", "~", -1)
}
return result, nil
}