-
Notifications
You must be signed in to change notification settings - Fork 5
/
ref_alias_resolver.go
100 lines (81 loc) · 2.5 KB
/
ref_alias_resolver.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
package vervet
import (
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/snyk/vervet/v8/internal/openapiwalker"
)
// refAliasResolver rewrites references in an OpenAPI document object to local
// references, so that the spec is self-contained.
type refAliasResolver struct {
doc *openapi3.T
refAliases map[string]string
}
func (l *refAliasResolver) ProcessCallbackRef(ref *openapi3.CallbackRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessExampleRef(ref *openapi3.ExampleRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessHeaderRef(ref *openapi3.HeaderRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessLinkRef(ref *openapi3.LinkRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessParameterRef(ref *openapi3.ParameterRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessRequestBodyRef(ref *openapi3.RequestBodyRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessResponseRef(ref *openapi3.ResponseRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessSchemaRef(ref *openapi3.SchemaRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
func (l *refAliasResolver) ProcessSecuritySchemeRef(ref *openapi3.SecuritySchemeRef) error {
ref.Ref = l.resolveRefAlias(ref.Ref)
return nil
}
// newRefAliasResolver returns a new refAliasResolver.
func newRefAliasResolver(doc *openapi3.T) *refAliasResolver {
res := &refAliasResolver{doc: doc}
if doc.Components == nil {
return res
}
res.refAliases = make(map[string]string, len(doc.Components.Extensions))
for refAlias, extValue := range doc.Components.Extensions {
contents, ok := extValue.(map[string]interface{})
if !ok {
continue
}
ref, ok := contents["$ref"].(string)
if ok && ref != "" {
res.refAliases["#/components/"+refAlias] = ref
}
}
return res
}
func (l *refAliasResolver) resolveRefAlias(ref string) string {
if ref != "" && ref[0] == '#' {
for refAlias, refTarget := range l.refAliases {
if strings.HasPrefix(ref, refAlias) {
return strings.Replace(ref, refAlias, refTarget+"#", 1)
}
}
}
return ref
}
// resolve rewrites all references in the OpenAPI document to local references.
func (l *refAliasResolver) resolve() error {
return openapiwalker.ProcessRefs(l.doc, l)
}