-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathopenapi2jsonschema.go
More file actions
405 lines (377 loc) · 9.45 KB
/
Copy pathopenapi2jsonschema.go
File metadata and controls
405 lines (377 loc) · 9.45 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
// Derived from https://github.com/instrumenta/openapi2jsonschema
// Go port of openapi2jsonschema.py.
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// OrderedMap preserves key insertion order, matching Python dict semantics
// (insertion-ordered) used by PyYAML SafeLoader and json.dumps.
type OrderedMap struct {
keys []string
values map[string]any
}
func NewOrderedMap() *OrderedMap {
return &OrderedMap{values: map[string]any{}}
}
func (m *OrderedMap) Has(k string) bool {
_, ok := m.values[k]
return ok
}
func (m *OrderedMap) Get(k string) (any, bool) {
v, ok := m.values[k]
return v, ok
}
func (m *OrderedMap) Set(k string, v any) {
if _, ok := m.values[k]; !ok {
m.keys = append(m.keys, k)
}
m.values[k] = v
}
func (m *OrderedMap) Keys() []string { return m.keys }
func (m *OrderedMap) Len() int { return len(m.keys) }
// MarshalJSON emits keys in insertion order with no HTML escaping, matching
// Python's json.dumps default.
func (m *OrderedMap) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteByte('{')
for i, k := range m.keys {
if i > 0 {
buf.WriteByte(',')
}
kb, err := encodeJSON(k)
if err != nil {
return nil, err
}
buf.Write(kb)
buf.WriteByte(':')
vb, err := encodeJSON(m.values[k])
if err != nil {
return nil, err
}
buf.Write(vb)
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
func encodeJSON(v any) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
// Encoder always appends a trailing newline; strip it.
out := buf.Bytes()
if n := len(out); n > 0 && out[n-1] == '\n' {
out = out[:n-1]
}
return out, nil
}
// yamlToData converts a yaml.Node into Go values made of *OrderedMap, []any,
// and primitive types, preserving mapping key order.
func yamlToData(n *yaml.Node) (any, error) {
switch n.Kind {
case yaml.DocumentNode:
if len(n.Content) == 0 {
return nil, nil
}
return yamlToData(n.Content[0])
case yaml.MappingNode:
m := NewOrderedMap()
for i := 0; i < len(n.Content); i += 2 {
kNode := n.Content[i]
vNode := n.Content[i+1]
var key string
if err := kNode.Decode(&key); err != nil {
key = kNode.Value
}
v, err := yamlToData(vNode)
if err != nil {
return nil, err
}
m.Set(key, v)
}
return m, nil
case yaml.SequenceNode:
out := make([]any, 0, len(n.Content))
for _, c := range n.Content {
v, err := yamlToData(c)
if err != nil {
return nil, err
}
out = append(out, v)
}
return out, nil
case yaml.ScalarNode:
// Decode preserves YAML scalar typing (bool, int, float, string, null).
var v any
if err := n.Decode(&v); err != nil {
return nil, err
}
return v, nil
case yaml.AliasNode:
return yamlToData(n.Alias)
}
return nil, nil
}
// additionalProperties recreates the kubectl behaviour: any object with a
// "properties" key gets `additionalProperties: false` set (unless the caller
// asks to skip it for the root).
func additionalProperties(data any, skip bool) any {
m, ok := data.(*OrderedMap)
if !ok {
if list, ok := data.([]any); ok {
for i := range list {
list[i] = additionalProperties(list[i], false)
}
}
return data
}
if m.Has("properties") && !skip {
if !m.Has("additionalProperties") {
m.Set("additionalProperties", false)
}
}
for _, k := range m.Keys() {
v, _ := m.Get(k)
m.Set(k, additionalProperties(v, false))
}
return m
}
// replaceIntOrString replaces `format: int-or-string` with the canonical
// oneOf{string,integer} expansion.
func replaceIntOrString(data any) any {
m, ok := data.(*OrderedMap)
if !ok {
if list, ok := data.([]any); ok {
out := make([]any, len(list))
for i, x := range list {
out[i] = replaceIntOrString(x)
}
return out
}
return data
}
out := NewOrderedMap()
for _, k := range m.Keys() {
v, _ := m.Get(k)
switch vv := v.(type) {
case *OrderedMap:
if f, ok := vv.Get("format"); ok {
if s, ok := f.(string); ok && s == "int-or-string" {
replacement := NewOrderedMap()
strType := NewOrderedMap()
strType.Set("type", "string")
intType := NewOrderedMap()
intType.Set("type", "integer")
replacement.Set("oneOf", []any{strType, intType})
out.Set(k, replacement)
continue
}
}
out.Set(k, replaceIntOrString(vv))
case []any:
rep := make([]any, len(vv))
for i, x := range vv {
rep[i] = replaceIntOrString(x)
}
out.Set(k, rep)
default:
out.Set(k, v)
}
}
return out
}
func writeSchemaFile(schema any, filename string, denyRootAdditionalProperties bool) error {
schema = additionalProperties(schema, !denyRootAdditionalProperties)
schema = replaceIntOrString(schema)
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(schema); err != nil {
return err
}
// Encoder appends "\n"; Python's `print(s, file=f)` also appends one.
// json.dumps itself does not, so the encoder's newline matches print().
// Treat the input as a path component only — guard against directory
// traversal in user-supplied filenames.
filename = filepath.Base(filename)
if err := os.WriteFile(filename, buf.Bytes(), 0o644); err != nil {
return err
}
fmt.Printf("JSON schema written to %s\n", filename)
return nil
}
func formatFilename(format, kind, group, fullgroup, version string) string {
r := strings.NewReplacer(
"{kind}", kind,
"{group}", group,
"{fullgroup}", fullgroup,
"{version}", version,
)
return strings.ToLower(r.Replace(format)) + ".json"
}
func openInput(path string) (io.ReadCloser, error) {
if strings.HasPrefix(path, "http") {
client := http.DefaultClient
if os.Getenv("DISABLE_SSL_CERT_VALIDATION") != "" {
client = &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}}
}
resp, err := client.Get(path)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
resp.Body.Close()
return nil, fmt.Errorf("HTTP %d fetching %s", resp.StatusCode, path)
}
return resp.Body, nil
}
return os.Open(path)
}
// process consumes one CRD source (file or URL) and writes one JSON schema per
// version found, mirroring the original Python control flow.
func process(path string, filenameFormat string, denyRoot bool) error {
r, err := openInput(path)
if err != nil {
return err
}
defer r.Close()
dec := yaml.NewDecoder(r)
var defs []*OrderedMap
for {
var node yaml.Node
if err := dec.Decode(&node); err != nil {
if err == io.EOF {
break
}
return err
}
v, err := yamlToData(&node)
if err != nil {
return err
}
m, ok := v.(*OrderedMap)
if !ok || m == nil {
continue
}
if items, ok := m.Get("items"); ok {
if list, ok := items.([]any); ok {
for _, it := range list {
if im, ok := it.(*OrderedMap); ok {
defs = append(defs, im)
}
}
}
}
kind, ok := m.Get("kind")
if !ok {
continue
}
if ks, _ := kind.(string); ks != "CustomResourceDefinition" {
continue
}
defs = append(defs, m)
}
for _, y := range defs {
spec, ok := getMap(y, "spec")
if !ok {
continue
}
names, _ := getMap(spec, "names")
kind, _ := getString(names, "kind")
fullgroup, _ := getString(spec, "group")
group := strings.SplitN(fullgroup, ".", 2)[0]
versions, hasVersions := spec.Get("versions")
versionList, _ := versions.([]any)
if hasVersions && len(versionList) > 0 {
for _, vAny := range versionList {
vMap, ok := vAny.(*OrderedMap)
if !ok {
continue
}
vName, _ := getString(vMap, "name")
schemaMap, hasSchema := getMap(vMap, "schema")
if hasSchema {
if root, ok := schemaMap.Get("openAPIV3Schema"); ok {
filename := formatFilename(filenameFormat, kind, group, fullgroup, vName)
if err := writeSchemaFile(root, filename, denyRoot); err != nil {
return err
}
continue
}
}
validation, hasValidation := getMap(spec, "validation")
if hasValidation {
if root, ok := validation.Get("openAPIV3Schema"); ok {
filename := formatFilename(filenameFormat, kind, group, fullgroup, vName)
if err := writeSchemaFile(root, filename, denyRoot); err != nil {
return err
}
}
}
}
} else if validation, hasValidation := getMap(spec, "validation"); hasValidation {
if root, ok := validation.Get("openAPIV3Schema"); ok {
vName, _ := getString(spec, "version")
filename := formatFilename(filenameFormat, kind, group, fullgroup, vName)
if err := writeSchemaFile(root, filename, denyRoot); err != nil {
return err
}
}
}
}
return nil
}
func getMap(m *OrderedMap, key string) (*OrderedMap, bool) {
if m == nil {
return nil, false
}
v, ok := m.Get(key)
if !ok {
return nil, false
}
mm, ok := v.(*OrderedMap)
return mm, ok
}
func getString(m *OrderedMap, key string) (string, bool) {
if m == nil {
return "", false
}
v, ok := m.Get(key)
if !ok {
return "", false
}
s, ok := v.(string)
return s, ok
}
func main() {
if len(os.Args) < 2 {
fmt.Printf("Missing FILE parameter.\nUsage: %s [FILE]\n", os.Args[0])
os.Exit(1)
}
filenameFormat := os.Getenv("FILENAME_FORMAT")
if filenameFormat == "" {
filenameFormat = "{kind}_{version}"
}
denyRoot := os.Getenv("DENY_ROOT_ADDITIONAL_PROPERTIES") != ""
for _, arg := range os.Args[1:] {
if err := process(arg, filenameFormat, denyRoot); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
os.Exit(0)
}