-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathextract_refs.go
753 lines (666 loc) · 24.4 KB
/
extract_refs.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package index
import (
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"github.com/pb33f/libopenapi/utils"
"gopkg.in/yaml.v3"
)
// ExtractRefs will return a deduplicated slice of references for every unique ref found in the document.
// The total number of refs, will generally be much higher, you can extract those from GetRawReferenceCount()
func (index *SpecIndex) ExtractRefs(node, parent *yaml.Node, seenPath []string, level int, poly bool, pName string) []*Reference {
if node == nil {
return nil
}
var found []*Reference
if len(node.Content) > 0 {
var prev, polyName string
for i, n := range node.Content {
if utils.IsNodeMap(n) || utils.IsNodeArray(n) {
level++
// check if we're using polymorphic values. These tend to create rabbit warrens of circular
// references if every single link is followed. We don't resolve polymorphic values.
isPoly, _ := index.checkPolymorphicNode(prev)
polyName = pName
if isPoly {
poly = true
if prev != "" {
polyName = prev
}
}
found = append(found, index.ExtractRefs(n, node, seenPath, level, poly, polyName)...)
}
// check if we're dealing with an inline schema definition, that isn't part of an array
// (which means it's being used as a value in an array, and it's not a label)
// https://github.com/pb33f/libopenapi/issues/76
schemaContainingNodes := []string{"schema", "items", "additionalProperties", "contains", "not", "unevaluatedItems", "unevaluatedProperties"}
if i%2 == 0 && slices.Contains(schemaContainingNodes, n.Value) && !utils.IsNodeArray(node) && (i+1 < len(node.Content)) {
var jsonPath, definitionPath, fullDefinitionPath string
if len(seenPath) > 0 || n.Value != "" {
loc := append(seenPath, n.Value)
// create definition and full definition paths
definitionPath = fmt.Sprintf("#/%s", strings.Join(loc, "/"))
fullDefinitionPath = fmt.Sprintf("%s#/%s", index.specAbsolutePath, strings.Join(loc, "/"))
_, jsonPath = utils.ConvertComponentIdIntoFriendlyPathSearch(definitionPath)
}
ref := &Reference{
ParentNode: parent,
FullDefinition: fullDefinitionPath,
Definition: definitionPath,
Node: node.Content[i+1],
KeyNode: node.Content[i],
Path: jsonPath,
Index: index,
}
isRef, _, _ := utils.IsNodeRefValue(node.Content[i+1])
if isRef {
// record this reference
index.allRefSchemaDefinitions = append(index.allRefSchemaDefinitions, ref)
continue
}
if n.Value == "additionalProperties" || n.Value == "unevaluatedProperties" {
if utils.IsNodeBoolValue(node.Content[i+1]) {
continue
}
}
index.allInlineSchemaDefinitions = append(index.allInlineSchemaDefinitions, ref)
// check if the schema is an object or an array,
// and if so, add it to the list of inline schema object definitions.
k, v := utils.FindKeyNodeTop("type", node.Content[i+1].Content)
if k != nil && v != nil {
if v.Value == "object" || v.Value == "array" {
index.allInlineSchemaObjectDefinitions = append(index.allInlineSchemaObjectDefinitions, ref)
}
}
}
// Perform the same check for all maps of schemas like properties and patternProperties
// https://github.com/pb33f/libopenapi/issues/76
mapOfSchemaContainingNodes := []string{"properties", "patternProperties"}
if i%2 == 0 && slices.Contains(mapOfSchemaContainingNodes, n.Value) && !utils.IsNodeArray(node) && (i+1 < len(node.Content)) {
// if 'examples' or 'example' exists in the seenPath, skip this 'properties' node.
// https://github.com/pb33f/libopenapi/issues/160
if len(seenPath) > 0 {
skip := false
// iterate through the path and look for an item named 'examples' or 'example'
for _, p := range seenPath {
if p == "examples" || p == "example" {
skip = true
break
}
// look for any extension in the path and ignore it
if strings.HasPrefix(p, "x-") {
skip = true
break
}
}
if skip {
continue
}
}
// for each property add it to our schema definitions
label := ""
for h, prop := range node.Content[i+1].Content {
if h%2 == 0 {
label = prop.Value
continue
}
var jsonPath, definitionPath, fullDefinitionPath string
if len(seenPath) > 0 || n.Value != "" && label != "" {
loc := append(seenPath, n.Value, label)
definitionPath = fmt.Sprintf("#/%s", strings.Join(loc, "/"))
fullDefinitionPath = fmt.Sprintf("%s#/%s", index.specAbsolutePath, strings.Join(loc, "/"))
_, jsonPath = utils.ConvertComponentIdIntoFriendlyPathSearch(definitionPath)
}
ref := &Reference{
ParentNode: parent,
FullDefinition: fullDefinitionPath,
Definition: definitionPath,
Node: prop,
KeyNode: node.Content[i],
Path: jsonPath,
Index: index,
}
isRef, _, _ := utils.IsNodeRefValue(prop)
if isRef {
// record this reference
index.allRefSchemaDefinitions = append(index.allRefSchemaDefinitions, ref)
continue
}
index.allInlineSchemaDefinitions = append(index.allInlineSchemaDefinitions, ref)
// check if the schema is an object or an array,
// and if so, add it to the list of inline schema object definitions.
k, v := utils.FindKeyNodeTop("type", prop.Content)
if k != nil && v != nil {
if v.Value == "object" || v.Value == "array" {
index.allInlineSchemaObjectDefinitions = append(index.allInlineSchemaObjectDefinitions, ref)
}
}
}
}
// Perform the same check for all arrays of schemas like allOf, anyOf, oneOf
arrayOfSchemaContainingNodes := []string{"allOf", "anyOf", "oneOf", "prefixItems"}
if i%2 == 0 && slices.Contains(arrayOfSchemaContainingNodes, n.Value) && !utils.IsNodeArray(node) && (i+1 < len(node.Content)) {
// for each element in the array, add it to our schema definitions
for h, element := range node.Content[i+1].Content {
var jsonPath, definitionPath, fullDefinitionPath string
if len(seenPath) > 0 {
loc := append(seenPath, n.Value, fmt.Sprintf("%d", h))
definitionPath = fmt.Sprintf("#/%s", strings.Join(loc, "/"))
fullDefinitionPath = fmt.Sprintf("%s#/%s", index.specAbsolutePath, strings.Join(loc, "/"))
_, jsonPath = utils.ConvertComponentIdIntoFriendlyPathSearch(definitionPath)
} else {
definitionPath = fmt.Sprintf("#/%s", n.Value)
fullDefinitionPath = fmt.Sprintf("%s#/%s", index.specAbsolutePath, n.Value)
_, jsonPath = utils.ConvertComponentIdIntoFriendlyPathSearch(definitionPath)
}
ref := &Reference{
ParentNode: parent,
FullDefinition: fullDefinitionPath,
Definition: definitionPath,
Node: element,
KeyNode: node.Content[i],
Path: jsonPath,
Index: index,
}
isRef, _, _ := utils.IsNodeRefValue(element)
if isRef { // record this reference
index.allRefSchemaDefinitions = append(index.allRefSchemaDefinitions, ref)
continue
}
index.allInlineSchemaDefinitions = append(index.allInlineSchemaDefinitions, ref)
// check if the schema is an object or an array,
// and if so, add it to the list of inline schema object definitions.
k, v := utils.FindKeyNodeTop("type", element.Content)
if k != nil && v != nil {
if v.Value == "object" || v.Value == "array" {
index.allInlineSchemaObjectDefinitions = append(index.allInlineSchemaObjectDefinitions, ref)
}
}
}
}
if i%2 == 0 && n.Value == "$ref" {
// check if this reference is under an extension or not, if so, drop it from the index.
if index.config.ExcludeExtensionRefs {
ext := false
for _, spi := range seenPath {
if strings.HasPrefix(spi, "x-") {
ext = true
break
}
}
if ext {
continue
}
}
// only look at scalar values, not maps (looking at you k8s)
if len(node.Content) > i+1 {
if !utils.IsNodeStringValue(node.Content[i+1]) {
continue
}
// issue #481, don't look at refs in arrays, the next node isn't the value.
if utils.IsNodeArray(node) {
continue
}
}
index.linesWithRefs[n.Line] = true
fp := make([]string, len(seenPath))
copy(fp, seenPath)
if len(node.Content) > i+1 {
value := node.Content[i+1].Value
segs := strings.Split(value, "/")
name := segs[len(segs)-1]
uri := strings.Split(value, "#/")
// determine absolute path to this definition
var defRoot string
if strings.HasPrefix(index.specAbsolutePath, "http") {
defRoot = index.specAbsolutePath
} else {
defRoot = filepath.Dir(index.specAbsolutePath)
}
var componentName string
var fullDefinitionPath string
if len(uri) == 2 {
// Check if we are dealing with a ref to a local definition.
if uri[0] == "" {
fullDefinitionPath = fmt.Sprintf("%s#/%s", index.specAbsolutePath, uri[1])
componentName = value
} else {
if strings.HasPrefix(uri[0], "http") {
fullDefinitionPath = value
componentName = fmt.Sprintf("#/%s", uri[1])
} else {
if filepath.IsAbs(uri[0]) {
fullDefinitionPath = value
componentName = fmt.Sprintf("#/%s", uri[1])
} else {
// if the index has a base path, use that to resolve the path
if index.config.BasePath != "" && index.config.BaseURL == nil {
abs, _ := filepath.Abs(utils.CheckPathOverlap(index.config.BasePath, uri[0], string(os.PathSeparator)))
if abs != defRoot {
abs, _ = filepath.Abs(utils.CheckPathOverlap(defRoot, uri[0], string(os.PathSeparator)))
}
fullDefinitionPath = fmt.Sprintf("%s#/%s", abs, uri[1])
componentName = fmt.Sprintf("#/%s", uri[1])
} else {
// if the index has a base URL, use that to resolve the path.
if index.config.BaseURL != nil && !filepath.IsAbs(defRoot) {
var u url.URL
if strings.HasPrefix(defRoot, "http") {
up, _ := url.Parse(defRoot)
up.Path = utils.ReplaceWindowsDriveWithLinuxPath(filepath.Dir(up.Path))
u = *up
} else {
u = *index.config.BaseURL
}
// abs, _ := filepath.Abs(filepath.Join(u.Path, uri[0]))
// abs, _ := filepath.Abs(utils.CheckPathOverlap(u.Path, uri[0], string(os.PathSeparator)))
abs := utils.CheckPathOverlap(u.Path, uri[0], string(os.PathSeparator))
u.Path = utils.ReplaceWindowsDriveWithLinuxPath(abs)
fullDefinitionPath = fmt.Sprintf("%s#/%s", u.String(), uri[1])
componentName = fmt.Sprintf("#/%s", uri[1])
} else {
abs, _ := filepath.Abs(utils.CheckPathOverlap(defRoot, uri[0], string(os.PathSeparator)))
fullDefinitionPath = fmt.Sprintf("%s#/%s", abs, uri[1])
componentName = fmt.Sprintf("#/%s", uri[1])
}
}
}
}
}
} else {
if strings.HasPrefix(uri[0], "http") {
fullDefinitionPath = value
} else {
// is it a relative file include?
if !strings.Contains(uri[0], "#") {
if strings.HasPrefix(defRoot, "http") {
if !filepath.IsAbs(uri[0]) {
u, _ := url.Parse(defRoot)
pathDir := filepath.Dir(u.Path)
// pathAbs, _ := filepath.Abs(filepath.Join(pathDir, uri[0]))
pathAbs, _ := filepath.Abs(utils.CheckPathOverlap(pathDir, uri[0], string(os.PathSeparator)))
pathAbs = utils.ReplaceWindowsDriveWithLinuxPath(pathAbs)
u.Path = pathAbs
fullDefinitionPath = u.String()
}
} else {
if !filepath.IsAbs(uri[0]) {
// if the index has a base path, use that to resolve the path
if index.config.BasePath != "" {
abs, _ := filepath.Abs(utils.CheckPathOverlap(index.config.BasePath, uri[0], string(os.PathSeparator)))
if abs != defRoot {
abs, _ = filepath.Abs(utils.CheckPathOverlap(defRoot, uri[0], string(os.PathSeparator)))
}
fullDefinitionPath = abs
componentName = uri[0]
} else {
// if the index has a base URL, use that to resolve the path.
if index.config.BaseURL != nil {
u := *index.config.BaseURL
abs := utils.CheckPathOverlap(u.Path, uri[0], string(os.PathSeparator))
abs = utils.ReplaceWindowsDriveWithLinuxPath(abs)
u.Path = abs
fullDefinitionPath = u.String()
componentName = uri[0]
} else {
abs, _ := filepath.Abs(utils.CheckPathOverlap(defRoot, uri[0], string(os.PathSeparator)))
fullDefinitionPath = abs
componentName = uri[0]
}
}
}
}
}
}
}
_, p := utils.ConvertComponentIdIntoFriendlyPathSearch(componentName)
ref := &Reference{
ParentNode: parent,
FullDefinition: fullDefinitionPath,
Definition: componentName,
Name: name,
Node: node,
KeyNode: node.Content[i+1],
Path: p,
Index: index,
}
// add to raw sequenced refs
index.rawSequencedRefs = append(index.rawSequencedRefs, ref)
// add ref by line number
refNameIndex := strings.LastIndex(value, "/")
refName := value[refNameIndex+1:]
if len(index.refsByLine[refName]) > 0 {
index.refsByLine[refName][n.Line] = true
} else {
v := make(map[int]bool)
v[n.Line] = true
index.refsByLine[refName] = v
}
// if this ref value has any siblings (node.Content is larger than two elements)
// then add to refs with siblings
if len(node.Content) > 2 {
copiedNode := *node
copied := Reference{
ParentNode: parent,
FullDefinition: fullDefinitionPath,
Definition: ref.Definition,
Name: ref.Name,
Node: &copiedNode,
KeyNode: node.Content[i],
Path: p,
Index: index,
}
// protect this data using a copy, prevent the resolver from destroying things.
index.refsWithSiblings[value] = copied
}
// if this is a polymorphic reference, we're going to leave it out
// allRefs. We don't ever want these resolved, so instead of polluting
// the timeline, we will keep each poly ref in its own collection for later
// analysis.
if poly {
index.polymorphicRefs[value] = ref
// index each type
switch pName {
case "anyOf":
index.polymorphicAnyOfRefs = append(index.polymorphicAnyOfRefs, ref)
case "allOf":
index.polymorphicAllOfRefs = append(index.polymorphicAllOfRefs, ref)
case "oneOf":
index.polymorphicOneOfRefs = append(index.polymorphicOneOfRefs, ref)
}
continue
}
// check if this is a dupe, if so, skip it, we don't care now.
if index.allRefs[value] != nil { // seen before, skip.
continue
}
if value == "" {
completedPath := fmt.Sprintf("$.%s", strings.Join(fp, "."))
c := node.Content[i]
if len(node.Content) > i+1 { // if the next node exists, use that.
c = node.Content[i+1]
}
indexError := &IndexingError{
Err: errors.New("schema reference is empty and cannot be processed"),
Node: c,
KeyNode: node.Content[i],
Path: completedPath,
}
index.refErrors = append(index.refErrors, indexError)
continue
}
// This sets the ref in the path using the full URL and sub-path.
index.allRefs[fullDefinitionPath] = ref
found = append(found, ref)
}
}
if i%2 == 0 && n.Value != "$ref" && n.Value != "" {
v := n.Value
if strings.HasPrefix(v, "/") {
v = strings.Replace(v, "/", "~1", 1)
}
loc := append(seenPath, v)
definitionPath := fmt.Sprintf("#/%s", strings.Join(loc, "/"))
_, jsonPath := utils.ConvertComponentIdIntoFriendlyPathSearch(definitionPath)
// capture descriptions and summaries
if n.Value == "description" {
// if the parent is a sequence, ignore.
if utils.IsNodeArray(node) {
continue
}
if !slices.Contains(seenPath, "example") && !slices.Contains(seenPath, "examples") {
ref := &DescriptionReference{
ParentNode: parent,
Content: node.Content[i+1].Value,
Path: jsonPath,
Node: node.Content[i+1],
KeyNode: node.Content[i],
IsSummary: false,
}
if !utils.IsNodeMap(ref.Node) {
index.allDescriptions = append(index.allDescriptions, ref)
index.descriptionCount++
}
}
}
if n.Value == "summary" {
if slices.Contains(seenPath, "example") || slices.Contains(seenPath, "examples") {
continue
}
var b *yaml.Node
if len(node.Content) == i+1 {
b = node.Content[i]
} else {
b = node.Content[i+1]
}
ref := &DescriptionReference{
ParentNode: parent,
Content: b.Value,
Path: jsonPath,
Node: b,
KeyNode: n,
IsSummary: true,
}
index.allSummaries = append(index.allSummaries, ref)
index.summaryCount++
}
// capture security requirement references (these are not traditional references, but they
// are used as a look-up. This is the only exception to the design.
if n.Value == "security" {
var b *yaml.Node
if len(node.Content) == i+1 {
b = node.Content[i]
} else {
b = node.Content[i+1]
}
if utils.IsNodeArray(b) {
var secKey string
for k := range b.Content {
if utils.IsNodeMap(b.Content[k]) {
for g := range b.Content[k].Content {
if g%2 == 0 {
secKey = b.Content[k].Content[g].Value
continue
}
if utils.IsNodeArray(b.Content[k].Content[g]) {
var refMap map[string][]*Reference
if index.securityRequirementRefs[secKey] == nil {
index.securityRequirementRefs[secKey] = make(map[string][]*Reference)
refMap = index.securityRequirementRefs[secKey]
} else {
refMap = index.securityRequirementRefs[secKey]
}
for r := range b.Content[k].Content[g].Content {
var refs []*Reference
if refMap[b.Content[k].Content[g].Content[r].Value] != nil {
refs = refMap[b.Content[k].Content[g].Content[r].Value]
}
refs = append(refs, &Reference{
Definition: b.Content[k].Content[g].Content[r].Value,
Path: fmt.Sprintf("%s.security[%d].%s[%d]", jsonPath, k, secKey, r),
Node: b.Content[k].Content[g].Content[r],
KeyNode: b.Content[k].Content[g],
})
index.securityRequirementRefs[secKey][b.Content[k].Content[g].Content[r].Value] = refs
}
}
}
}
}
}
}
// capture enums
if n.Value == "enum" {
if len(seenPath) > 0 {
lastItem := seenPath[len(seenPath)-1]
if lastItem == "properties" {
seenPath = append(seenPath, strings.ReplaceAll(n.Value, "/", "~1"))
prev = n.Value
continue
}
}
// all enums need to have a type, extract the type from the node where the enum was found.
_, enumKeyValueNode := utils.FindKeyNodeTop("type", node.Content)
if enumKeyValueNode != nil {
ref := &EnumReference{
ParentNode: parent,
Path: jsonPath,
Node: node.Content[i+1],
KeyNode: node.Content[i],
Type: enumKeyValueNode,
SchemaNode: node,
}
index.allEnums = append(index.allEnums, ref)
index.enumCount++
}
}
// capture all objects with properties
if n.Value == "properties" {
_, typeKeyValueNode := utils.FindKeyNodeTop("type", node.Content)
if typeKeyValueNode != nil {
isObject := false
if typeKeyValueNode.Value == "object" {
isObject = true
}
for _, v := range typeKeyValueNode.Content {
if v.Value == "object" {
isObject = true
}
}
if isObject {
index.allObjectsWithProperties = append(index.allObjectsWithProperties, &ObjectReference{
Path: jsonPath,
Node: node,
KeyNode: n,
ParentNode: parent,
})
}
}
}
seenPath = append(seenPath, strings.ReplaceAll(n.Value, "/", "~1"))
// seenPath = append(seenPath, n.Value)
prev = n.Value
}
// if next node is map, don't add segment.
if i < len(node.Content)-1 {
next := node.Content[i+1]
if i%2 != 0 && next != nil && !utils.IsNodeArray(next) && !utils.IsNodeMap(next) && len(seenPath) > 0 {
seenPath = seenPath[:len(seenPath)-1]
}
}
}
}
index.refCount = len(index.allRefs)
return found
}
// ExtractComponentsFromRefs returns located components from references. The returned nodes from here
// can be used for resolving as they contain the actual object properties.
func (index *SpecIndex) ExtractComponentsFromRefs(refs []*Reference) []*Reference {
var found []*Reference
// run this async because when things get recursive, it can take a while
var c chan struct{}
if !index.config.ExtractRefsSequentially {
c = make(chan struct{})
}
locate := func(ref *Reference, refIndex int, sequence []*ReferenceMapped) {
index.refLock.Lock()
if index.allMappedRefs[ref.FullDefinition] != nil {
rm := &ReferenceMapped{
OriginalReference: ref,
Reference: index.allMappedRefs[ref.FullDefinition],
Definition: index.allMappedRefs[ref.FullDefinition].Definition,
FullDefinition: index.allMappedRefs[ref.FullDefinition].FullDefinition,
}
sequence[refIndex] = rm
if !index.config.ExtractRefsSequentially {
c <- struct{}{}
}
index.refLock.Unlock()
} else {
index.refLock.Unlock()
// If it's local, this is safe to do unlocked
uri := strings.Split(ref.FullDefinition, "#/")
unsafeAsync := len(uri) == 2 && len(uri[0]) > 0
if unsafeAsync {
index.refLock.Lock()
}
located := index.FindComponent(ref.FullDefinition)
if unsafeAsync {
index.refLock.Unlock()
}
if located != nil {
// key node is always going to be nil when mapping, yamlpath API returns
// subnodes only, so we need to rollback in the nodemap a line (if we can) to extract
// the keynode.
if located.Node != nil {
index.nodeMapLock.RLock()
if located.Node.Line > 1 && len(index.nodeMap[located.Node.Line-1]) > 0 {
for _, v := range index.nodeMap[located.Node.Line-1] {
located.KeyNode = v
break
}
}
index.nodeMapLock.RUnlock()
}
// have we already mapped this?
index.refLock.Lock()
if index.allMappedRefs[ref.FullDefinition] == nil {
found = append(found, located)
index.allMappedRefs[located.FullDefinition] = located
}
rm := &ReferenceMapped{
OriginalReference: ref,
Reference: located,
Definition: located.Definition,
FullDefinition: located.FullDefinition,
}
sequence[refIndex] = rm
index.refLock.Unlock()
} else {
_, path := utils.ConvertComponentIdIntoFriendlyPathSearch(ref.Definition)
indexError := &IndexingError{
Err: fmt.Errorf("component `%s` does not exist in the specification", ref.Definition),
Node: ref.Node,
Path: path,
KeyNode: ref.KeyNode,
}
index.errorLock.Lock()
index.refErrors = append(index.refErrors, indexError)
index.errorLock.Unlock()
}
if !index.config.ExtractRefsSequentially {
c <- struct{}{}
}
}
}
var refsToCheck []*Reference
refsToCheck = append(refsToCheck, refs...)
mappedRefsInSequence := make([]*ReferenceMapped, len(refsToCheck))
for r := range refsToCheck {
// expand our index of all mapped refs
if !index.config.ExtractRefsSequentially {
go locate(refsToCheck[r], r, mappedRefsInSequence) // run async
} else {
locate(refsToCheck[r], r, mappedRefsInSequence) // run synchronously
}
}
if !index.config.ExtractRefsSequentially {
completedRefs := 0
for completedRefs < len(refsToCheck) {
<-c
completedRefs++
}
}
for m := range mappedRefsInSequence {
if mappedRefsInSequence[m] != nil {
index.allMappedRefsSequenced = append(index.allMappedRefsSequenced, mappedRefsInSequence[m])
}
}
return found
}