-
Notifications
You must be signed in to change notification settings - Fork 3
/
loader.go
359 lines (308 loc) · 7.86 KB
/
loader.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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)
const (
defaultVersionNumber = 0
defaultPackageName = "sonarqube_client"
serviceSuffix = "Service"
requestSuffix = "Request"
responseSuffix = "Response"
urlPrefix = "api/"
fileExt = ".go"
webservicesUrl = "/api/webservices/list"
includeInternalUrl = "?include_internals=true"
serverVersionUrl = "/api/server/version"
defaultVersionString = "0.0"
)
type version struct {
major byte
minor byte
str string
}
func newVersion(s string) *version {
v := &version{}
if strings.TrimSpace(s) == "" {
s = defaultVersionString
}
v.UnmarshalJSON([]byte(s))
return v
}
func (v *version) String() string {
return v.str
}
func (v *version) UnmarshalJSON(raw []byte) error {
v.str = strings.Trim(string(raw), "\"")
seg := strings.Split(v.str, ".")
major, err := strconv.ParseInt(seg[0], 10, 8)
if err != nil {
return fmt.Errorf("failed to pars major version, str - %v:%w", v.str, err)
}
v.major = byte(major)
if len(seg) >= 2 {
minor, err := strconv.ParseInt(seg[1], 10, 8)
if err != nil {
return fmt.Errorf("failed to pars minor version, str - %v:%w", v.str, err)
}
v.minor = byte(minor)
} else {
v.minor = defaultVersionNumber
}
return nil
}
func (v *version) lessOrEqual(ov *version) bool {
switch {
case v.major > ov.major:
// 3.3, 2.2 => false
return false
case v.major < ov.major:
// 1.1, 2.2 => true
return true
case v.minor > ov.minor:
// 1.3, 1.2 => false
return false
case v.minor < ov.minor:
// 1.1, 1.2 => true
return true
default:
// 1.1, 1.1 => false
return true
}
}
func (v *version) greater(ov *version) bool {
return !v.lessOrEqual(ov)
}
func (v *version) isSet() bool {
return v.major != defaultVersionNumber && v.minor != defaultVersionNumber
}
type apiDefinition struct {
Host string
PackageName string
Version *version
WebServices []*webService
}
func (ad *apiDefinition) ensurePackageName() {
if ad.PackageName == "" {
ad.PackageName = defaultPackageName
}
}
type webService struct {
PackageName string
Path string
Since version
Description string
Actions []*action
}
func (ws *webService) Internal() bool {
for _, action := range ws.Actions {
if !action.Internal {
return false
}
}
return true
}
func (ws *webService) Deprecated() bool {
for _, action := range ws.Actions {
if !action.DeprecatedSince.isSet() {
return false
}
}
return true
}
func (ws *webService) ServiceName() string {
return ws.Getter() + serviceSuffix
}
func (ws *webService) Variable() string {
return makeUnexported(ws.ServiceName())
}
func (ws *webService) Getter() string {
name := strings.TrimPrefix(ws.Path, urlPrefix)
return makeExported(snakeToCamel(name))
}
func (ws *webService) fileName() string {
return strings.TrimPrefix(ws.Path, urlPrefix) + fileExt
}
type action struct {
ServiceName string
Key string
Description string
Since version
Internal bool
Post bool
HasResponseExample bool
DeprecatedSince version
Changelog []*change
Params []*param
}
func (a *action) MethodName() string {
return makeExported(snakeToCamel(a.Key))
}
func (a *action) RequestTypeName() string {
return a.ServiceName + a.MethodName() + requestSuffix
}
func (a *action) ResponseTypeName() string {
return a.ServiceName + a.MethodName() + responseSuffix
}
func (a *action) Deprecated() bool {
return a.DeprecatedSince.isSet()
}
type change struct {
Description string
Version string
}
func (c *change) String() string {
return c.Version + ": " + strings.ReplaceAll(c.Description, "\n", "")
}
type param struct {
Key string
Since version
Description string
Required bool
Internal bool
ExampleValue string
DeprecatedSince version
PossibleValues []string
DeprecatedKey string
DeprecatedKeySince version
DefaultValue string
MaximumValue int
MinimumLength int
MaximumLength int
MaxValuesAllowed int
}
func (p *param) ParamName() string {
return formatFieldName(makeExported(snakeToCamel(sanitizeItentifier(p.Key))))
}
func (p *param) Deprecated() bool {
return p.DeprecatedSince.isSet()
}
type filter struct {
internal bool
deprecated bool
version *version
}
func url(host string, internal bool) string {
link := host + webservicesUrl
if internal {
link += includeInternalUrl
}
return link
}
func getTargetVersion(client *http.Client, host, version string) (string, error) {
if version != "" {
return version, nil
}
resp, err := client.Get(host + serverVersionUrl)
if err != nil {
return "", fmt.Errorf("failed to fetch server version:%w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("got error response from the server, code - %d:%w", resp.StatusCode, err)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to fetch server version:%w", err)
}
version = buf.String()
return version, nil
}
func getDefinition(client *http.Client, host string, auth string, internal bool, version *version) (*apiDefinition, error) {
req, _ := http.NewRequest("GET", url(host, internal), nil)
if auth != "" {
req.Header.Set("Authorization", auth)
}
resp, err := client.Do(req)
if resp.StatusCode == 401 {
return nil, errors.New("authorization failed to fetch api definitions")
}
// resp, err := client.Get(url(host, internal))
if err != nil {
return nil, fmt.Errorf("failed to fetch api definitions:%w", err)
}
defer resp.Body.Close()
def := &apiDefinition{
PackageName: packageName,
Host: host,
Version: version,
}
dec := json.NewDecoder(resp.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(def); err != nil {
return nil, fmt.Errorf("failed to decode response:%w", err)
}
def.ensurePackageName()
for _, service := range def.WebServices {
service.PackageName = def.PackageName
for _, action := range service.Actions {
action.ServiceName = service.ServiceName()
}
}
return def, nil
}
func filterParams(params []*param, f *filter) []*param {
result := make([]*param, 0, len(params))
for _, p := range params {
if !f.deprecated && p.Deprecated() ||
!f.internal && p.Internal ||
p.Since.greater(f.version) {
continue
}
result = append(result, p)
}
return result
}
func filterActions(actions []*action, f *filter) []*action {
result := make([]*action, 0, len(actions))
for _, action := range actions {
if !f.deprecated && action.Deprecated() ||
!f.internal && action.Internal ||
action.Since.greater(f.version) {
continue
}
action.Params = filterParams(action.Params, f)
result = append(result, action)
}
return result
}
func filterDefinition(def *apiDefinition, f *filter) *apiDefinition {
wss := make([]*webService, 0, len(def.WebServices))
for _, ws := range def.WebServices {
if !f.deprecated && ws.Deprecated() ||
!f.internal && ws.Internal() ||
ws.Since.greater(f.version) {
continue
}
ws.Actions = filterActions(ws.Actions, f)
wss = append(wss, ws)
}
def.WebServices = wss
return def
}
func loadAPI(client *http.Client, host string, deprecated bool, internal bool, version string, auth string) (*apiDefinition, error) {
if client == nil {
client = http.DefaultClient
}
version, err := getTargetVersion(client, host, version)
if err != nil {
return nil, fmt.Errorf("failed to resolve target version:%w", err)
}
parsedVersion := newVersion(version)
def, err := getDefinition(client, host, auth, internal, parsedVersion)
if err != nil {
return nil, fmt.Errorf("failed to load definition:%w", err)
}
filterDefinition(def, &filter{
deprecated: deprecated,
internal: internal,
version: parsedVersion,
})
return def, nil
}