/
schema.go
1182 lines (1062 loc) · 33.4 KB
/
schema.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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package codescan
import (
"encoding/json"
"fmt"
"go/ast"
"go/importer"
"go/types"
"log"
"os"
"reflect"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
"github.com/go-openapi/spec"
"github.com/pkg/errors"
)
func addExtension(ve *spec.VendorExtensible, key string, value interface{}) {
if os.Getenv("SWAGGER_GENERATE_EXTENSION") == "false" {
return
}
ve.AddExtension(key, value)
}
type schemaTypable struct {
schema *spec.Schema
level int
}
func (st schemaTypable) Typed(tpe, format string) {
st.schema.Typed(tpe, format)
}
func (st schemaTypable) SetRef(ref spec.Ref) {
st.schema.Ref = ref
}
func (st schemaTypable) Schema() *spec.Schema {
return st.schema
}
func (st schemaTypable) Items() swaggerTypable {
if st.schema.Items == nil {
st.schema.Items = new(spec.SchemaOrArray)
}
if st.schema.Items.Schema == nil {
st.schema.Items.Schema = new(spec.Schema)
}
st.schema.Typed("array", "")
return schemaTypable{st.schema.Items.Schema, st.level + 1}
}
func (st schemaTypable) AdditionalProperties() swaggerTypable {
if st.schema.AdditionalProperties == nil {
st.schema.AdditionalProperties = new(spec.SchemaOrBool)
}
if st.schema.AdditionalProperties.Schema == nil {
st.schema.AdditionalProperties.Schema = new(spec.Schema)
}
st.schema.Typed("object", "")
return schemaTypable{st.schema.AdditionalProperties.Schema, st.level + 1}
}
func (st schemaTypable) Level() int { return st.level }
func (st schemaTypable) AddExtension(key string, value interface{}) {
addExtension(&st.schema.VendorExtensible, key, value)
}
func (st schemaTypable) WithEnum(values ...interface{}) {
st.schema.WithEnum(values...)
}
func (st schemaTypable) WithEnumDescription(desc string) {
if desc == "" {
return
}
st.AddExtension(extEnumDesc, desc)
}
type schemaValidations struct {
current *spec.Schema
}
func (sv schemaValidations) SetMaximum(val float64, exclusive bool) {
sv.current.Maximum = &val
sv.current.ExclusiveMaximum = exclusive
}
func (sv schemaValidations) SetMinimum(val float64, exclusive bool) {
sv.current.Minimum = &val
sv.current.ExclusiveMinimum = exclusive
}
func (sv schemaValidations) SetMultipleOf(val float64) { sv.current.MultipleOf = &val }
func (sv schemaValidations) SetMinItems(val int64) { sv.current.MinItems = &val }
func (sv schemaValidations) SetMaxItems(val int64) { sv.current.MaxItems = &val }
func (sv schemaValidations) SetMinLength(val int64) { sv.current.MinLength = &val }
func (sv schemaValidations) SetMaxLength(val int64) { sv.current.MaxLength = &val }
func (sv schemaValidations) SetPattern(val string) { sv.current.Pattern = val }
func (sv schemaValidations) SetUnique(val bool) { sv.current.UniqueItems = val }
func (sv schemaValidations) SetDefault(val interface{}) { sv.current.Default = val }
func (sv schemaValidations) SetExample(val interface{}) { sv.current.Example = val }
func (sv schemaValidations) SetEnum(val string) {
sv.current.Enum = parseEnum(val, &spec.SimpleSchema{Format: sv.current.Format, Type: sv.current.Type[0]})
}
type schemaBuilder struct {
ctx *scanCtx
decl *entityDecl
GoName string
Name string
annotated bool
discovered []*entityDecl
postDecls []*entityDecl
}
func (s *schemaBuilder) inferNames() (goName string, name string) {
if s.GoName != "" {
goName, name = s.GoName, s.Name
return
}
goName = s.decl.Ident.Name
name = goName
defer func() {
s.GoName = goName
s.Name = name
}()
if s.decl.Comments == nil {
return
}
DECLS:
for _, cmt := range s.decl.Comments.List {
for _, ln := range strings.Split(cmt.Text, "\n") {
matches := rxModelOverride.FindStringSubmatch(ln)
if len(matches) > 0 {
s.annotated = true
}
if len(matches) > 1 && len(matches[1]) > 0 {
name = matches[1]
break DECLS
}
}
}
return
}
func (s *schemaBuilder) Build(definitions map[string]spec.Schema) error {
s.inferNames()
schema := definitions[s.Name]
err := s.buildFromDecl(s.decl, &schema)
if err != nil {
return err
}
definitions[s.Name] = schema
return nil
}
func (s *schemaBuilder) buildFromDecl(decl *entityDecl, schema *spec.Schema) error {
// analyze doc comment for the model
sp := new(sectionedParser)
sp.setTitle = func(lines []string) { schema.Title = joinDropLast(lines) }
sp.setDescription = func(lines []string) {
schema.Description = joinDropLast(lines)
enumDesc := getEnumDesc(schema.VendorExtensible.Extensions)
if enumDesc != "" {
schema.Description += "\n" + enumDesc
}
}
if err := sp.Parse(s.decl.Comments); err != nil {
return err
}
// if the type is marked to ignore, just return
if sp.ignored {
return nil
}
switch tpe := s.decl.Type.Obj().Type().(type) {
case *types.Basic:
debugLog("basic: %v", tpe.Name())
case *types.Struct:
if err := s.buildFromStruct(s.decl, tpe, schema, make(map[string]string)); err != nil {
return err
}
case *types.Interface:
if err := s.buildFromInterface(s.decl, tpe, schema, make(map[string]string)); err != nil {
return err
}
case *types.Array:
debugLog("array: %v -> %v", s.decl.Ident.Name, tpe.Elem().String())
case *types.Slice:
debugLog("slice: %v -> %v", s.decl.Ident.Name, tpe.Elem().String())
case *types.Map:
debugLog("map: %v -> [%v]%v", s.decl.Ident.Name, tpe.Key().String(), tpe.Elem().String())
case *types.Named:
o := tpe.Obj()
if o != nil {
debugLog("got the named type object: %s.%s | isAlias: %t | exported: %t", o.Pkg().Path(), o.Name(), o.IsAlias(), o.Exported())
if o.Pkg().Name() == "time" && o.Name() == "Time" {
schema.Typed("string", "date-time")
return nil
}
ps := schemaTypable{schema, 0}
for {
ti := s.decl.Pkg.TypesInfo.Types[s.decl.Spec.Type]
if ti.IsBuiltin() {
break
}
if ti.IsType() {
if err := s.buildFromType(ti.Type, ps); err != nil {
return err
}
break
}
}
}
default:
log.Printf("WARNING: Missing parser for a %T, skipping model: %s\n", tpe, s.Name)
return nil
}
if schema.Ref.String() == "" {
if s.Name != s.GoName {
addExtension(&schema.VendorExtensible, "x-go-name", s.GoName)
}
addExtension(&schema.VendorExtensible, "x-go-package", s.decl.Type.Obj().Pkg().Path())
}
return nil
}
func (s *schemaBuilder) buildFromTextMarshal(tpe types.Type, tgt swaggerTypable) error {
if typePtr, ok := tpe.(*types.Pointer); ok {
return s.buildFromTextMarshal(typePtr.Elem(), tgt)
}
typeNamed, ok := tpe.(*types.Named)
if !ok {
tgt.Typed("string", "")
return nil
}
tio := typeNamed.Obj()
if tio.Pkg() == nil && tio.Name() == "error" {
return swaggerSchemaForType(tio.Name(), tgt)
}
debugLog("named refined type %s.%s", tio.Pkg().Path(), tio.Name())
pkg, found := s.ctx.PkgForType(tpe)
if strings.ToLower(tio.Name()) == "uuid" {
tgt.Typed("string", "uuid")
return nil
}
if !found {
// this must be a builtin
debugLog("skipping because package is nil: %s", tpe.String())
return nil
}
if pkg.Name == "time" && tio.Name() == "Time" {
tgt.Typed("string", "date-time")
return nil
}
if pkg.PkgPath == "encoding/json" && tio.Name() == "RawMessage" {
tgt.Typed("object", "")
return nil
}
cmt, hasComments := s.ctx.FindComments(pkg, tio.Name())
if !hasComments {
cmt = new(ast.CommentGroup)
}
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
tgt.Typed("string", "")
return nil
}
func (s *schemaBuilder) buildFromType(tpe types.Type, tgt swaggerTypable) error {
pkg, err := importer.Default().Import("encoding")
if err != nil {
return nil
}
ifc := pkg.Scope().Lookup("TextMarshaler").Type().Underlying().(*types.Interface)
// check if the type implements encoding.TextMarshaler interface
isTextMarshaler := types.Implements(tpe, ifc)
if isTextMarshaler {
return s.buildFromTextMarshal(tpe, tgt)
}
switch titpe := tpe.(type) {
case *types.Basic:
return swaggerSchemaForType(titpe.String(), tgt)
case *types.Pointer:
return s.buildFromType(titpe.Elem(), tgt)
case *types.Struct:
return s.buildFromStruct(s.decl, titpe, tgt.Schema(), make(map[string]string))
case *types.Interface:
return s.buildFromInterface(s.decl, titpe, tgt.Schema(), make(map[string]string))
case *types.Slice:
return s.buildFromType(titpe.Elem(), tgt.Items())
case *types.Array:
return s.buildFromType(titpe.Elem(), tgt.Items())
case *types.Map:
// debugLog("map: %v -> [%v]%v", fld.Name(), ftpe.Key().String(), ftpe.Elem().String())
// check if key is a string type, if not print a message
// and skip the map property. Only maps with string keys can go into additional properties
sch := tgt.Schema()
if sch == nil {
return errors.New("items doesn't support maps")
}
eleProp := schemaTypable{sch, tgt.Level()}
key := titpe.Key()
isTextMarshaler := types.Implements(key, ifc)
if key.Underlying().String() == "string" || isTextMarshaler {
if err := s.buildFromType(titpe.Elem(), eleProp.AdditionalProperties()); err != nil {
return err
}
return nil
}
case *types.Named:
tio := titpe.Obj()
if tio.Pkg() == nil && tio.Name() == "error" {
return swaggerSchemaForType(tio.Name(), tgt)
}
debugLog("named refined type %s.%s", tio.Pkg().Path(), tio.Name())
pkg, found := s.ctx.PkgForType(tpe)
if !found {
// this must be a builtin
debugLog("skipping because package is nil: %s", tpe.String())
return nil
}
if pkg.Name == "time" && tio.Name() == "Time" {
tgt.Typed("string", "date-time")
return nil
}
if pkg.PkgPath == "encoding/json" && tio.Name() == "RawMessage" {
tgt.Typed("object", "")
return nil
}
cmt, hasComments := s.ctx.FindComments(pkg, tio.Name())
if !hasComments {
cmt = new(ast.CommentGroup)
}
if typeName, ok := typeName(cmt); ok {
_ = swaggerSchemaForType(typeName, tgt)
return nil
}
switch utitpe := tpe.Underlying().(type) {
case *types.Struct:
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if decl.Type.Obj().Pkg().Path() == "time" && decl.Type.Obj().Name() == "Time" {
tgt.Typed("string", "date-time")
return nil
}
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
if typeName, ok := typeName(cmt); ok {
_ = swaggerSchemaForType(typeName, tgt)
return nil
}
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
case *types.Interface:
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
case *types.Basic:
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
if enumName, ok := enumName(cmt); ok {
enumValues, enumDesces, _ := s.ctx.FindEnumValues(pkg, enumName)
if len(enumValues) > 0 {
tgt.WithEnum(enumValues...)
enumTypeName := reflect.TypeOf(enumValues[0]).String()
_ = swaggerSchemaForType(enumTypeName, tgt)
}
if len(enumDesces) > 0 {
tgt.WithEnumDescription(strings.Join(enumDesces, "\n"))
}
return nil
}
if defaultName, ok := defaultName(cmt); ok {
debugLog(defaultName)
return nil
}
if typeName, ok := typeName(cmt); ok {
_ = swaggerSchemaForType(typeName, tgt)
return nil
}
if isAliasParam(tgt) || aliasParam(cmt) {
err := swaggerSchemaForType(utitpe.Name(), tgt)
if err == nil {
return nil
}
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
return swaggerSchemaForType(utitpe.String(), tgt)
case *types.Array:
if sfnm, isf := strfmtName(cmt); isf {
if sfnm == "byte" {
tgt.Typed("string", sfnm)
return nil
}
if sfnm == "bsonobjectid" {
tgt.Typed("string", sfnm)
return nil
}
tgt.Items().Typed("string", sfnm)
return nil
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
return s.buildFromType(utitpe.Elem(), tgt.Items())
case *types.Slice:
if sfnm, isf := strfmtName(cmt); isf {
if sfnm == "byte" {
tgt.Typed("string", sfnm)
return nil
}
tgt.Items().Typed("string", sfnm)
return nil
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
return s.buildFromType(utitpe.Elem(), tgt.Items())
case *types.Map:
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
if err := s.makeRef(decl, tgt); err != nil {
return err
}
return nil
}
return nil
default:
log.Printf("WARNING: can't figure out object type for named type (%T): %v [alias: %t]", tpe.Underlying(), tpe.Underlying(), titpe.Obj().IsAlias())
return nil
}
default:
panic(fmt.Sprintf("WARNING: can't determine refined type %s (%T)", titpe.String(), titpe))
}
return nil
}
func (s *schemaBuilder) buildFromInterface(decl *entityDecl, it *types.Interface, schema *spec.Schema, seen map[string]string) error {
if it.Empty() {
return nil
}
var (
tgt *spec.Schema
hasAllOf bool
)
var flist []*ast.Field
if specType, ok := decl.Spec.Type.(*ast.InterfaceType); ok {
flist = make([]*ast.Field, it.NumEmbeddeds()+it.NumExplicitMethods())
copy(flist, specType.Methods.List)
// for i := range specType.Methods.List {
// flist[i] = specType.Methods.List[i]
// }
}
// First collect the embedded interfaces
// create refs when the embedded interface is decorated with an allOf annotation
for i := 0; i < it.NumEmbeddeds(); i++ {
fld := it.EmbeddedType(i)
switch ftpe := fld.(type) {
case *types.Named:
o := ftpe.Obj()
var afld *ast.Field
for _, an := range flist {
if len(an.Names) != 0 {
continue
}
tpp := decl.Pkg.TypesInfo.Types[an.Type]
if tpp.Type.String() != o.Type().String() {
continue
}
// decl.
debugLog("maybe interface field %s: %s(%T)", o.Name(), o.Type().String(), o.Type())
afld = an
break
}
if afld == nil {
debugLog("can't find source associated with %s for %s", fld.String(), it.String())
continue
}
// if the field is annotated with swagger:ignore, ignore it
if ignored(afld.Doc) {
continue
}
if !allOfMember(afld.Doc) {
var newSch spec.Schema
if err := s.buildEmbedded(o.Type(), &newSch, seen); err != nil {
return err
}
schema.AllOf = append(schema.AllOf, newSch)
hasAllOf = true
continue
}
hasAllOf = true
if tgt == nil {
tgt = &spec.Schema{}
}
var newSch spec.Schema
// when the embedded struct is annotated with swagger:allOf it will be used as allOf property
// otherwise the fields will just be included as normal properties
if err := s.buildAllOf(o.Type(), &newSch); err != nil {
return err
}
if afld.Doc != nil {
for _, cmt := range afld.Doc.List {
for _, ln := range strings.Split(cmt.Text, "\n") {
matches := rxAllOf.FindStringSubmatch(ln)
ml := len(matches)
if ml > 1 {
mv := matches[ml-1]
if mv != "" {
schema.AddExtension("x-class", mv)
}
}
}
}
}
schema.AllOf = append(schema.AllOf, newSch)
default:
log.Printf("WARNING: can't figure out object type for allOf named type (%T): %v", ftpe, ftpe.Underlying())
}
debugLog("got embedded interface: %s {%T}", fld.String(), fld)
}
if tgt == nil {
tgt = schema
}
// We can finally build the actual schema for the struct
if tgt.Properties == nil {
tgt.Properties = make(map[string]spec.Schema)
}
tgt.Typed("object", "")
for i := 0; i < it.NumExplicitMethods(); i++ {
fld := it.ExplicitMethod(i)
if !fld.Exported() {
continue
}
sig, isSignature := fld.Type().(*types.Signature)
if !isSignature {
continue
}
if sig.Params().Len() > 0 {
continue
}
if sig.Results() == nil || sig.Results().Len() != 1 {
continue
}
var afld *ast.Field
ans, _ := astutil.PathEnclosingInterval(decl.File, fld.Pos(), fld.Pos())
// debugLog("got %d nodes (exact: %t)", len(ans), isExact)
for _, an := range ans {
at, valid := an.(*ast.Field)
if !valid {
continue
}
debugLog("maybe interface field %s: %s(%T)", fld.Name(), fld.Type().String(), fld.Type())
afld = at
break
}
if afld == nil {
debugLog("can't find source associated with %s for %s", fld.String(), it.String())
continue
}
// if the field is annotated with swagger:ignore, ignore it
if ignored(afld.Doc) {
continue
}
name := fld.Name()
if afld.Doc != nil {
for _, cmt := range afld.Doc.List {
for _, ln := range strings.Split(cmt.Text, "\n") {
matches := rxName.FindStringSubmatch(ln)
ml := len(matches)
if ml > 1 {
name = matches[ml-1]
}
}
}
}
ps := tgt.Properties[name]
if err := s.buildFromType(sig.Results().At(0).Type(), schemaTypable{&ps, 0}); err != nil {
return err
}
if sfName, isStrfmt := strfmtName(afld.Doc); isStrfmt {
ps.Typed("string", sfName)
ps.Ref = spec.Ref{}
ps.Items = nil
}
if err := s.createParser(name, tgt, &ps, afld).Parse(afld.Doc); err != nil {
return err
}
if ps.Ref.String() == "" && name != fld.Name() {
ps.AddExtension("x-go-name", fld.Name())
}
seen[name] = fld.Name()
tgt.Properties[name] = ps
}
if tgt == nil {
return nil
}
if hasAllOf && len(tgt.Properties) > 0 {
schema.AllOf = append(schema.AllOf, *tgt)
}
for k := range tgt.Properties {
if _, ok := seen[k]; !ok {
delete(tgt.Properties, k)
}
}
return nil
}
func (s *schemaBuilder) buildFromStruct(decl *entityDecl, st *types.Struct, schema *spec.Schema, seen map[string]string) error {
s.ctx.FindComments(decl.Pkg, decl.Type.Obj().Name())
cmt, hasComments := s.ctx.FindComments(decl.Pkg, decl.Type.Obj().Name())
if !hasComments {
cmt = new(ast.CommentGroup)
}
if typeName, ok := typeName(cmt); ok {
_ = swaggerSchemaForType(typeName, schemaTypable{schema: schema})
return nil
}
// First check for all of schemas
var tgt *spec.Schema
hasAllOf := false
for i := 0; i < st.NumFields(); i++ {
fld := st.Field(i)
if !fld.Anonymous() {
debugLog("skipping field %q for allOf scan because not anonymous", fld.Name())
continue
}
tg := st.Tag(i)
debugLog("maybe allof field(%t) %s: %s (%T) [%q](anon: %t, embedded: %t)", fld.IsField(), fld.Name(), fld.Type().String(), fld.Type(), tg, fld.Anonymous(), fld.Embedded())
var afld *ast.Field
ans, _ := astutil.PathEnclosingInterval(decl.File, fld.Pos(), fld.Pos())
// debugLog("got %d nodes (exact: %t)", len(ans), isExact)
for _, an := range ans {
at, valid := an.(*ast.Field)
if !valid {
continue
}
debugLog("maybe allof field %s: %s(%T) [%q]", fld.Name(), fld.Type().String(), fld.Type(), tg)
afld = at
break
}
if afld == nil {
debugLog("can't find source associated with %s for %s", fld.String(), st.String())
continue
}
// if the field is annotated with swagger:ignore, ignore it
if ignored(afld.Doc) {
continue
}
_, ignore, _, err := parseJSONTag(afld)
if err != nil {
return err
}
if ignore {
continue
}
if !allOfMember(afld.Doc) {
if tgt == nil {
tgt = schema
}
if err := s.buildEmbedded(fld.Type(), tgt, seen); err != nil {
return err
}
continue
}
// if this created an allOf property then we have to rejig the schema var
// because all the fields collected that aren't from embedded structs should go in
// their own proper schema
// first process embedded structs in order of embedding
hasAllOf = true
if tgt == nil {
tgt = &spec.Schema{}
}
var newSch spec.Schema
// when the embedded struct is annotated with swagger:allOf it will be used as allOf property
// otherwise the fields will just be included as normal properties
if err := s.buildAllOf(fld.Type(), &newSch); err != nil {
return err
}
if afld.Doc != nil {
for _, cmt := range afld.Doc.List {
for _, ln := range strings.Split(cmt.Text, "\n") {
matches := rxAllOf.FindStringSubmatch(ln)
ml := len(matches)
if ml > 1 {
mv := matches[ml-1]
if mv != "" {
schema.AddExtension("x-class", mv)
}
}
}
}
}
schema.AllOf = append(schema.AllOf, newSch)
}
if tgt == nil {
if schema != nil {
tgt = schema
} else {
tgt = &spec.Schema{}
}
}
// We can finally build the actual schema for the struct
if tgt.Properties == nil {
tgt.Properties = make(map[string]spec.Schema)
}
tgt.Typed("object", "")
for i := 0; i < st.NumFields(); i++ {
fld := st.Field(i)
tg := st.Tag(i)
if fld.Embedded() {
continue
}
if !fld.Exported() {
debugLog("skipping field %s because it's not exported", fld.Name())
continue
}
var afld *ast.Field
ans, _ := astutil.PathEnclosingInterval(decl.File, fld.Pos(), fld.Pos())
// debugLog("got %d nodes (exact: %t)", len(ans), isExact)
for _, an := range ans {
at, valid := an.(*ast.Field)
if !valid {
continue
}
debugLog("field %s: %s(%T) [%q] ==> %s", fld.Name(), fld.Type().String(), fld.Type(), tg, at.Doc.Text())
afld = at
break
}
if afld == nil {
debugLog("can't find source associated with %s", fld.String())
continue
}
// if the field is annotated with swagger:ignore, ignore it
if ignored(afld.Doc) {
continue
}
name, ignore, isString, err := parseJSONTag(afld)
if err != nil {
return err
}
if ignore {
for seenTagName, seenFieldName := range seen {
if seenFieldName == fld.Name() {
delete(tgt.Properties, seenTagName)
break
}
}
continue
}
ps := tgt.Properties[name]
if err = s.buildFromType(fld.Type(), schemaTypable{&ps, 0}); err != nil {
return err
}
if isString {
ps.Typed("string", ps.Format)
ps.Ref = spec.Ref{}
ps.Items = nil
}
if sfName, isStrfmt := strfmtName(afld.Doc); isStrfmt {
ps.Typed("string", sfName)
ps.Ref = spec.Ref{}
ps.Items = nil
}
if err = s.createParser(name, tgt, &ps, afld).Parse(afld.Doc); err != nil {
return err
}
if ps.Ref.String() == "" && name != fld.Name() {
addExtension(&ps.VendorExtensible, "x-go-name", fld.Name())
}
// we have 2 cases:
// 1. field with different name override tag
// 2. field with different name removes tag
// so we need to save both tag&name
seen[name] = fld.Name()
tgt.Properties[name] = ps
}
if tgt == nil {
return nil
}
if hasAllOf && len(tgt.Properties) > 0 {
schema.AllOf = append(schema.AllOf, *tgt)
}
for k := range tgt.Properties {
if _, ok := seen[k]; !ok {
delete(tgt.Properties, k)
}
}
return nil
}
func (s *schemaBuilder) buildAllOf(tpe types.Type, schema *spec.Schema) error {
debugLog("allOf %s", tpe.Underlying())
switch ftpe := tpe.(type) {
case *types.Pointer:
return s.buildAllOf(ftpe.Elem(), schema)
case *types.Named:
switch utpe := ftpe.Underlying().(type) {
case *types.Struct:
decl, found := s.ctx.FindModel(ftpe.Obj().Pkg().Path(), ftpe.Obj().Name())
if found {
if ftpe.Obj().Pkg().Path() == "time" && ftpe.Obj().Name() == "Time" {
schema.Typed("string", "date-time")
return nil
}
if sfnm, isf := strfmtName(decl.Comments); isf {
schema.Typed("string", sfnm)
return nil
}
if decl.HasModelAnnotation() {
if err := s.makeRef(decl, schemaTypable{schema, 0}); err != nil {
return err
}
return nil
}
return s.buildFromStruct(decl, utpe, schema, make(map[string]string))
}
return errors.Errorf("can't find source file for struct: %s", ftpe.String())
case *types.Interface:
decl, found := s.ctx.FindModel(ftpe.Obj().Pkg().Path(), ftpe.Obj().Name())
if found {
if sfnm, isf := strfmtName(decl.Comments); isf {
schema.Typed("string", sfnm)
return nil
}
if decl.HasModelAnnotation() {
if err := s.makeRef(decl, schemaTypable{schema, 0}); err != nil {
return err
}
return nil
}
return s.buildFromInterface(decl, utpe, schema, make(map[string]string))
}
return errors.Errorf("can't find source file for interface: %s", ftpe.String())
default:
log.Printf("WARNING: can't figure out object type for allOf named type (%T): %v", ftpe, ftpe.Underlying())
return fmt.Errorf("unable to locate source file for allOf %s", utpe.String())
}
default:
log.Printf("WARNING: Missing allOf parser for a %T, skipping field", ftpe)
return fmt.Errorf("unable to resolve allOf member for: %v", ftpe)
}
}
func (s *schemaBuilder) buildEmbedded(tpe types.Type, schema *spec.Schema, seen map[string]string) error {
debugLog("embedded %s", tpe.Underlying())
switch ftpe := tpe.(type) {
case *types.Pointer:
return s.buildEmbedded(ftpe.Elem(), schema, seen)
case *types.Named:
debugLog("embedded named type: %T", ftpe.Underlying())
switch utpe := ftpe.Underlying().(type) {
case *types.Struct:
decl, found := s.ctx.FindModel(ftpe.Obj().Pkg().Path(), ftpe.Obj().Name())
if found {
return s.buildFromStruct(decl, utpe, schema, seen)
}
return errors.Errorf("can't find source file for struct: %s", ftpe.String())
case *types.Interface:
decl, found := s.ctx.FindModel(ftpe.Obj().Pkg().Path(), ftpe.Obj().Name())
if found {
return s.buildFromInterface(decl, utpe, schema, seen)
}
return errors.Errorf("can't find source file for struct: %s", ftpe.String())
default:
log.Printf("WARNING: can't figure out object type for embedded named type (%T): %v", ftpe, ftpe.Underlying())
}
default:
log.Printf("WARNING: Missing embedded parser for a %T, skipping model\n", ftpe)
return nil
}
return nil
}
func (s *schemaBuilder) makeRef(decl *entityDecl, prop swaggerTypable) error {
nm, _ := decl.Names()
ref, err := spec.NewRef("#/definitions/" + nm)
if err != nil {
return err
}
prop.SetRef(ref)
s.postDecls = append(s.postDecls, decl)
return nil
}
func (s *schemaBuilder) createParser(nm string, schema, ps *spec.Schema, fld *ast.Field) *sectionedParser {
sp := new(sectionedParser)
schemeType, err := ps.Type.MarshalJSON()
if err != nil {
return nil
}
if ps.Ref.String() == "" {
sp.setDescription = func(lines []string) {
ps.Description = joinDropLast(lines)
enumDesc := getEnumDesc(ps.VendorExtensible.Extensions)
if enumDesc != "" {
ps.Description += "\n" + enumDesc