This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
forked from launchdarkly/goas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
1899 lines (1733 loc) · 54.9 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 main
import (
"encoding/json"
"errors"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"io/ioutil"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"unicode"
"github.com/iancoleman/orderedmap"
module "golang.org/x/mod/modfile"
)
type parser struct {
ModulePath string
ModuleName string
MainFilePath string
HandlerPath string
GoModFilePath string
GoModCachePath string
GoRootSrcPath string
OpenAPI OpenAPIObject
CorePkgs map[string]bool
KnownPkgs []pkg
KnownNamePkg map[string]*pkg
KnownPathPkg map[string]*pkg
KnownIDSchema map[string]*SchemaObject
TypeSpecs map[string]map[string]*ast.TypeSpec
PkgPathAstPkgCache map[string]map[string]*ast.Package
PkgNameImportedPkgAlias map[string]map[string][]string
// map of package name to type name to schema name
ApiSchemaNames map[string]map[string]string
Debug bool
OmitPackages bool
ShowHidden bool
FileRefPath string
}
type pkg struct {
Name string
Path string
}
var (
objectType = "object"
stringType = "string"
arrayType = "array"
)
func newParser(modulePath, mainFilePath, handlerPath, descriptionRefPath string, debug, omitPackages, showHidden bool) (*parser, error) {
p := &parser{
CorePkgs: map[string]bool{},
KnownPkgs: []pkg{},
KnownNamePkg: map[string]*pkg{},
KnownPathPkg: map[string]*pkg{},
KnownIDSchema: map[string]*SchemaObject{},
TypeSpecs: map[string]map[string]*ast.TypeSpec{},
PkgPathAstPkgCache: map[string]map[string]*ast.Package{},
PkgNameImportedPkgAlias: map[string]map[string][]string{},
Debug: debug,
OmitPackages: omitPackages,
ShowHidden: showHidden,
FileRefPath: descriptionRefPath,
}
p.OpenAPI.OpenAPI = OpenAPIVersion
p.OpenAPI.Paths = make(PathsObject)
p.OpenAPI.Security = []map[string][]string{}
p.OpenAPI.Components.Schemas = make(map[string]*SchemaObject)
p.OpenAPI.Components.SecuritySchemes = map[string]*SecuritySchemeObject{}
// check modulePath is exist
modulePath, _ = filepath.Abs(modulePath)
moduleInfo, err := os.Stat(modulePath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("cannot get information of %s: %s", modulePath, err)
}
if !moduleInfo.IsDir() {
return nil, fmt.Errorf("modulePath should be a directory")
}
p.ModulePath = modulePath
p.debugf("module path: %s", p.ModulePath)
// check go.mod file is exist
goModFilePath := filepath.Join(modulePath, "go.mod")
goModFileInfo, err := os.Stat(goModFilePath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("cannot get information of %s: %s", goModFilePath, err)
}
if goModFileInfo.IsDir() {
return nil, fmt.Errorf("%s should be a file", goModFilePath)
}
p.GoModFilePath = goModFilePath
p.debugf("go.mod file path: %s", p.GoModFilePath)
// check mainFilePath is exist
if mainFilePath == "" {
fns, err := filepath.Glob(filepath.Join(modulePath, "*.go"))
if err != nil {
return nil, err
}
for _, fn := range fns {
if isMainFile(fn) {
mainFilePath = fn
break
}
}
} else {
mainFileInfo, err := os.Stat(mainFilePath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("cannot get information of %s: %s", mainFilePath, err)
}
if mainFileInfo.IsDir() {
return nil, fmt.Errorf("mainFilePath should not be a directory")
}
}
p.MainFilePath = mainFilePath
p.debugf("main file path: %s", p.MainFilePath)
// get module name from go.mod file
moduleName := getModuleNameFromGoMod(goModFilePath)
if moduleName == "" {
return nil, fmt.Errorf("cannot get module name from %s", goModFileInfo)
}
p.ModuleName = moduleName
p.debugf("module name: %s", p.ModuleName)
// check go module cache path is exist ($GOPATH/pkg/mod)
goPath := os.Getenv("GOPATH")
// If GOPATH contains multiple paths use the last
// TODO: choosing the last is arbritrary; handle this better
goPathParts := strings.Split(goPath, ":")
goPath = goPathParts[len(goPathParts)-1]
if goPath == "" {
user, err := user.Current()
if err != nil {
return nil, fmt.Errorf("cannot get current user: %s", err)
}
goPath = filepath.Join(user.HomeDir, "go")
}
goModCachePath := filepath.Join(goPath, "pkg", "mod")
goModCacheInfo, err := os.Stat(goModCachePath)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("could not find goModCachePath: %w", err)
}
return nil, fmt.Errorf("cannot get information of %s: %s", goModCachePath, err)
}
if !goModCacheInfo.IsDir() {
return nil, fmt.Errorf("%s should be a directory", goModCachePath)
}
p.GoModCachePath = goModCachePath
p.debugf("go module cache path: %s", p.GoModCachePath)
goRoot := runtime.GOROOT()
if goRoot == "" {
return nil, fmt.Errorf("cannot get GOROOT")
}
goRootSrcPath := filepath.Join(goRoot, "src")
_, err = os.Stat(goRootSrcPath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("cannot get information of %s: %s", goRootSrcPath, err)
}
if !goModCacheInfo.IsDir() {
return nil, fmt.Errorf("%s should be a directory", goRootSrcPath)
}
p.GoRootSrcPath = goRootSrcPath
p.debugf("go root src path: %s", p.GoRootSrcPath)
if handlerPath != "" {
handlerPath, _ = filepath.Abs(handlerPath)
_, err := os.Stat(handlerPath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("cannot get information of %s: %s", handlerPath, err)
}
}
p.HandlerPath = handlerPath
p.debugf("handler path: %s", p.HandlerPath)
if p.ApiSchemaNames == nil {
p.ApiSchemaNames = map[string]map[string]string{}
}
return p, nil
}
func (p *parser) parse() error {
// parse basic info
err := p.parseEntryPoint()
if err != nil {
return err
}
// parse sub-package
err = p.parseModule()
if err != nil {
return err
}
// parse go.mod info
err = p.parseGoMod()
if err != nil {
return err
}
// parse core packages
err = p.parseGoRoot()
if err != nil {
return err
}
// parse APIs info
err = p.parseAPIs()
if err != nil {
return err
}
return nil
}
func (p *parser) CreateOASFile(path string) error {
if err := p.parse(); err != nil {
return err
}
conflicts := p.validateSchemaNames()
if len(conflicts) > 0 {
return fmt.Errorf("conflicting schema names - %s", strings.Join(conflicts, ", "))
}
fd, err := os.Create(path)
if err != nil {
return fmt.Errorf("can not create the file %s: %v", path, err)
}
defer fd.Close()
// for descriptions specified with $refs, pull that content in and embed it directly
// TODO may be a good idea to make this optional via clarg
err = p.explodeRefs()
if err != nil {
return err
}
output, err := json.MarshalIndent(p.OpenAPI, "", " ")
if err != nil {
return err
}
_, err = fd.WriteString(string(output))
return err
}
func (p *parser) validateSchemaNames() []string {
potentialConflictsMap := map[string][]string{}
for pkgName, schemaNames := range p.ApiSchemaNames {
for typeName, schemaName := range schemaNames {
potentialConflictsMap[schemaName] = append(potentialConflictsMap[schemaName], pkgName+"#"+typeName)
}
}
conflicts := []string{}
for schemaName := range potentialConflictsMap {
if len(potentialConflictsMap[schemaName]) > 1 {
conflicts = append(conflicts, schemaName+": "+strings.Join(potentialConflictsMap[schemaName], " | "))
}
}
return conflicts
}
func (p *parser) explodeRefs() error {
if p.OpenAPI.Info.Description != nil {
desc, err := fetchRef(p.FileRefPath, p.OpenAPI.Info.Description.Value)
if err != nil {
return err
}
p.OpenAPI.Info.Description.Value = desc
}
for i, tag := range p.OpenAPI.Tags {
if tag.Description == nil {
continue
}
desc, err := fetchRef(p.FileRefPath, tag.Description.Value)
if err != nil {
return err
}
p.OpenAPI.Tags[i].Description.Value = desc
}
return nil
}
func fetchRef(filePath, description string) (string, error) {
if !strings.HasPrefix(description, "$ref:") {
return description, nil
}
url := description[5:]
if strings.HasPrefix(url, "file://") {
descPath := strings.Join([]string{filePath, url[7:]}, "/")
dat, err := ioutil.ReadFile(descPath)
if err != nil {
return "", err
}
return string(dat), nil
}
// else assume http and fetch
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func (p *parser) parseEntryPoint() error {
fileTree, err := goparser.ParseFile(token.NewFileSet(), p.MainFilePath, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("can not parse general API information: %v", err)
}
// Security Scopes are defined at a different level in the hierarchy as where they need to end up in the OpenAPI structure,
// so a temporary list is needed.
oauthScopes := make(map[string]map[string]string, 0)
if fileTree.Comments != nil {
for i := range fileTree.Comments {
for _, comment := range strings.Split(fileTree.Comments[i].Text(), "\n") {
attribute := strings.ToLower(strings.Split(comment, " ")[0])
if len(attribute) == 0 || attribute[0] != '@' {
continue
}
value := strings.TrimSpace(comment[len(attribute):])
if len(value) == 0 {
continue
}
// p.debug(attribute, value)
switch attribute {
case "@version":
p.OpenAPI.Info.Version = value
case "@title":
p.OpenAPI.Info.Title = value
case "@description":
if p.OpenAPI.Info.Description == nil {
p.OpenAPI.Info.Description = &ReffableString{}
}
p.OpenAPI.Info.Description.Value = value
case "@termsofserviceurl":
p.OpenAPI.Info.TermsOfService = value
case "@contactname":
if p.OpenAPI.Info.Contact == nil {
p.OpenAPI.Info.Contact = &ContactObject{}
}
p.OpenAPI.Info.Contact.Name = value
case "@contactemail":
if p.OpenAPI.Info.Contact == nil {
p.OpenAPI.Info.Contact = &ContactObject{}
}
p.OpenAPI.Info.Contact.Email = value
case "@contacturl":
if p.OpenAPI.Info.Contact == nil {
p.OpenAPI.Info.Contact = &ContactObject{}
}
p.OpenAPI.Info.Contact.URL = value
case "@licensename":
if p.OpenAPI.Info.License == nil {
p.OpenAPI.Info.License = &LicenseObject{}
}
p.OpenAPI.Info.License.Name = value
case "@licenseurl":
if p.OpenAPI.Info.License == nil {
p.OpenAPI.Info.License = &LicenseObject{}
}
p.OpenAPI.Info.License.URL = value
case "@server":
fields := strings.Split(value, " ")
s := ServerObject{URL: fields[0], Description: value[len(fields[0]):]}
p.OpenAPI.Servers = append(p.OpenAPI.Servers, s)
case "@security":
fields := strings.Split(value, " ")
security := map[string][]string{
fields[0]: fields[1:],
}
p.OpenAPI.Security = append(p.OpenAPI.Security, security)
case "@securityscheme":
fields := strings.Split(value, " ")
var scheme *SecuritySchemeObject
if strings.Contains(fields[1], "oauth2") {
if oauthScheme, ok := p.OpenAPI.Components.SecuritySchemes[fields[0]]; ok {
scheme = oauthScheme
} else {
scheme = &SecuritySchemeObject{
Type: "oauth2",
OAuthFlows: &SecuritySchemeOauthObject{},
}
}
}
if scheme == nil {
scheme = &SecuritySchemeObject{
Type: fields[1],
}
}
switch fields[1] {
case "http":
scheme.Scheme = fields[2]
scheme.Description = strings.Join(fields[3:], " ")
case "apiKey":
scheme.In = fields[2]
scheme.Name = fields[3]
scheme.Description = strings.Join(fields[4:], "")
case "openIdConnect":
scheme.OpenIdConnectUrl = fields[2]
scheme.Description = strings.Join(fields[3:], " ")
case "oauth2AuthCode":
scheme.OAuthFlows.AuthorizationCode = &SecuritySchemeOauthFlowObject{
AuthorizationUrl: fields[2],
TokenUrl: fields[3],
Scopes: make(map[string]string, 0),
}
case "oauth2Implicit":
scheme.OAuthFlows.Implicit = &SecuritySchemeOauthFlowObject{
AuthorizationUrl: fields[2],
Scopes: make(map[string]string, 0),
}
case "oauth2ResourceOwnerCredentials":
scheme.OAuthFlows.ResourceOwnerPassword = &SecuritySchemeOauthFlowObject{
TokenUrl: fields[2],
Scopes: make(map[string]string, 0),
}
case "oauth2ClientCredentials":
scheme.OAuthFlows.ClientCredentials = &SecuritySchemeOauthFlowObject{
TokenUrl: fields[2],
Scopes: make(map[string]string, 0),
}
}
p.OpenAPI.Components.SecuritySchemes[fields[0]] = scheme
case "@securityscope":
fields := strings.Split(value, " ")
if _, ok := oauthScopes[fields[0]]; !ok {
oauthScopes[fields[0]] = make(map[string]string, 0)
}
oauthScopes[fields[0]][fields[1]] = strings.Join(fields[2:], " ")
case "@tags":
t, err := parseTags(comment)
if err != nil {
return err
}
p.OpenAPI.Tags = append(p.OpenAPI.Tags, *t)
}
}
}
}
// Apply security scopes to their security schemes
for scheme, _ := range p.OpenAPI.Components.SecuritySchemes {
if p.OpenAPI.Components.SecuritySchemes[scheme].Type == "oauth2" {
if scopes, ok := oauthScopes[scheme]; ok {
p.OpenAPI.Components.SecuritySchemes[scheme].OAuthFlows.ApplyScopes(scopes)
}
}
}
if len(p.OpenAPI.Servers) < 1 {
p.OpenAPI.Servers = append(p.OpenAPI.Servers, ServerObject{URL: "/", Description: "Default Server URL"})
}
if p.OpenAPI.Info.Title == "" {
return fmt.Errorf("info.title cannot not be empty")
}
if p.OpenAPI.Info.Version == "" {
return fmt.Errorf("info.version cannot not be empty")
}
for i := range p.OpenAPI.Servers {
if p.OpenAPI.Servers[i].URL == "" {
return fmt.Errorf("servers[%d].url cannot not be empty", i)
}
}
return nil
}
func parseTags(comment string) (*TagDefinition, error) {
re := regexp.MustCompile("\"([^\"]*)\"")
matches := re.FindAllStringSubmatch(comment, -1)
if len(matches) == 0 || len(matches[0]) == 1 {
return nil, fmt.Errorf("Expected: @Tags \"<name>\" [\"<description>\"] Received: %s", comment)
}
tag := TagDefinition{Name: matches[0][1]}
if len(matches) > 1 {
tag.Description = &ReffableString{Value: matches[1][1]}
}
return &tag, nil
}
func (p *parser) parseModule() error {
walker := func(path string, info os.FileInfo, err error) error {
if info != nil && info.IsDir() {
if strings.HasPrefix(strings.Trim(strings.TrimPrefix(path, p.ModulePath), "/"), ".git") {
return nil
}
fns, err := filepath.Glob(filepath.Join(path, "*.go"))
if len(fns) == 0 || err != nil {
return nil
}
// p.debug(path)
name := filepath.Join(p.ModuleName, strings.TrimPrefix(path, p.ModulePath))
name = filepath.ToSlash(name)
p.KnownPkgs = append(p.KnownPkgs, pkg{
Name: name,
Path: path,
})
p.KnownNamePkg[name] = &p.KnownPkgs[len(p.KnownPkgs)-1]
p.KnownPathPkg[path] = &p.KnownPkgs[len(p.KnownPkgs)-1]
}
return nil
}
filepath.Walk(p.ModulePath, walker)
return nil
}
func fixer(path, version string) (string, error) {
return version, nil
}
func (p *parser) parseGoMod() error {
b, err := ioutil.ReadFile(p.GoModFilePath)
if err != nil {
return err
}
goMod, err := module.ParseLax(p.GoModFilePath, b, fixer)
if err != nil {
return err
}
for i := range goMod.Require {
pathRunes := []rune{}
for _, v := range goMod.Require[i].Mod.Path {
if !unicode.IsUpper(v) {
pathRunes = append(pathRunes, v)
continue
}
pathRunes = append(pathRunes, '!')
pathRunes = append(pathRunes, unicode.ToLower(v))
}
pkgName := goMod.Require[i].Mod.Path
pkgPath := filepath.Join(p.GoModCachePath, string(pathRunes)+"@"+goMod.Require[i].Mod.Version)
pkgName = filepath.ToSlash(pkgName)
p.KnownPkgs = append(p.KnownPkgs, pkg{
Name: pkgName,
Path: pkgPath,
})
p.KnownNamePkg[pkgName] = &p.KnownPkgs[len(p.KnownPkgs)-1]
p.KnownPathPkg[pkgPath] = &p.KnownPkgs[len(p.KnownPkgs)-1]
walker := func(path string, info os.FileInfo, err error) error {
if info != nil && info.IsDir() {
if strings.HasPrefix(strings.Trim(strings.TrimPrefix(path, p.ModulePath), "/"), ".git") {
return nil
}
fns, err := filepath.Glob(filepath.Join(path, "*.go"))
if len(fns) == 0 || err != nil {
return nil
}
// p.debug(path)
name := filepath.Join(pkgName, strings.TrimPrefix(path, pkgPath))
name = filepath.ToSlash(name)
p.KnownPkgs = append(p.KnownPkgs, pkg{
Name: name,
Path: path,
})
p.KnownNamePkg[name] = &p.KnownPkgs[len(p.KnownPkgs)-1]
p.KnownPathPkg[path] = &p.KnownPkgs[len(p.KnownPkgs)-1]
}
return nil
}
filepath.Walk(pkgPath, walker)
}
if p.Debug {
for i := range p.KnownPkgs {
p.debug(p.KnownPkgs[i].Name, "->", p.KnownPkgs[i].Path)
}
}
return nil
}
func (p *parser) parseGoRoot() error {
walker := func(path string, info os.FileInfo, err error) error {
if info != nil && info.IsDir() {
fns, err := filepath.Glob(filepath.Join(path, "*.go"))
if len(fns) == 0 || err != nil {
return nil
}
name := strings.TrimPrefix(filepath.ToSlash(strings.TrimPrefix(path, p.GoRootSrcPath)), "/")
p.CorePkgs[name] = true
}
return nil
}
filepath.Walk(p.GoRootSrcPath, walker)
return nil
}
func (p *parser) getPkgAst(pkgPath string) (map[string]*ast.Package, error) {
if cache, ok := p.PkgPathAstPkgCache[pkgPath]; ok {
return cache, nil
}
ignoreFileFilter := func(info os.FileInfo) bool {
name := info.Name()
return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go")
}
astPackages, err := goparser.ParseDir(token.NewFileSet(), pkgPath, ignoreFileFilter, goparser.ParseComments)
if err != nil {
return nil, err
}
p.PkgPathAstPkgCache[pkgPath] = astPackages
return astPackages, nil
}
func (p *parser) parseAPIs() error {
err := p.parseImportStatements()
if err != nil {
return err
}
err = p.parseTypeSpecs()
if err != nil {
return err
}
return p.parsePaths()
}
func (p *parser) parseImportStatements() error {
for i := range p.KnownPkgs {
pkgPath := p.KnownPkgs[i].Path
pkgName := p.KnownPkgs[i].Name
astPkgs, err := p.getPkgAst(pkgPath)
if err != nil {
p.debugf("parseImportStatements: parse of %s package cause error: %s\n", pkgPath, err)
continue
}
p.PkgNameImportedPkgAlias[pkgName] = map[string][]string{}
for _, astPackageKey := range sortedPackageKeys(astPkgs) {
astPackage := astPkgs[astPackageKey]
for _, astFileKey := range sortedFileKeys(astPackage.Files) {
astFile := astPackage.Files[astFileKey]
for _, astImport := range astFile.Imports {
importedPkgName := strings.Trim(astImport.Path.Value, "\"")
importedPkgAlias := ""
// _, known := p.KnownNamePkg[importedPkgName]
// if !known {
// p.debug("unknown", importedPkgName)
// }
if astImport.Name != nil && astImport.Name.Name != "." && astImport.Name.Name != "_" {
importedPkgAlias = astImport.Name.String()
// p.debug(importedPkgAlias, importedPkgName)
} else {
s := strings.Split(importedPkgName, "/")
importedPkgAlias = s[len(s)-1]
}
exist := false
for _, v := range p.PkgNameImportedPkgAlias[pkgName][importedPkgAlias] {
if v == importedPkgName {
exist = true
break
}
}
if !exist {
p.PkgNameImportedPkgAlias[pkgName][importedPkgAlias] = append(p.PkgNameImportedPkgAlias[pkgName][importedPkgAlias], importedPkgName)
}
}
}
}
}
return nil
}
func (p *parser) parseTypeSpecs() error {
for i := range p.KnownPkgs {
pkgPath := p.KnownPkgs[i].Path
pkgName := p.KnownPkgs[i].Name
_, ok := p.TypeSpecs[pkgName]
if !ok {
p.TypeSpecs[pkgName] = map[string]*ast.TypeSpec{}
}
astPkgs, err := p.getPkgAst(pkgPath)
if err != nil {
p.debugf("parseTypeSpecs: parse of %s package cause error: %s\n", pkgPath, err)
continue
}
for _, astPackageKey := range sortedPackageKeys(astPkgs) {
astPackage := astPkgs[astPackageKey]
for _, astFileKey := range sortedFileKeys(astPackage.Files) {
astFile := astPackage.Files[astFileKey]
for _, astDeclaration := range astFile.Decls {
if astGenDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && astGenDeclaration.Tok == token.TYPE {
// find type declaration
for _, astSpec := range astGenDeclaration.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
typeName := typeSpec.Name.String()
p.TypeSpecs[pkgName][typeName] = typeSpec
if astGenDeclaration.Doc != nil {
err := p.parseTypeAnnotations(pkgName, typeName, astGenDeclaration.Doc)
if err != nil {
return err
}
}
}
}
} else if astFuncDeclaration, ok := astDeclaration.(*ast.FuncDecl); ok {
// find type declaration in func, method
if astFuncDeclaration.Doc != nil && astFuncDeclaration.Doc.List != nil && astFuncDeclaration.Body != nil {
funcName := astFuncDeclaration.Name.String()
for _, astStmt := range astFuncDeclaration.Body.List {
if astDeclStmt, ok := astStmt.(*ast.DeclStmt); ok {
if astGenDeclaration, ok := astDeclStmt.Decl.(*ast.GenDecl); ok {
for _, astSpec := range astGenDeclaration.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
// type in func
if astFuncDeclaration.Recv == nil {
p.TypeSpecs[pkgName][strings.Join([]string{funcName, typeSpec.Name.String()}, "@")] = typeSpec
continue
}
// type in method
var recvTypeName string
if astStarExpr, ok := astFuncDeclaration.Recv.List[0].Type.(*ast.StarExpr); ok {
recvTypeName = fmt.Sprintf("%s", astStarExpr.X)
} else if astIdent, ok := astFuncDeclaration.Recv.List[0].Type.(*ast.Ident); ok {
recvTypeName = astIdent.String()
}
p.TypeSpecs[pkgName][strings.Join([]string{recvTypeName, funcName, typeSpec.Name.String()}, "@")] = typeSpec
}
}
}
}
}
}
}
}
}
}
}
return nil
}
func (p *parser) parseTypeAnnotations(pkgName string, typeName string, commentGroup *ast.CommentGroup) error {
for _, comment := range commentGroup.List {
fields := strings.Fields(strings.TrimLeft(comment.Text, "/"))
if len(fields) == 0 {
continue
}
switch strings.ToLower(fields[0]) {
case "@apischemaname":
if len(fields) < 2 {
return fmt.Errorf("expected \"// @ApiSchemaName {alias}\" received %s", comment.Text)
}
if p.ApiSchemaNames[pkgName] == nil {
p.ApiSchemaNames[pkgName] = map[string]string{}
}
p.ApiSchemaNames[pkgName][typeName] = fields[1]
}
}
return nil
}
func (p *parser) parsePaths() error {
for i := range p.KnownPkgs {
pkgPath := p.KnownPkgs[i].Path
pkgName := p.KnownPkgs[i].Name
astPkgs, err := p.getPkgAst(pkgPath)
if err != nil {
p.debugf("parsePaths: parse of %s package cause error: %s\n", pkgPath, err)
continue
}
for _, astPackageKey := range sortedPackageKeys(astPkgs) {
astPackage := astPkgs[astPackageKey]
for _, astFileKey := range sortedFileKeys(astPackage.Files) {
astFile := astPackage.Files[astFileKey]
for _, astDeclaration := range astFile.Decls {
if astFuncDeclaration, ok := astDeclaration.(*ast.FuncDecl); ok {
if astFuncDeclaration.Doc != nil && astFuncDeclaration.Doc.List != nil {
err = p.parseOperation(pkgPath, pkgName, astFuncDeclaration.Doc.List)
if err != nil {
return err
}
}
} else if astVarDeclaration, ok := astDeclaration.(*ast.GenDecl); ok {
if astVarDeclaration.Doc != nil && astVarDeclaration.Doc.List != nil {
err = p.parseOperation(pkgPath, pkgName, astVarDeclaration.Doc.List)
if err != nil {
return err
}
}
}
}
}
}
}
return nil
}
func isHidden(astComments []*ast.Comment, showHidden bool) bool {
for _, astComment := range astComments {
comment := strings.TrimSpace(strings.TrimLeft(astComment.Text, "/"))
if len(comment) == 0 {
// ignore empty lines
continue
}
attribute := strings.Fields(comment)[0]
if strings.ToLower(attribute) == "@hidden" && !showHidden {
return true
}
}
return false
}
func (p *parser) parseOperation(pkgPath, pkgName string, astComments []*ast.Comment) error {
operation := &OperationObject{
Responses: map[string]*ResponseObject{},
}
if !strings.HasPrefix(pkgPath, p.ModulePath) {
// ignore this pkgName
// p.debugf("parseOperation ignores %s", pkgPath)
return nil
} else if p.HandlerPath != "" && !strings.HasPrefix(pkgPath, p.HandlerPath) {
return nil
}
if isHidden(astComments, p.ShowHidden) {
return nil
}
var err error
var tagList []string
for _, tag := range p.OpenAPI.Tags {
tagList = append(tagList, tag.Name)
}
for _, astComment := range astComments {
comment := strings.TrimSpace(strings.TrimLeft(astComment.Text, "/"))
if len(comment) == 0 {
// ignore empty lines
continue
}
attribute := strings.Fields(comment)[0]
value := strings.TrimSpace(comment[len(attribute):])
switch strings.ToLower(attribute) {
case "@title":
operation.Summary = value
case "@description":
err = p.parseDescription(operation, value)
case "@operationid":
operation.OperationID = value
case "@param":
err = p.parseParamComment(pkgPath, pkgName, operation, value)
case "@success", "@failure":
err = p.parseResponseComment(pkgPath, pkgName, operation, value)
case "@resource", "@tag":
resource := value
if resource == "" {
resource = "others"
}
if !isInStringList(tagList, resource) && !p.ShowHidden {
err = fmt.Errorf("Could not find tag \"%s\" in the main list of tags", resource)
} else if !isInStringList(operation.Tags, resource) {
operation.Tags = append(operation.Tags, resource)
}
case "@route", "@router":
err = p.parseRouteComment(operation, comment)
}
if err != nil {
return err
}
}
return nil
}
func (p *parser) parseDescription(operation *OperationObject, description string) error {
desc, err := fetchRef(p.FileRefPath, description)
if err != nil {
return err
}
if operation.Description == "" {
operation.Description = desc
} else {
operation.Description = operation.Description + " " + desc
}
return nil
}
func (p *parser) parseParamComment(pkgPath, pkgName string, operation *OperationObject, comment string) error {
// {name} {in} {goType} {required} {description} {example (optional)}
// user body User true "Info of a user." "{\"name\":\"Bilbo\"}"
// f file ignored true "Upload a file."
re := regexp.MustCompile(`([-\w]+)[\s]+([\w]+)[\s]+([\w./\[\]\\(\\),]+)[\s]+([\w]+)[\s]+"([^"]+)"(?:[\s]+"((?:[^"\\]|\\")*)")?`)
matches := re.FindStringSubmatch(comment)
if len(matches) < 6 {
return fmt.Errorf("parseParamComment can not parse param comment \"%s\"", comment)
}
name := matches[1]
in := matches[2]
re = regexp.MustCompile(`\[\w*\]`)
goType := re.ReplaceAllString(matches[3], "[]")
required := false
switch strings.ToLower(matches[4]) {
case "true", "required":
required = true
}
description := matches[5]
// `file`, `form`
if in == "file" || in == "files" || in == "form" {
if operation.RequestBody == nil {
operation.RequestBody = &RequestBodyObject{
Content: map[string]*MediaTypeObject{
ContentTypeForm: &MediaTypeObject{
Schema: SchemaObject{
Type: &objectType,
Properties: orderedmap.New(),
},
},
},
Required: required,
}
}
if in == "file" {
operation.RequestBody.Content[ContentTypeForm].Schema.Properties.Set(name, &SchemaObject{
Type: &stringType,
Format: "binary",
Description: description,
})
} else if in == "files" {
operation.RequestBody.Content[ContentTypeForm].Schema.Properties.Set(name, &SchemaObject{
Type: &arrayType,
Items: &SchemaObject{
Type: &stringType,
Format: "binary",
},
Description: description,
})
} else if isGoTypeOASType(goType) {
localGoType := goTypesOASTypes[goType]
operation.RequestBody.Content[ContentTypeForm].Schema.Properties.Set(name, &SchemaObject{
Type: &localGoType,
Format: goTypesOASFormats[goType],
Description: description,