-
Notifications
You must be signed in to change notification settings - Fork 54
/
spec_info.go
110 lines (92 loc) · 2.35 KB
/
spec_info.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
package load
import (
"errors"
"fmt"
"net/url"
"github.com/getkin/kin-openapi/openapi3"
"github.com/yargevad/filepathx"
)
// SpecInfo contains information about an OpenAPI spec and its metadata
type SpecInfo struct {
Url string
Spec *openapi3.T
Version string
}
func (specInfo *SpecInfo) GetVersion() string {
if specInfo == nil || specInfo.Version == "" {
return "n/a"
}
return specInfo.Version
}
func newSpecInfo(spec *openapi3.T, path string) *SpecInfo {
return &SpecInfo{
Spec: spec,
Url: path,
Version: getVersion(spec),
}
}
func getVersion(spec *openapi3.T) string {
if spec == nil || spec.Info == nil {
return ""
}
return spec.Info.Version
}
// NewSpecInfo creates a SpecInfo from a local file path, a URL, or stdin
func NewSpecInfo(loader Loader, source *Source, options ...Option) (*SpecInfo, error) {
specInfo, err := loadSpecInfo(loader, source)
if err != nil {
return nil, err
}
specInfos := []*SpecInfo{specInfo}
for _, option := range options {
if specInfos, err = option(loader, specInfos); err != nil {
return nil, err
}
}
return specInfos[0], nil
}
// NewSpecInfoFromGlob creates SpecInfos from local files matching the specified glob parameter
func NewSpecInfoFromGlob(loader Loader, glob string, options ...Option) ([]*SpecInfo, error) {
specInfos, err := fromGlob(loader, glob)
if err != nil {
return nil, err
}
for _, option := range options {
if specInfos, err = option(loader, specInfos); err != nil {
return nil, err
}
}
return specInfos, nil
}
func loadSpecInfo(loader Loader, source *Source) (*SpecInfo, error) {
s, err := from(loader, source)
if err != nil {
return nil, err
}
return newSpecInfo(s, source.Path), nil
}
func fromGlob(loader Loader, glob string) ([]*SpecInfo, error) {
files, err := filepathx.Glob(glob)
if err != nil {
return nil, err
}
result := make([]*SpecInfo, 0)
for _, file := range files {
spec, err := loader.LoadFromFile(file)
if err != nil {
return nil, fmt.Errorf("failed to load %q: %w", file, err)
}
result = append(result, &SpecInfo{Url: file, Spec: spec})
}
if len(result) > 0 {
return result, nil
}
if isUrl(glob) {
return nil, errors.New("no matching files (should be a glob, not a URL)")
}
return nil, errors.New("no matching files")
}
func isUrl(spec string) bool {
_, err := url.ParseRequestURI(spec)
return err == nil
}