forked from gptscript-ai/gptscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload.go
121 lines (103 loc) · 2.47 KB
/
load.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
package openapi
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"github.com/getkin/kin-openapi/openapi2"
"github.com/getkin/kin-openapi/openapi2conv"
"github.com/getkin/kin-openapi/openapi3"
"gopkg.in/yaml.v3"
kyaml "sigs.k8s.io/yaml"
)
func Load(source string) (*openapi3.T, error) {
if strings.HasPrefix(source, "http://") || strings.HasPrefix(source, "https://") {
return loadFromURL(source)
}
return loadFromFile(source)
}
func loadFromURL(source string) (*openapi3.T, error) {
resp, err := http.DefaultClient.Get(source)
if err != nil {
return nil, err
}
defer resp.Body.Close()
contents, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return LoadFromBytes(contents)
}
func loadFromFile(source string) (*openapi3.T, error) {
contents, err := os.ReadFile(source)
if err != nil {
return nil, err
}
return LoadFromBytes(contents)
}
func LoadFromBytes(content []byte) (*openapi3.T, error) {
var (
openAPIDocument *openapi3.T
err error
)
switch IsOpenAPI(content) {
case 2:
// Convert OpenAPI v2 to v3
if !json.Valid(content) {
content, err = kyaml.YAMLToJSON(content)
if err != nil {
return nil, err
}
}
doc := &openapi2.T{}
if err := doc.UnmarshalJSON(content); err != nil {
return nil, fmt.Errorf("failed to unmarshal OpenAPI v2 document: %w", err)
}
openAPIDocument, err = openapi2conv.ToV3(doc)
if err != nil {
return nil, fmt.Errorf("failed to convert OpenAPI v2 to v3: %w", err)
}
case 3:
openAPIDocument, err = openapi3.NewLoader().LoadFromData(content)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported OpenAPI version")
}
return openAPIDocument, nil
}
// IsOpenAPI checks if the data is an OpenAPI definition and returns the version if it is.
func IsOpenAPI(data []byte) int {
var fragment struct {
Paths map[string]any `json:"paths,omitempty"`
Swagger string `json:"swagger,omitempty"`
OpenAPI string `json:"openapi,omitempty"`
}
if err := json.Unmarshal(data, &fragment); err != nil {
if err := yaml.Unmarshal(data, &fragment); err != nil {
return 0
}
}
if len(fragment.Paths) == 0 {
return 0
}
if v, _, _ := strings.Cut(fragment.OpenAPI, "."); v != "" {
ver, err := strconv.Atoi(v)
if err != nil {
return 0
}
return ver
}
if v, _, _ := strings.Cut(fragment.Swagger, "."); v != "" {
ver, err := strconv.Atoi(v)
if err != nil {
return 0
}
return ver
}
return 0
}