-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathunused.go
168 lines (150 loc) · 4.72 KB
/
unused.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
package main
import (
"errors"
"fmt"
"strings"
"github.com/dolmen-go/jsonptr"
)
func removeEmptyObject(rdoc *interface{}, pointer string) {
ptr, err := jsonptr.Parse(pointer)
if err != nil {
panic(fmt.Errorf("%s: %v", pointer, err))
}
parentRaw, err := ptr[:len(ptr)-1].In(*rdoc)
if err != nil {
return
}
parent, isObj := parentRaw.(map[string]interface{})
if !isObj || len(parent) == 0 {
return
}
key := ptr[len(ptr)-1]
obj, isObj := parent[key].(map[string]interface{})
if isObj && len(obj) == 0 {
delete(parent, key)
}
}
// CleanUnused checks references to global components and removes unreferenced components.
//
// This is an important step after ExpandRefs as some components referenced through $inline
// or $merge have been injected and are not needed anymore.
func CleanUnused(rdoc *interface{}) error {
root, isObj := (*rdoc).(map[string]interface{})
if !isObj {
return errors.New("root is not an object")
}
if paths, hasPaths := root["paths"]; hasPaths {
var components []string
if _, hasSwaggerVersion := stringProp(root, "swagger"); hasSwaggerVersion {
// TODO check version value (must be "2.0")
components = []string{`/definitions`, `/parameters`, `/responses`}
}
if _, hasOpenAPIVersion := stringProp(root, "openapi"); hasOpenAPIVersion {
components = []string{
`/components/schemas`,
`/components/parameters`,
`/components/responses`,
`/components/examples`,
`/components/requestBodies`,
`/components/headers`,
`/components/securitySchemes`,
`/components/links`,
`/components/callbacks`,
}
}
// Collect all defined components.
unused := make(map[string]bool)
for _, p := range components {
compRaw, err := jsonptr.Get(root, p)
if err != nil {
continue
}
comp, compObj := compRaw.(map[string]interface{})
if !compObj {
continue
}
for k := range comp {
unused[p+"/"+jsonptr.EscapeString(k)] = true
}
}
visited := make(map[string]bool)
var visitor func(ptr jsonptr.Pointer, ref string) (string, error)
visitor = func(ptr jsonptr.Pointer, ref string) (string, error) {
// Assumptions (ensured by ExpandRefs):
// - all $ref have been resolved to internal links
// - all $ref have been checked to not be circular
if ref[0] != '#' {
return ref, fmt.Errorf("%s: unexpected $ref %q", ptr, ref)
}
link := ref[1:]
// log.Println(ptr, "=>", link)
if visited[link] {
return ref, nil
}
if unused[link] {
// log.Println("seen", link)
delete(unused, link)
}
visited[link] = true
targetPtr, err := jsonptr.Parse(link)
if err != nil {
return ref, err
}
targetPtr.Grow(20)
target, err := targetPtr.In(root)
if err != nil { // should not happen if
return ref, fmt.Errorf("%v -> %v: %v", ptr, link, err)
}
return ref, visitRefs(target, targetPtr, visitor)
}
// Visit paths to detect components which are used
err := visitRefs(paths, append(make(jsonptr.Pointer, 0, 50), "paths"), visitor)
if err != nil {
return err
}
// If there are securitySchemes components, look for references.
if secSchemesAny, err := jsonptr.Get(*rdoc, `/components/securitySchemes`); err == nil {
if secSchemes, isObj := secSchemesAny.(map[string]any); isObj && len(secSchemes) > 0 {
markUsedSecuritySchemes := func(ptr string, doc map[string]any) {
for _, req := range iterSecurity(ptr, doc) {
// https://spec.openapis.org/oas/v3.1.1.html#security-requirement-object
for name := range req {
// fmt.Println("used: " + `/components/securitySchemes/` + jsonptr.EscapeString(name))
// TODO: signal if the securityScheme is not present in /components/securitySchemes
delete(unused, `/components/securitySchemes/`+jsonptr.EscapeString(name))
}
}
}
markUsedSecuritySchemes(``, root) // process /security
// https://spec.openapis.org/oas/v3.1.1.html#operation-object
for ptr, op := range iterOperations(root) {
markUsedSecuritySchemes(ptr, op) // process /paths/<path>/<method>/security
}
}
}
nextUnused:
for p := range unused {
// Look for deep references in unused schemas
prefix := p + "/"
for v := range visited {
if strings.HasPrefix(v, prefix) {
continue nextUnused
}
}
// log.Printf("%s: unused", p)
_, err = jsonptr.Delete(rdoc, p)
if err != nil {
panic("This should not happen")
}
}
}
removeEmptyObject(rdoc, `/components/schemas`)
removeEmptyObject(rdoc, `/components/parameters`)
removeEmptyObject(rdoc, `/components/responses`)
removeEmptyObject(rdoc, `/components/securitySchemes`)
removeEmptyObject(rdoc, `/components`)
removeEmptyObject(rdoc, `/definitions`)
removeEmptyObject(rdoc, `/parameters`)
removeEmptyObject(rdoc, `/responses`)
return nil
}