-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathjsonpointer.go
More file actions
431 lines (357 loc) · 14.5 KB
/
jsonpointer.go
File metadata and controls
431 lines (357 loc) · 14.5 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
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
// Package jsonpointer provides JSONPointer an implementation of RFC6901 https://datatracker.ietf.org/doc/html/rfc6901
package jsonpointer
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/speakeasy-api/openapi/errors"
"github.com/speakeasy-api/openapi/internal/interfaces"
"gopkg.in/yaml.v3"
)
const (
// ErrNotFound is returned when the target is not found.
ErrNotFound = errors.Error("not found")
// ErrInvalidPath is returned when the path is invalid.
ErrInvalidPath = errors.Error("invalid path")
// ErrValidation is returned when the jsonpointer is invalid.
ErrValidation = errors.Error("validation error")
// ErrSkipInterface is returned when this implementation of the interface is not applicable to the current type.
ErrSkipInterface = errors.Error("skip interface")
)
const (
DefaultStructTag = "key"
)
type option func(o *options)
type options struct {
StructTags []string
}
// WithStructTags will set the type of struct tags to use when navigating structs.
func WithStructTags(structTags ...string) option {
return func(o *options) {
o.StructTags = structTags
}
}
func getOptions(opts []option) *options {
o := &options{
StructTags: []string{DefaultStructTag},
}
for _, opt := range opts {
opt(o)
}
return o
}
// JSONPointer represents a JSON Pointer value as defined by RFC6901 https://datatracker.ietf.org/doc/html/rfc6901
type JSONPointer string
var _ fmt.Stringer = (*JSONPointer)(nil)
func (j JSONPointer) String() string {
return string(j)
}
// Validate will validate the JSONPointer is valid as per RFC6901.
func (j JSONPointer) Validate() error {
_, err := j.getNavigationStack()
if err != nil {
return ErrValidation.Wrap(err)
}
return nil
}
// GetTarget will evaluate the JSONPointer against the source and return the target.
// WithStructTags can be used to set the type of struct tags to use when navigating structs.
// If the struct implements any of the Navigable interfaces it will be used to navigate the source.
func GetTarget(source any, pointer JSONPointer, opts ...option) (any, error) {
o := getOptions(opts)
stack, err := pointer.getNavigationStack()
if err != nil {
return nil, ErrValidation.Wrap(err)
}
target, _, err := getCurrentStackTarget(source, stack, "/", o)
if err != nil {
return nil, err
}
return target, nil
}
// PartsToJSONPointer will convert the exploded parts of a JSONPointer to a JSONPointer.
func PartsToJSONPointer(parts []string) JSONPointer {
var sb strings.Builder
for _, part := range parts {
sb.WriteByte('/')
sb.WriteString(escape(part))
}
return JSONPointer(sb.String())
}
func getCurrentStackTarget(source any, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if len(stack) == 0 {
// For YAML nodes, delegate to YAML implementation for proper root handling
if yamlNode, ok := source.(*yaml.Node); ok {
return getYamlNodeTarget(yamlNode, navigationPart{}, []navigationPart{}, currentPath, o)
}
if yamlNode, ok := source.(yaml.Node); ok {
return getYamlNodeTarget(&yamlNode, navigationPart{}, []navigationPart{}, currentPath, o)
}
return source, stack, nil
}
currentPart := stack[0]
stack = stack[1:]
currentPath = buildPath(currentPath, currentPart)
return getTarget(source, currentPart, stack, currentPath, o)
}
func getTarget(source any, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
// Handle yaml.Node specially (both pointer and non-pointer versions)
if yamlNode, ok := source.(*yaml.Node); ok {
return getYamlNodeTarget(yamlNode, currentPart, stack, currentPath, o)
}
if yamlNode, ok := source.(yaml.Node); ok {
return getYamlNodeTarget(&yamlNode, currentPart, stack, currentPath, o)
}
sourceType := reflect.TypeOf(source)
sourceElemType := sourceType
if sourceType.Kind() == reflect.Ptr {
sourceElemType = sourceType.Elem()
}
switch sourceElemType.Kind() {
case reflect.Map:
return getMapTarget(reflect.ValueOf(source), currentPart, stack, currentPath, o)
case reflect.Slice, reflect.Array:
return getSliceTarget(reflect.ValueOf(source), currentPart, stack, currentPath, o)
case reflect.Struct:
return getStructTarget(reflect.ValueOf(source), currentPart, stack, currentPath, o)
default:
return nil, nil, ErrInvalidPath.Wrap(fmt.Errorf("expected map, slice, struct, or yaml.Node, got %s at %s", sourceElemType.Kind(), currentPath))
}
}
func getMapTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
sourceValElem := reflect.Indirect(sourceVal)
// Allow both partTypeKey and partTypeIndex for maps (integer keys should be treated as string keys)
if sourceValElem.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("map is nil at %s", currentPath))
}
keyStr := currentPart.unescapeValue()
keyType := sourceValElem.Type().Key()
// Convert the string key to the appropriate type for the map
var keyValue reflect.Value
switch keyType.Kind() {
case reflect.String:
keyValue = reflect.ValueOf(keyStr)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if intKey, err := strconv.Atoi(keyStr); err == nil {
keyValue = reflect.ValueOf(intKey).Convert(keyType)
} else {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("key %s cannot be converted to %s at %s", keyStr, keyType.Kind(), currentPath))
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if uintKey, err := strconv.ParseUint(keyStr, 10, 64); err == nil {
keyValue = reflect.ValueOf(uintKey).Convert(keyType)
} else {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("key %s cannot be converted to %s at %s", keyStr, keyType.Kind(), currentPath))
}
default:
return nil, nil, ErrInvalidPath.Wrap(fmt.Errorf("unsupported map key type %s at %s", keyType.Kind(), currentPath))
}
target := sourceValElem.MapIndex(keyValue)
if !target.IsValid() || target.IsZero() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("key %s not found in map at %s", keyStr, currentPath))
}
return getCurrentStackTarget(target.Interface(), stack, currentPath, o)
}
func getSliceTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
sourceValElem := reflect.Indirect(sourceVal)
if currentPart.Type != partTypeIndex {
return nil, nil, ErrInvalidPath.Wrap(fmt.Errorf("expected index, got %s at %s", currentPart.Type, currentPath))
}
if sourceValElem.Kind() == reflect.Slice && sourceValElem.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("slice is nil at %s", currentPath))
}
index := currentPart.getIndex()
if index < 0 || index >= sourceValElem.Len() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("index %d out of range for slice/array of length %d at %s", index, sourceValElem.Len(), currentPath))
}
return getCurrentStackTarget(sourceValElem.Index(index).Interface(), stack, currentPath, o)
}
// KeyNavigable is an interface that can be implemented by a struct to allow navigation by key, bypassing navigating by struct tags.
type KeyNavigable interface {
NavigateWithKey(key string) (any, error)
}
// IndexNavigable is an interface that can be implemented by a struct to allow navigation by index if the struct wraps some slice like type.
type IndexNavigable interface {
NavigateWithIndex(index int) (any, error)
}
// NavigableNoder is an interface that can be implemented by a struct to allow returning an alternative node to evaluate instead of the struct itself.
type NavigableNoder interface {
GetNavigableNode() (any, error)
}
func getStructTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("struct is nil at %s", currentPath))
}
if interfaces.ImplementsInterface[NavigableNoder](sourceVal.Type()) {
val, stack, err := getNavigableNoderTarget(sourceVal, currentPart, stack, currentPath, o)
if err != nil {
if !errors.Is(err, ErrSkipInterface) {
return nil, nil, err
}
} else {
return val, stack, nil
}
}
if interfaces.ImplementsInterface[model](sourceVal.Type()) {
val, stack, err := navigateModel(sourceVal, currentPart, stack, currentPath, o)
if err != nil {
if !errors.Is(err, ErrSkipInterface) {
return nil, nil, err
}
} else {
return val, stack, nil
}
}
switch currentPart.Type {
case partTypeKey:
return getKeyBasedStructTarget(sourceVal, currentPart, stack, currentPath, o)
case partTypeIndex:
// Try key-based navigation first for integer parts
keyPart := navigationPart{
Type: partTypeKey,
Value: currentPart.Value,
}
result, nextVal, err := getKeyBasedStructTarget(sourceVal, keyPart, stack, currentPath, o)
if err == nil {
return result, nextVal, nil
}
// If key navigation fails but doesn't return a "not found" error,
// we should still return the error instead of trying index navigation
if !errors.Is(err, ErrNotFound) {
return nil, nil, err
}
// Fall back to index-based navigation
return getIndexBasedStructTarget(sourceVal, currentPart, stack, currentPath, o)
default:
return nil, nil, ErrInvalidPath.Wrap(fmt.Errorf("expected key or index, got %s at %s", currentPart.Type, currentPath))
}
}
func getKeyBasedStructTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if interfaces.ImplementsInterface[KeyNavigable](sourceVal.Type()) {
val, stack, err := getNavigableWithKeyTarget(sourceVal, currentPart, stack, currentPath, o)
if err != nil {
if !errors.Is(err, ErrSkipInterface) {
return nil, nil, err
}
} else {
return val, stack, nil
}
}
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("struct is nil at %s", currentPath))
}
key := currentPart.unescapeValue()
sourceValElem := reflect.Indirect(sourceVal)
for i := 0; i < sourceValElem.NumField(); i++ {
field := sourceValElem.Type().Field(i)
if !field.IsExported() {
continue
}
fieldVal := sourceValElem.Field(i)
tags := []string{}
for _, tag := range o.StructTags {
if field.Tag.Get(tag) != "" {
tags = append(tags, field.Tag.Get(tag))
}
}
fieldKey := field.Name
if len(tags) > 0 {
fieldKey = tags[0]
}
if fieldKey == key {
return getCurrentStackTarget(fieldVal.Interface(), stack, currentPath, o)
}
}
// Field not found in struct fields, try searching the associated YAML node if available
// Check if the struct implements RootNodeAccessor interface (which has GetRootNode)
type rootNodeAccessor interface {
GetRootNode() *yaml.Node
}
if rootNodeAccessor, ok := sourceVal.Interface().(rootNodeAccessor); ok {
rootNode := rootNodeAccessor.GetRootNode()
if rootNode != nil {
// Use the existing YAML node navigation logic to search for the key
result, newStack, err := getYamlNodeTarget(rootNode, currentPart, stack, currentPath, o)
if err == nil {
return result, newStack, nil
}
}
}
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("key %s not found in %v at %s", key, sourceVal.Type(), currentPath))
}
func getIndexBasedStructTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if interfaces.ImplementsInterface[IndexNavigable](sourceVal.Type()) {
val, stack, err := getNavigableWithIndexTarget(sourceVal, currentPart, stack, currentPath, o)
if err != nil {
if errors.Is(err, ErrSkipInterface) {
return nil, nil, fmt.Errorf("can't navigate by index on %s at %s", sourceVal.Type(), currentPath)
}
return nil, nil, err
} else {
return val, stack, nil
}
} else {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("expected IndexNavigable, got %s at %s", sourceVal.Kind(), currentPath))
}
}
func getNavigableWithKeyTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("source is nil at %s", currentPath))
}
kn, ok := sourceVal.Interface().(KeyNavigable)
if !ok {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("expected keyNavigable, got %s at %s", sourceVal.Kind(), currentPath))
}
key := currentPart.unescapeValue()
value, err := kn.NavigateWithKey(key)
if err != nil {
return nil, nil, ErrNotFound.Wrap(err)
}
return getCurrentStackTarget(value, stack, currentPath, o)
}
func getNavigableWithIndexTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("source is nil at %s", currentPath))
}
kn, ok := sourceVal.Interface().(IndexNavigable)
if !ok {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("expected indexNavigable, got %s at %s", sourceVal.Kind(), currentPath))
}
index := currentPart.getIndex()
value, err := kn.NavigateWithIndex(index)
if err != nil {
return nil, nil, ErrNotFound.Wrap(err)
}
return getCurrentStackTarget(value, stack, currentPath, o)
}
func getNavigableNoderTarget(sourceVal reflect.Value, currentPart navigationPart, stack []navigationPart, currentPath string, o *options) (any, []navigationPart, error) {
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("source is nil at %s", currentPath))
}
nn, ok := sourceVal.Interface().(NavigableNoder)
if !ok {
return nil, nil, ErrNotFound.Wrap(fmt.Errorf("expected navigableNoder, got %s at %s", sourceVal.Kind(), currentPath))
}
value, err := nn.GetNavigableNode()
if err != nil {
return nil, nil, err
}
return getTarget(value, currentPart, stack, currentPath, o)
}
func buildPath(currentPath string, currentPart navigationPart) string {
if !strings.HasSuffix(currentPath, "/") {
currentPath += "/"
}
return currentPath + currentPart.Value
}
// EscapeString escapes a string for use as a reference token in a JSON pointer according to RFC6901.
// It replaces "~" with "~0" and "/" with "~1" as required by the specification.
// This function should be used when constructing JSON pointers from string values that may contain
// these special characters.
func EscapeString(s string) string {
return escape(s)
}
func escape(part string) string {
return strings.ReplaceAll(strings.ReplaceAll(part, "~", "~0"), "/", "~1")
}