-
Notifications
You must be signed in to change notification settings - Fork 5
/
util.go
76 lines (70 loc) · 1.93 KB
/
util.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
package vervet
import (
"bytes"
"encoding/json"
"fmt"
"io/fs"
"github.com/getkin/kin-openapi/openapi3"
"github.com/ghodss/yaml"
)
// ToSpecJSON renders an OpenAPI document object as JSON.
func ToSpecJSON(v interface{}) ([]byte, error) {
return json.MarshalIndent(v, "", " ")
}
// ToSpecYAML renders an OpenAPI document object as YAML.
func ToSpecYAML(v interface{}) ([]byte, error) {
jsonBuf, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %w", err)
}
yamlBuf, err := yaml.JSONToYAML(jsonBuf)
if err != nil {
return nil, fmt.Errorf("failed to marshal YAML: %w", err)
}
return WithGeneratedComment(yamlBuf)
}
// WithGeneratedComment prepends a comment to YAML output indicating the file
// was generated.
func WithGeneratedComment(yamlBuf []byte) ([]byte, error) {
var buf bytes.Buffer
_, err := fmt.Fprintf(&buf, "# OpenAPI spec generated by vervet, DO NOT EDIT\n")
if err != nil {
return nil, fmt.Errorf("failed to write output: %w", err)
}
_, err = buf.Write(yamlBuf)
if err != nil {
return nil, fmt.Errorf("failed to write output: %w", err)
}
return buf.Bytes(), nil
}
// LoadVersions loads all Vervet-compiled and versioned API specs from a
// filesystem root and returns them.
func LoadVersions(root fs.FS) ([]*openapi3.T, error) {
versions := []*openapi3.T{}
specFiles, err := fs.Glob(root, "*/spec.json")
if err != nil {
return nil, err
}
for _, specFile := range specFiles {
specData, err := fs.ReadFile(root, specFile)
if err != nil {
return nil, err
}
l := openapi3.NewLoader()
t, err := l.LoadFromData(specData)
if err != nil {
return nil, err
}
if _, err := ExtensionString(t.Extensions, ExtSnykApiVersion); IsExtensionNotFound(err) {
// Not a versioned OpenAPI spec, skip it
continue
} else if err != nil {
return nil, err
}
versions = append(versions, t)
}
if len(versions) == 0 {
return nil, ErrNoMatchingVersion
}
return versions, nil
}