forked from go-openapi/codescan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparameters.go
More file actions
627 lines (526 loc) · 17.8 KB
/
parameters.go
File metadata and controls
627 lines (526 loc) · 17.8 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0
package codescan
import (
"fmt"
"go/types"
"strings"
"github.com/go-openapi/spec"
)
type paramTypable struct {
param *spec.Parameter
skipExt bool
}
func (pt paramTypable) In() string { return pt.param.In }
func (pt paramTypable) Level() int { return 0 }
func (pt paramTypable) Typed(tpe, format string) {
pt.param.Typed(tpe, format)
}
func (pt paramTypable) SetRef(ref spec.Ref) {
pt.param.Ref = ref
}
func (pt paramTypable) Items() swaggerTypable { //nolint:ireturn // polymorphic by design
bdt, schema := bodyTypable(pt.param.In, pt.param.Schema, pt.skipExt)
if bdt != nil {
pt.param.Schema = schema
return bdt
}
if pt.param.Items == nil {
pt.param.Items = new(spec.Items)
}
pt.param.Type = typeArray
return itemsTypable{pt.param.Items, 1, pt.param.In}
}
func (pt paramTypable) Schema() *spec.Schema {
if pt.param.In != bodyTag {
return nil
}
if pt.param.Schema == nil {
pt.param.Schema = new(spec.Schema)
}
return pt.param.Schema
}
func (pt paramTypable) AddExtension(key string, value any) {
if pt.param.In == bodyTag {
pt.Schema().AddExtension(key, value)
} else {
pt.param.AddExtension(key, value)
}
}
func (pt paramTypable) WithEnum(values ...any) {
pt.param.WithEnum(values...)
}
func (pt paramTypable) WithEnumDescription(desc string) {
if desc == "" {
return
}
pt.param.AddExtension(extEnumDesc, desc)
}
type itemsTypable struct {
items *spec.Items
level int
in string
}
func (pt itemsTypable) In() string { return pt.in } // TODO(fred): inherit from param
func (pt itemsTypable) Level() int { return pt.level }
func (pt itemsTypable) Typed(tpe, format string) {
pt.items.Typed(tpe, format)
}
func (pt itemsTypable) SetRef(ref spec.Ref) {
pt.items.Ref = ref
}
func (pt itemsTypable) Schema() *spec.Schema {
return nil
}
func (pt itemsTypable) Items() swaggerTypable { //nolint:ireturn // polymorphic by design
if pt.items.Items == nil {
pt.items.Items = new(spec.Items)
}
pt.items.Type = typeArray
return itemsTypable{pt.items.Items, pt.level + 1, pt.in}
}
func (pt itemsTypable) AddExtension(key string, value any) {
pt.items.AddExtension(key, value)
}
func (pt itemsTypable) WithEnum(values ...any) {
pt.items.WithEnum(values...)
}
func (pt itemsTypable) WithEnumDescription(_ string) {
// no
}
type paramValidations struct {
current *spec.Parameter
}
func (sv paramValidations) SetMaximum(val float64, exclusive bool) {
sv.current.Maximum = &val
sv.current.ExclusiveMaximum = exclusive
}
func (sv paramValidations) SetMinimum(val float64, exclusive bool) {
sv.current.Minimum = &val
sv.current.ExclusiveMinimum = exclusive
}
func (sv paramValidations) SetMultipleOf(val float64) { sv.current.MultipleOf = &val }
func (sv paramValidations) SetMinItems(val int64) { sv.current.MinItems = &val }
func (sv paramValidations) SetMaxItems(val int64) { sv.current.MaxItems = &val }
func (sv paramValidations) SetMinLength(val int64) { sv.current.MinLength = &val }
func (sv paramValidations) SetMaxLength(val int64) { sv.current.MaxLength = &val }
func (sv paramValidations) SetPattern(val string) { sv.current.Pattern = val }
func (sv paramValidations) SetUnique(val bool) { sv.current.UniqueItems = val }
func (sv paramValidations) SetCollectionFormat(val string) { sv.current.CollectionFormat = val }
func (sv paramValidations) SetEnum(val string) {
sv.current.Enum = parseEnum(val, &spec.SimpleSchema{Type: sv.current.Type, Format: sv.current.Format})
}
func (sv paramValidations) SetDefault(val any) { sv.current.Default = val }
func (sv paramValidations) SetExample(val any) { sv.current.Example = val }
type itemsValidations struct {
current *spec.Items
}
func (sv itemsValidations) SetMaximum(val float64, exclusive bool) {
sv.current.Maximum = &val
sv.current.ExclusiveMaximum = exclusive
}
func (sv itemsValidations) SetMinimum(val float64, exclusive bool) {
sv.current.Minimum = &val
sv.current.ExclusiveMinimum = exclusive
}
func (sv itemsValidations) SetMultipleOf(val float64) { sv.current.MultipleOf = &val }
func (sv itemsValidations) SetMinItems(val int64) { sv.current.MinItems = &val }
func (sv itemsValidations) SetMaxItems(val int64) { sv.current.MaxItems = &val }
func (sv itemsValidations) SetMinLength(val int64) { sv.current.MinLength = &val }
func (sv itemsValidations) SetMaxLength(val int64) { sv.current.MaxLength = &val }
func (sv itemsValidations) SetPattern(val string) { sv.current.Pattern = val }
func (sv itemsValidations) SetUnique(val bool) { sv.current.UniqueItems = val }
func (sv itemsValidations) SetCollectionFormat(val string) { sv.current.CollectionFormat = val }
func (sv itemsValidations) SetEnum(val string) {
sv.current.Enum = parseEnum(val, &spec.SimpleSchema{Type: sv.current.Type, Format: sv.current.Format})
}
func (sv itemsValidations) SetDefault(val any) { sv.current.Default = val }
func (sv itemsValidations) SetExample(val any) { sv.current.Example = val }
type parameterBuilder struct {
ctx *scanCtx
decl *entityDecl
postDecls []*entityDecl
}
func (p *parameterBuilder) Build(operations map[string]*spec.Operation) error {
// check if there is a swagger:parameters tag that is followed by one or more words,
// these words are the ids of the operations this parameter struct applies to
// once type name is found convert it to a schema, by looking up the schema in the
// parameters dictionary that got passed into this parse method
for _, opid := range p.decl.OperationIDs() {
operation, ok := operations[opid]
if !ok {
operation = new(spec.Operation)
operations[opid] = operation
operation.ID = opid
}
debugLogf(p.ctx.debug, "building parameters for: %s", opid)
// analyze struct body for fields etc
// each exported struct field:
// * gets a type mapped to a go primitive
// * perhaps gets a format
// * has to document the validations that apply for the type and the field
// * when the struct field points to a model it becomes a ref: #/definitions/ModelName
// * comments that aren't tags is used as the description
if err := p.buildFromType(p.decl.ObjType(), operation, make(map[string]spec.Parameter)); err != nil {
return err
}
}
return nil
}
func (p *parameterBuilder) buildFromType(otpe types.Type, op *spec.Operation, seen map[string]spec.Parameter) error {
switch tpe := otpe.(type) {
case *types.Pointer:
return p.buildFromType(tpe.Elem(), op, seen)
case *types.Named:
return p.buildNamedType(tpe, op, seen)
case *types.Alias:
debugLogf(p.ctx.debug, "alias(parameters.buildFromType): got alias %v to %v", tpe, tpe.Rhs())
return p.buildAlias(tpe, op, seen)
default:
return fmt.Errorf("unhandled type (%T): %s: %w", otpe, tpe.String(), ErrCodeScan)
}
}
func (p *parameterBuilder) buildNamedType(tpe *types.Named, op *spec.Operation, seen map[string]spec.Parameter) error {
o := tpe.Obj()
if isAny(o) || isStdError(o) {
return fmt.Errorf("%s type not supported in the context of a parameters section definition: %w", o.Name(), ErrCodeScan)
}
mustNotBeABuiltinType(o)
switch stpe := o.Type().Underlying().(type) {
case *types.Struct:
debugLogf(p.ctx.debug, "build from named type %s: %T", o.Name(), tpe)
if decl, found := p.ctx.DeclForType(o.Type()); found {
return p.buildFromStruct(decl, stpe, op, seen)
}
return p.buildFromStruct(p.decl, stpe, op, seen)
default:
return fmt.Errorf("unhandled type (%T): %s: %w", stpe, o.Type().Underlying().String(), ErrCodeScan)
}
}
func (p *parameterBuilder) buildAlias(tpe *types.Alias, op *spec.Operation, seen map[string]spec.Parameter) error {
o := tpe.Obj()
if isAny(o) || isStdError(o) {
return fmt.Errorf("%s type not supported in the context of a parameters section definition: %w", o.Name(), ErrCodeScan)
}
mustNotBeABuiltinType(o)
mustHaveRightHandSide(tpe)
rhs := tpe.Rhs()
// If transparent aliases are enabled, use the underlying type directly without creating a definition
if p.ctx.app.transparentAliases {
return p.buildFromType(rhs, op, seen)
}
decl, ok := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !ok {
return fmt.Errorf("can't find source file for aliased type: %v -> %v: %w", tpe, rhs, ErrCodeScan)
}
p.postDecls = append(p.postDecls, decl) // mark the left-hand side as discovered
switch rtpe := rhs.(type) {
// load declaration for named unaliased type
case *types.Named:
o := rtpe.Obj()
if o.Pkg() == nil {
break // builtin
}
decl, found := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
p.postDecls = append(p.postDecls, decl)
case *types.Alias:
o := rtpe.Obj()
if o.Pkg() == nil {
break // builtin
}
decl, found := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
p.postDecls = append(p.postDecls, decl)
}
return p.buildFromType(rhs, op, seen)
}
func (p *parameterBuilder) buildFromField(fld *types.Var, tpe types.Type, typable swaggerTypable, seen map[string]spec.Parameter) error {
debugLogf(p.ctx.debug, "build from field %s: %T", fld.Name(), tpe)
switch ftpe := tpe.(type) {
case *types.Basic:
return swaggerSchemaForType(ftpe.Name(), typable)
case *types.Struct:
return p.buildFromFieldStruct(ftpe, typable)
case *types.Pointer:
return p.buildFromField(fld, ftpe.Elem(), typable, seen)
case *types.Interface:
return p.buildFromFieldInterface(ftpe, typable)
case *types.Array:
return p.buildFromField(fld, ftpe.Elem(), typable.Items(), seen)
case *types.Slice:
return p.buildFromField(fld, ftpe.Elem(), typable.Items(), seen)
case *types.Map:
return p.buildFromFieldMap(ftpe, typable)
case *types.Named:
return p.buildNamedField(ftpe, typable)
case *types.Alias:
debugLogf(p.ctx.debug, "alias(parameters.buildFromField): got alias %v to %v", ftpe, ftpe.Rhs()) // TODO
return p.buildFieldAlias(ftpe, typable, fld, seen)
default:
return fmt.Errorf("unknown type for %s: %T: %w", fld.String(), fld.Type(), ErrCodeScan)
}
}
func (p *parameterBuilder) buildFromFieldStruct(tpe *types.Struct, typable swaggerTypable) error {
sb := schemaBuilder{
decl: p.decl,
ctx: p.ctx,
}
if err := sb.buildFromType(tpe, typable); err != nil {
return err
}
p.postDecls = append(p.postDecls, sb.postDecls...)
return nil
}
func (p *parameterBuilder) buildFromFieldMap(ftpe *types.Map, typable swaggerTypable) error {
schema := new(spec.Schema)
typable.Schema().Typed("object", "").AdditionalProperties = &spec.SchemaOrBool{
Schema: schema,
}
sb := schemaBuilder{
decl: p.decl,
ctx: p.ctx,
}
if err := sb.buildFromType(ftpe.Elem(), schemaTypable{schema, typable.Level() + 1, p.ctx.opts.SkipExtensions}); err != nil {
return err
}
return nil
}
func (p *parameterBuilder) buildFromFieldInterface(tpe *types.Interface, typable swaggerTypable) error {
sb := schemaBuilder{
decl: p.decl,
ctx: p.ctx,
}
if err := sb.buildFromType(tpe, typable); err != nil {
return err
}
p.postDecls = append(p.postDecls, sb.postDecls...)
return nil
}
func (p *parameterBuilder) buildNamedField(ftpe *types.Named, typable swaggerTypable) error {
o := ftpe.Obj()
if isAny(o) {
// e.g. Field interface{} or Field any
return nil
}
if isStdError(o) {
return fmt.Errorf("%s type not supported in the context of a parameter definition: %w", o.Name(), ErrCodeScan)
}
mustNotBeABuiltinType(o)
decl, found := p.ctx.DeclForType(o.Type())
if !found {
return fmt.Errorf("unable to find package and source file for: %s: %w", ftpe.String(), ErrCodeScan)
}
if isStdTime(o) {
typable.Typed("string", "date-time")
return nil
}
if sfnm, isf := strfmtName(decl.Comments); isf {
typable.Typed("string", sfnm)
return nil
}
sb := &schemaBuilder{ctx: p.ctx, decl: decl}
sb.inferNames()
if err := sb.buildFromType(decl.ObjType(), typable); err != nil {
return err
}
p.postDecls = append(p.postDecls, sb.postDecls...)
return nil
}
func (p *parameterBuilder) buildFieldAlias(tpe *types.Alias, typable swaggerTypable, fld *types.Var, seen map[string]spec.Parameter) error {
o := tpe.Obj()
if isAny(o) {
// e.g. Field interface{} or Field any
_ = typable.Schema()
return nil // just leave an empty schema
}
if isStdError(o) {
return fmt.Errorf("%s type not supported in the context of a parameter definition: %w", o.Name(), ErrCodeScan)
}
mustNotBeABuiltinType(o)
mustHaveRightHandSide(tpe)
rhs := tpe.Rhs()
// If transparent aliases are enabled, use the underlying type directly without creating a definition
if p.ctx.app.transparentAliases {
sb := schemaBuilder{
decl: p.decl,
ctx: p.ctx,
}
if err := sb.buildFromType(rhs, typable); err != nil {
return err
}
p.postDecls = append(p.postDecls, sb.postDecls...)
return nil
}
decl, ok := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !ok {
return fmt.Errorf("can't find source file for aliased type: %v -> %v: %w", tpe, rhs, ErrCodeScan)
}
p.postDecls = append(p.postDecls, decl) // mark the left-hand side as discovered
if typable.In() != bodyTag || !p.ctx.app.refAliases {
// if ref option is disabled, and always for non-body parameters: just expand the alias
unaliased := types.Unalias(tpe)
return p.buildFromField(fld, unaliased, typable, seen)
}
// for parameters that are full-fledged schemas, consider expanding or ref'ing
switch rtpe := rhs.(type) {
// load declaration for named RHS type (might be an alias itself)
case *types.Named:
o := rtpe.Obj()
if o.Pkg() == nil {
break // builtin
}
decl, found := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
return p.makeRef(decl, typable)
case *types.Alias:
o := rtpe.Obj()
if o.Pkg() == nil {
break // builtin
}
decl, found := p.ctx.FindModel(o.Pkg().Path(), o.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
return p.makeRef(decl, typable)
}
// anonymous type: just expand it
return p.buildFromField(fld, rhs, typable, seen)
}
func spExtensionsSetter(ps *spec.Parameter, skipExt bool) func(*spec.Extensions) {
return func(exts *spec.Extensions) {
for name, value := range *exts {
addExtension(&ps.VendorExtensible, name, value, skipExt)
}
}
}
func (p *parameterBuilder) buildFromStruct(decl *entityDecl, tpe *types.Struct, op *spec.Operation, seen map[string]spec.Parameter) error {
numFields := tpe.NumFields()
if numFields == 0 {
return nil
}
sequence := make([]string, 0, numFields)
for i := range numFields {
fld := tpe.Field(i)
if fld.Embedded() {
if err := p.buildFromType(fld.Type(), op, seen); err != nil {
return err
}
continue
}
name, err := p.processParamField(fld, decl, seen)
if err != nil {
return err
}
if name != "" {
sequence = append(sequence, name)
}
}
for _, k := range sequence {
p := seen[k]
for i, v := range op.Parameters {
if v.Name == k {
op.Parameters = append(op.Parameters[:i], op.Parameters[i+1:]...)
break
}
}
op.Parameters = append(op.Parameters, p)
}
return nil
}
// processParamField processes a single non-embedded struct field for parameter building.
// Returns the parameter name if the field was processed, or "" if it was skipped.
func (p *parameterBuilder) processParamField(fld *types.Var, decl *entityDecl, seen map[string]spec.Parameter) (string, error) {
if !fld.Exported() {
debugLogf(p.ctx.debug, "skipping field %s because it's not exported", fld.Name())
return "", nil
}
afld := findASTField(decl.File, fld.Pos())
if afld == nil {
debugLogf(p.ctx.debug, "can't find source associated with %s", fld.String())
return "", nil
}
if ignored(afld.Doc) {
return "", nil
}
name, ignore, _, _, err := parseJSONTag(afld)
if err != nil {
return "", err
}
if ignore {
return "", nil
}
in := paramInQuery
// scan for param location first, this changes some behavior down the line
if afld.Doc != nil {
for _, cmt := range afld.Doc.List {
for line := range strings.SplitSeq(cmt.Text, "\n") {
matches := rxIn.FindStringSubmatch(line)
if len(matches) > 0 && len(strings.TrimSpace(matches[1])) > 0 {
in = strings.TrimSpace(matches[1])
}
}
}
}
ps := seen[name]
ps.In = in
var pty swaggerTypable = paramTypable{&ps, p.ctx.opts.SkipExtensions}
if in == bodyTag {
pty = schemaTypable{pty.Schema(), 0, p.ctx.opts.SkipExtensions}
}
if in == "formData" && afld.Doc != nil && fileParam(afld.Doc) {
pty.Typed("file", "")
} else if err := p.buildFromField(fld, fld.Type(), pty, seen); err != nil {
return "", err
}
if strfmtName, ok := strfmtName(afld.Doc); ok {
ps.Typed("string", strfmtName)
ps.Ref = spec.Ref{}
ps.Items = nil
}
sp := new(sectionedParser)
sp.setDescription = func(lines []string) {
ps.Description = joinDropLast(lines)
enumDesc := getEnumDesc(ps.Extensions)
if enumDesc != "" {
ps.Description += "\n" + enumDesc
}
}
if ps.Ref.String() != "" {
setupRefParamTaggers(sp, &ps, p.ctx.opts.SkipExtensions, p.ctx.debug)
} else {
if err := setupInlineParamTaggers(sp, &ps, name, afld, p.ctx.opts.SkipExtensions, p.ctx.debug); err != nil {
return "", err
}
}
if err := sp.Parse(afld.Doc); err != nil {
return "", err
}
if ps.In == "path" {
ps.Required = true
}
if ps.Name == "" {
ps.Name = name
}
if name != fld.Name() {
addExtension(&ps.VendorExtensible, "x-go-name", fld.Name(), p.ctx.opts.SkipExtensions)
}
seen[name] = ps
return name, nil
}
func (p *parameterBuilder) makeRef(decl *entityDecl, prop swaggerTypable) error {
nm, _ := decl.Names()
ref, err := spec.NewRef("#/definitions/" + nm)
if err != nil {
return err
}
prop.SetRef(ref)
p.postDecls = append(p.postDecls, decl) // mark the $ref target as discovered
return nil
}