-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
parser.go
1525 lines (1353 loc) · 43.4 KB
/
parser.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 swag
import (
"encoding/json"
"fmt"
"go/ast"
"go/build"
goparser "go/parser"
"go/token"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"github.com/KyleBanks/depth"
"github.com/go-openapi/jsonreference"
"github.com/go-openapi/spec"
)
const (
// CamelCase indicates using CamelCase strategy for struct field.
CamelCase = "camelcase"
// PascalCase indicates using PascalCase strategy for struct field.
PascalCase = "pascalcase"
// SnakeCase indicates using SnakeCase strategy for struct field.
SnakeCase = "snakecase"
)
// Parser implements a parser for Go source files.
type Parser struct {
// swagger represents the root document object for the API specification
swagger *spec.Swagger
// files is a map that stores map[real_go_file_path][astFile]
files map[string]*ast.File
// TypeDefinitions is a map that stores [package name][type name][*ast.TypeSpec]
TypeDefinitions map[string]map[string]*ast.TypeSpec
// ImportAliases is map that stores [import name][import package name][*ast.ImportSpec]
ImportAliases map[string]map[string]*ast.ImportSpec
// CustomPrimitiveTypes is a map that stores custom primitive types to actual golang types [type name][string]
CustomPrimitiveTypes map[string]string
// registerTypes is a map that stores [refTypeName][*ast.TypeSpec]
registerTypes map[string]*ast.TypeSpec
PropNamingStrategy string
ParseVendor bool
// ParseDependencies whether swag should be parse outside dependency folder
ParseDependency bool
// ParseInternal whether swag should parse internal packages
ParseInternal bool
// structStack stores full names of the structures that were already parsed or are being parsed now
structStack []string
// markdownFileDir holds the path to the folder, where markdown files are stored
markdownFileDir string
// collectionFormatInQuery set the default collectionFormat otherwise then 'csv' for array in query params
collectionFormatInQuery string
// excludes excludes dirs and files in SearchDir
excludes map[string]bool
}
// New creates a new Parser with default properties.
func New(options ...func(*Parser)) *Parser {
parser := &Parser{
swagger: &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Info: &spec.Info{
InfoProps: spec.InfoProps{
Contact: &spec.ContactInfo{},
License: &spec.License{},
},
},
Paths: &spec.Paths{
Paths: make(map[string]spec.PathItem),
},
Definitions: make(map[string]spec.Schema),
},
},
files: make(map[string]*ast.File),
TypeDefinitions: make(map[string]map[string]*ast.TypeSpec),
ImportAliases: make(map[string]map[string]*ast.ImportSpec),
CustomPrimitiveTypes: make(map[string]string),
registerTypes: make(map[string]*ast.TypeSpec),
excludes: make(map[string]bool),
}
for _, option := range options {
option(parser)
}
return parser
}
// SetMarkdownFileDirectory sets the directory to search for markdownfiles
func SetMarkdownFileDirectory(directoryPath string) func(*Parser) {
return func(p *Parser) {
p.markdownFileDir = directoryPath
}
}
// SetExcludedDirsAndFiles sets directories and files to be excluded when searching
func SetExcludedDirsAndFiles(excludes string) func(*Parser) {
return func(p *Parser) {
for _, f := range strings.Split(excludes, ",") {
f = strings.TrimSpace(f)
if f != "" {
f = filepath.Clean(f)
p.excludes[f] = true
}
}
}
}
// ParseAPI parses general api info for given searchDir and mainAPIFile
func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string) error {
Printf("Generate general API Info, search dir:%s", searchDir)
if err := parser.getAllGoFileInfo(searchDir); err != nil {
return err
}
var t depth.Tree
t.ResolveInternal = true
absMainAPIFilePath, err := filepath.Abs(filepath.Join(searchDir, mainAPIFile))
if err != nil {
return err
}
if parser.ParseDependency {
pkgName, err := getPkgName(filepath.Dir(absMainAPIFilePath))
if err != nil {
return err
}
if err := t.Resolve(pkgName); err != nil {
return fmt.Errorf("pkg %s cannot find all dependencies, %s", pkgName, err)
}
for i := 0; i < len(t.Root.Deps); i++ {
if err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i]); err != nil {
return err
}
}
}
if err := parser.ParseGeneralAPIInfo(absMainAPIFilePath); err != nil {
return err
}
for _, astFile := range parser.files {
parser.ParseType(astFile)
}
for fileName, astFile := range parser.files {
if err := parser.ParseRouterAPIInfo(fileName, astFile); err != nil {
return err
}
}
return parser.parseDefinitions()
}
func getPkgName(searchDir string) (string, error) {
cmd := exec.Command("go", "list", "-f={{.ImportPath}}")
cmd.Dir = searchDir
var stdout, stderr strings.Builder
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("execute go list command, %s, stdout:%s, stderr:%s", err, stdout.String(), stderr.String())
}
outStr, _ := stdout.String(), stderr.String()
if outStr[0] == '_' { // will shown like _/{GOPATH}/src/{YOUR_PACKAGE} when NOT enable GO MODULE.
outStr = strings.TrimPrefix(outStr, "_"+build.Default.GOPATH+"/src/")
}
f := strings.Split(outStr, "\n")
outStr = f[0]
return outStr, nil
}
// ParseGeneralAPIInfo parses general api info for given mainAPIFile path
func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
fileSet := token.NewFileSet()
fileTree, err := goparser.ParseFile(fileSet, mainAPIFile, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("cannot parse source files %s: %s", mainAPIFile, err)
}
parser.swagger.Swagger = "2.0"
securityMap := map[string]*spec.SecurityScheme{}
for _, comment := range fileTree.Comments {
if !isGeneralAPIComment(comment) {
continue
}
comments := strings.Split(comment.Text(), "\n")
previousAttribute := ""
// parsing classic meta data model
for i, commentLine := range comments {
attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
value := strings.TrimSpace(commentLine[len(attribute):])
multilineBlock := false
if previousAttribute == attribute {
multilineBlock = true
}
switch attribute {
case "@version":
parser.swagger.Info.Version = value
case "@title":
parser.swagger.Info.Title = value
case "@description":
if multilineBlock {
parser.swagger.Info.Description += "\n" + value
continue
}
parser.swagger.Info.Description = value
case "@description.markdown":
commentInfo, err := getMarkdownForTag("api", parser.markdownFileDir)
if err != nil {
return err
}
parser.swagger.Info.Description = string(commentInfo)
case "@termsofservice":
parser.swagger.Info.TermsOfService = value
case "@contact.name":
parser.swagger.Info.Contact.Name = value
case "@contact.email":
parser.swagger.Info.Contact.Email = value
case "@contact.url":
parser.swagger.Info.Contact.URL = value
case "@license.name":
parser.swagger.Info.License.Name = value
case "@license.url":
parser.swagger.Info.License.URL = value
case "@host":
parser.swagger.Host = value
case "@basepath":
parser.swagger.BasePath = value
case "@schemes":
parser.swagger.Schemes = getSchemes(commentLine)
case "@tag.name":
parser.swagger.Tags = append(parser.swagger.Tags, spec.Tag{
TagProps: spec.TagProps{
Name: value,
},
})
case "@tag.description":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
tag.TagProps.Description = value
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.description.markdown":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
commentInfo, err := getMarkdownForTag(tag.TagProps.Name, parser.markdownFileDir)
if err != nil {
return err
}
tag.TagProps.Description = string(commentInfo)
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.url":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
tag.TagProps.ExternalDocs = &spec.ExternalDocumentation{
URL: value,
}
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.description":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
if tag.TagProps.ExternalDocs == nil {
return fmt.Errorf("%s needs to come after a @tags.docs.url", attribute)
}
tag.TagProps.ExternalDocs.Description = value
replaceLastTag(parser.swagger.Tags, tag)
case "@securitydefinitions.basic":
securityMap[value] = spec.BasicAuth()
case "@securitydefinitions.apikey":
attrMap, _, err := extractSecurityAttribute(attribute, []string{"@in", "@name"}, comments[i+1:])
if err != nil {
return err
}
securityMap[value] = spec.APIKeyAuth(attrMap["@name"], attrMap["@in"])
case "@securitydefinitions.oauth2.application":
attrMap, scopes, err := extractSecurityAttribute(attribute, []string{"@tokenurl"}, comments[i+1:])
if err != nil {
return err
}
securityMap[value] = securitySchemeOAuth2Application(attrMap["@tokenurl"], scopes)
case "@securitydefinitions.oauth2.implicit":
attrMap, scopes, err := extractSecurityAttribute(attribute, []string{"@authorizationurl"}, comments[i+1:])
if err != nil {
return err
}
securityMap[value] = securitySchemeOAuth2Implicit(attrMap["@authorizationurl"], scopes)
case "@securitydefinitions.oauth2.password":
attrMap, scopes, err := extractSecurityAttribute(attribute, []string{"@tokenurl"}, comments[i+1:])
if err != nil {
return err
}
securityMap[value] = securitySchemeOAuth2Password(attrMap["@tokenurl"], scopes)
case "@securitydefinitions.oauth2.accesscode":
attrMap, scopes, err := extractSecurityAttribute(attribute, []string{"@tokenurl", "@authorizationurl"}, comments[i+1:])
if err != nil {
return err
}
securityMap[value] = securitySchemeOAuth2AccessToken(attrMap["@authorizationurl"], attrMap["@tokenurl"], scopes)
case "@query.collection.format":
parser.collectionFormatInQuery = value
default:
prefixExtension := "@x-"
if len(attribute) > 5 { // Prefix extension + 1 char + 1 space + 1 char
if attribute[:len(prefixExtension)] == prefixExtension {
var valueJSON interface{}
split := strings.SplitAfter(commentLine, attribute+" ")
if len(split) < 2 {
return fmt.Errorf("annotation %s need a value", attribute)
}
extensionName := "x-" + strings.SplitAfter(attribute, prefixExtension)[1]
if err := json.Unmarshal([]byte(split[1]), &valueJSON); err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
}
parser.swagger.AddExtension(extensionName, valueJSON)
}
}
}
previousAttribute = attribute
}
}
if len(securityMap) > 0 {
parser.swagger.SecurityDefinitions = securityMap
}
return nil
}
func isGeneralAPIComment(comment *ast.CommentGroup) bool {
for _, commentLine := range strings.Split(comment.Text(), "\n") {
attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
switch attribute {
// The @summary, @router, @success,@failure annotation belongs to Operation
case "@summary", "@router", "@success", "@failure":
return false
}
}
return true
}
func extractSecurityAttribute(context string, search []string, lines []string) (map[string]string, map[string]string, error) {
attrMap := map[string]string{}
scopes := map[string]string{}
for _, v := range lines {
securityAttr := strings.ToLower(strings.Split(v, " ")[0])
for _, findterm := range search {
if securityAttr == findterm {
attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
continue
}
}
isExists, err := isExistsScope(securityAttr)
if err != nil {
return nil, nil, err
}
if isExists {
scopScheme, err := getScopeScheme(securityAttr)
if err != nil {
return nil, nil, err
}
scopes[scopScheme] = v[len(securityAttr):]
}
// next securityDefinitions
if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
break
}
}
if len(attrMap) != len(search) {
return nil, nil, fmt.Errorf("%s is %v required", context, search)
}
return attrMap, scopes, nil
}
func securitySchemeOAuth2Application(tokenurl string, scopes map[string]string) *spec.SecurityScheme {
securityScheme := spec.OAuth2Application(tokenurl)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
return securityScheme
}
func securitySchemeOAuth2Implicit(authorizationurl string, scopes map[string]string) *spec.SecurityScheme {
securityScheme := spec.OAuth2Implicit(authorizationurl)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
return securityScheme
}
func securitySchemeOAuth2Password(tokenurl string, scopes map[string]string) *spec.SecurityScheme {
securityScheme := spec.OAuth2Password(tokenurl)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
return securityScheme
}
func securitySchemeOAuth2AccessToken(authorizationurl, tokenurl string, scopes map[string]string) *spec.SecurityScheme {
securityScheme := spec.OAuth2AccessToken(authorizationurl, tokenurl)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
return securityScheme
}
func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
filesInfos, err := ioutil.ReadDir(dirPath)
if err != nil {
return nil, err
}
for _, fileInfo := range filesInfos {
if fileInfo.IsDir() {
continue
}
fileName := fileInfo.Name()
if !strings.Contains(fileName, ".md") {
continue
}
if strings.Contains(fileName, tagName) {
fullPath := filepath.Join(dirPath, fileName)
commentInfo, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read markdown file %s error: %s ", fullPath, err)
}
return commentInfo, nil
}
}
return nil, fmt.Errorf("Unable to find markdown file for tag %s in the given directory", tagName)
}
func getScopeScheme(scope string) (string, error) {
scopeValue := scope[strings.Index(scope, "@scope."):]
if scopeValue == "" {
return "", fmt.Errorf("@scope is empty")
}
return scope[len("@scope."):], nil
}
func isExistsScope(scope string) (bool, error) {
s := strings.Fields(scope)
for _, v := range s {
if strings.Contains(v, "@scope.") {
if strings.Contains(v, ",") {
return false, fmt.Errorf("@scope can't use comma(,) get=" + v)
}
}
}
return strings.Contains(scope, "@scope."), nil
}
// getSchemes parses swagger schemes for given commentLine
func getSchemes(commentLine string) []string {
attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
return strings.Split(strings.TrimSpace(commentLine[len(attribute):]), " ")
}
// ParseRouterAPIInfo parses router api info for given astFile
func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) error {
for _, astDescription := range astFile.Decls {
switch astDeclaration := astDescription.(type) {
case *ast.FuncDecl:
if astDeclaration.Doc != nil && astDeclaration.Doc.List != nil {
operation := NewOperation() //for per 'function' comment, create a new 'Operation' object
operation.parser = parser
for _, comment := range astDeclaration.Doc.List {
if err := operation.ParseComment(comment.Text, astFile); err != nil {
return fmt.Errorf("ParseComment error in file %s :%+v", fileName, err)
}
}
var pathItem spec.PathItem
var ok bool
if pathItem, ok = parser.swagger.Paths.Paths[operation.Path]; !ok {
pathItem = spec.PathItem{}
}
switch strings.ToUpper(operation.HTTPMethod) {
case http.MethodGet:
pathItem.Get = &operation.Operation
case http.MethodPost:
pathItem.Post = &operation.Operation
case http.MethodDelete:
pathItem.Delete = &operation.Operation
case http.MethodPut:
pathItem.Put = &operation.Operation
case http.MethodPatch:
pathItem.Patch = &operation.Operation
case http.MethodHead:
pathItem.Head = &operation.Operation
case http.MethodOptions:
pathItem.Options = &operation.Operation
}
parser.swagger.Paths.Paths[operation.Path] = pathItem
}
}
}
return nil
}
// ParseType parses type info for given astFile.
func (parser *Parser) ParseType(astFile *ast.File) {
if _, ok := parser.TypeDefinitions[astFile.Name.String()]; !ok {
parser.TypeDefinitions[astFile.Name.String()] = make(map[string]*ast.TypeSpec)
}
for _, astDeclaration := range astFile.Decls {
if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE {
for _, astSpec := range generalDeclaration.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
typeName := fmt.Sprintf("%v", typeSpec.Type)
// check if its a custom primitive type
if IsGolangPrimitiveType(typeName) {
var typeSpecFullName = fmt.Sprintf("%s.%s", astFile.Name.String(), typeSpec.Name.String())
parser.CustomPrimitiveTypes[typeSpecFullName] = TransToValidSchemeType(typeName)
} else {
parser.TypeDefinitions[astFile.Name.String()][typeSpec.Name.String()] = typeSpec
}
}
}
}
}
for _, importSpec := range astFile.Imports {
if importSpec.Name == nil {
continue
}
alias := importSpec.Name.Name
if _, ok := parser.ImportAliases[alias]; !ok {
parser.ImportAliases[alias] = make(map[string]*ast.ImportSpec)
}
importParts := strings.Split(strings.Trim(importSpec.Path.Value, "\""), "/")
importPkgName := importParts[len(importParts)-1]
parser.ImportAliases[alias][importPkgName] = importSpec
}
}
func (parser *Parser) isInStructStack(refTypeName string) bool {
for _, structName := range parser.structStack {
if refTypeName == structName {
return true
}
}
return false
}
// parseDefinitions parses Swagger Api definitions.
func (parser *Parser) parseDefinitions() error {
// sort the typeNames so that parsing definitions is deterministic
typeNames := make([]string, 0, len(parser.registerTypes))
for refTypeName := range parser.registerTypes {
typeNames = append(typeNames, refTypeName)
}
sort.Strings(typeNames)
for _, refTypeName := range typeNames {
typeSpec := parser.registerTypes[refTypeName]
ss := strings.Split(refTypeName, ".")
pkgName := ss[0]
parser.structStack = nil
if err := parser.ParseDefinition(pkgName, typeSpec.Name.Name, typeSpec); err != nil {
return err
}
}
return nil
}
// ParseDefinition parses given type spec that corresponds to the type under
// given name and package, and populates swagger schema definitions registry
// with a schema for the given type
func (parser *Parser) ParseDefinition(pkgName, typeName string, typeSpec *ast.TypeSpec) error {
refTypeName := TypeDocName(pkgName, typeSpec)
if typeSpec == nil {
Println("Skipping '" + refTypeName + "', pkg '" + pkgName + "' not found, try add flag --parseDependency or --parseVendor.")
return nil
}
if _, isParsed := parser.swagger.Definitions[refTypeName]; isParsed {
Println("Skipping '" + refTypeName + "', already parsed.")
return nil
}
if parser.isInStructStack(refTypeName) {
Println("Skipping '" + refTypeName + "', recursion detected.")
return nil
}
parser.structStack = append(parser.structStack, refTypeName)
Println("Generating " + refTypeName)
schema, err := parser.parseTypeExpr(pkgName, typeName, typeSpec.Type)
if err != nil {
return err
}
parser.swagger.Definitions[refTypeName] = *schema
return nil
}
func (parser *Parser) collectRequiredFields(pkgName string, properties map[string]spec.Schema, extraRequired []string) (requiredFields []string) {
// created sorted list of properties keys so when we iterate over them it's deterministic
ks := make([]string, 0, len(properties))
for k := range properties {
ks = append(ks, k)
}
sort.Strings(ks)
requiredFields = make([]string, 0)
// iterate over keys list instead of map to avoid the random shuffle of the order that go does for maps
for _, k := range ks {
prop := properties[k]
// todo find the pkgName of the property type
tname := prop.SchemaProps.Type[0]
if _, ok := parser.TypeDefinitions[pkgName][tname]; ok {
tspec := parser.TypeDefinitions[pkgName][tname]
parser.ParseDefinition(pkgName, tname, tspec)
}
requiredFields = append(requiredFields, prop.SchemaProps.Required...)
properties[k] = prop
}
if extraRequired != nil {
requiredFields = append(requiredFields, extraRequired...)
}
sort.Strings(requiredFields)
return
}
func fullTypeName(pkgName, typeName string) string {
if pkgName != "" {
return pkgName + "." + typeName
}
return typeName
}
// parseTypeExpr parses given type expression that corresponds to the type under
// given name and package, and returns swagger schema for it.
func (parser *Parser) parseTypeExpr(pkgName, typeName string, typeExpr ast.Expr) (*spec.Schema, error) {
switch expr := typeExpr.(type) {
// type Foo struct {...}
case *ast.StructType:
if typedef, ok := parser.TypeDefinitions[pkgName][typeName]; ok {
refTypeName := TypeDocName(pkgName, typedef)
if schema, isParsed := parser.swagger.Definitions[refTypeName]; isParsed {
return &schema, nil
}
}
return parser.parseStruct(pkgName, expr.Fields)
// type Foo Baz
case *ast.Ident:
if IsGolangPrimitiveType(expr.Name) {
return &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: spec.StringOrArray{TransToValidSchemeType(expr.Name)},
},
}, nil
}
refTypeName := fullTypeName(pkgName, expr.Name)
if typedef, ok := parser.TypeDefinitions[pkgName][expr.Name]; ok {
refTypeName = TypeDocName(pkgName, typedef)
if _, isParsed := parser.swagger.Definitions[refTypeName]; !isParsed {
parser.ParseDefinition(pkgName, expr.Name, typedef)
}
}
return RefSchema(refTypeName), nil
// type Foo *Baz
case *ast.StarExpr:
return parser.parseTypeExpr(pkgName, typeName, expr.X)
// type Foo []Baz
case *ast.ArrayType:
itemSchema, err := parser.parseTypeExpr(pkgName, "", expr.Elt)
if err != nil {
return &spec.Schema{}, err
}
return spec.ArrayProperty(itemSchema), nil
// type Foo pkg.Bar
case *ast.SelectorExpr:
if xIdent, ok := expr.X.(*ast.Ident); ok {
return parser.parseTypeExpr(xIdent.Name, expr.Sel.Name, expr.Sel)
}
// type Foo map[string]Bar
case *ast.MapType:
if _, ok := expr.Value.(*ast.InterfaceType); ok {
return spec.MapProperty(nil), nil
}
schema, err := parser.parseTypeExpr(pkgName, "", expr.Value)
if err != nil {
return &spec.Schema{}, err
}
return spec.MapProperty(schema), nil
// ...
default:
Printf("Type definition of type '%T' is not supported yet. Using 'object' instead.\n", typeExpr)
}
return PrimitiveSchema("object"), nil
}
func (parser *Parser) parseStruct(pkgName string, fields *ast.FieldList) (*spec.Schema, error) {
extraRequired := make([]string, 0)
properties := make(map[string]spec.Schema)
for _, field := range fields.List {
fieldProps, requiredFromAnon, err := parser.parseStructField(pkgName, field)
if err != nil {
return &spec.Schema{}, err
}
extraRequired = append(extraRequired, requiredFromAnon...)
for k, v := range fieldProps {
properties[k] = v
}
}
// collect requireds from our properties and anonymous fields
required := parser.collectRequiredFields(pkgName, properties, extraRequired)
// unset required from properties because we've collected them
for k, prop := range properties {
prop.SchemaProps.Required = make([]string, 0)
properties[k] = prop
}
return &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
Properties: properties,
Required: required,
}}, nil
}
type structField struct {
name string
desc string
schemaType string
arrayType string
formatType string
isRequired bool
readOnly bool
crossPkg string
exampleValue interface{}
maximum *float64
minimum *float64
maxLength *int64
minLength *int64
enums []interface{}
defaultValue interface{}
extensions map[string]interface{}
}
func (sf *structField) toStandardSchema() *spec.Schema {
required := make([]string, 0)
if sf.isRequired {
required = append(required, sf.name)
}
return &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{sf.schemaType},
Description: sf.desc,
Format: sf.formatType,
Required: required,
Maximum: sf.maximum,
Minimum: sf.minimum,
MaxLength: sf.maxLength,
MinLength: sf.minLength,
Enum: sf.enums,
Default: sf.defaultValue,
},
SwaggerSchemaProps: spec.SwaggerSchemaProps{
Example: sf.exampleValue,
ReadOnly: sf.readOnly,
},
VendorExtensible: spec.VendorExtensible{
Extensions: sf.extensions,
},
}
}
func (parser *Parser) parseStructField(pkgName string, field *ast.Field) (map[string]spec.Schema, []string, error) {
properties := map[string]spec.Schema{}
if field.Names == nil {
fullTypeName, err := getFieldType(field.Type)
if err != nil {
return properties, []string{}, nil
}
typeName := fullTypeName
if splits := strings.Split(fullTypeName, "."); len(splits) > 1 {
pkgName = splits[0]
typeName = splits[1]
}
typeSpec := parser.TypeDefinitions[pkgName][typeName]
if typeSpec == nil {
// Check if the pkg name is an alias and try to define type spec using real package name
if aliases, ok := parser.ImportAliases[pkgName]; ok {
for alias := range aliases {
typeSpec = parser.TypeDefinitions[alias][typeName]
if typeSpec != nil {
break
}
}
}
}
if typeSpec != nil {
schema, err := parser.parseTypeExpr(pkgName, typeName, typeSpec.Type)
if err != nil {
return properties, []string{}, err
}
schemaType := "unknown"
if len(schema.SchemaProps.Type) > 0 {
schemaType = schema.SchemaProps.Type[0]
}
switch schemaType {
case "object":
for k, v := range schema.SchemaProps.Properties {
properties[k] = v
}
case "array":
properties[typeName] = *schema
default:
Printf("Can't extract properties from a schema of type '%s'", schemaType)
}
return properties, schema.SchemaProps.Required, nil
}
return properties, nil, nil
}
structField, err := parser.parseField(pkgName, field)
if err != nil {
return properties, nil, err
}
if structField.name == "" {
return properties, nil, nil
}
// TODO: find package of schemaType and/or arrayType
if structField.crossPkg != "" {
pkgName = structField.crossPkg
}
fillObject := func(src, dest interface{}) error {
bin, err := json.Marshal(src)
if err != nil {
return err
}
return json.Unmarshal(bin, dest)
}
//for spec.Schema have implemented json.Marshaler, here in another way to convert
fillSchema := func(src, dest *spec.Schema) error {
err = fillObject(&src.SchemaProps, &dest.SchemaProps)
if err != nil {
return err
}
err = fillObject(&src.SwaggerSchemaProps, &dest.SwaggerSchemaProps)
if err != nil {
return err
}
return fillObject(&src.VendorExtensible, &dest.VendorExtensible)
}
if typeSpec, ok := parser.TypeDefinitions[pkgName][structField.schemaType]; ok { // user type field
// write definition if not yet present
err = parser.ParseDefinition(pkgName, structField.schemaType, typeSpec)
if err != nil {
return properties, nil, err
}
required := make([]string, 0)
if structField.isRequired {
required = append(required, structField.name)
}
properties[structField.name] = spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"}, // to avoid swagger validation error
Description: structField.desc,
Required: required,
Ref: spec.Ref{
Ref: jsonreference.MustCreateRef("#/definitions/" + TypeDocName(pkgName, typeSpec)),
},
},
SwaggerSchemaProps: spec.SwaggerSchemaProps{
ReadOnly: structField.readOnly,
},
}
} else if structField.schemaType == "array" { // array field type
// if defined -- ref it
if typeSpec, ok := parser.TypeDefinitions[pkgName][structField.arrayType]; ok { // user type in array
parser.ParseDefinition(pkgName, structField.arrayType,
parser.TypeDefinitions[pkgName][structField.arrayType])
required := make([]string, 0)
if structField.isRequired {
required = append(required, structField.name)
}
schema := spec.ArrayProperty(RefSchema(TypeDocName(pkgName, typeSpec)))
schema.Description = structField.desc
schema.Required = required
schema.ReadOnly = structField.readOnly
properties[structField.name] = *schema
} else if structField.arrayType == "object" {
// Anonymous struct
if astTypeArray, ok := field.Type.(*ast.ArrayType); ok { // if array
props := make(map[string]spec.Schema)
if expr, ok := astTypeArray.Elt.(*ast.StructType); ok {
for _, field := range expr.Fields.List {
var fieldProps map[string]spec.Schema
fieldProps, _, err = parser.parseStructField(pkgName, field)
if err != nil {
return properties, nil, err
}
for k, v := range fieldProps {
props[k] = v
}
}
properties[structField.name] = spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{structField.schemaType},
Description: structField.desc,
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
Properties: props,
},
},
},
},
SwaggerSchemaProps: spec.SwaggerSchemaProps{
ReadOnly: structField.readOnly,
},
}
} else {
schema, _ := parser.parseTypeExpr(pkgName, "", astTypeArray.Elt)
schema = spec.ArrayProperty(schema)
schema.Description = structField.desc
schema.ReadOnly = structField.readOnly
properties[structField.name] = *schema
}
}
} else if structField.arrayType == "array" {
if astTypeArray, ok := field.Type.(*ast.ArrayType); ok {
schema, _ := parser.parseTypeExpr(pkgName, "", astTypeArray.Elt)
schema = spec.ArrayProperty(schema)
schema.Description = structField.desc
schema.ReadOnly = structField.readOnly
properties[structField.name] = *schema
}
} else {
// standard type in array
required := make([]string, 0)
if structField.isRequired {