-
Notifications
You must be signed in to change notification settings - Fork 3
/
analyzer.go
403 lines (352 loc) · 8.71 KB
/
analyzer.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
package eapi
import (
"errors"
"fmt"
"go/ast"
"go/build"
"go/token"
"go/types"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/gotomicro/eapi/spec"
"github.com/knadh/koanf"
"github.com/samber/lo"
"golang.org/x/mod/modfile"
"golang.org/x/tools/go/packages"
)
type Analyzer struct {
routes APIs
globalEnv *Environment
plugins []Plugin
definitions Definitions
depends []string
k *koanf.Koanf
doc *spec.T
packages []*packages.Package
}
func NewAnalyzer(k *koanf.Koanf) *Analyzer {
a := &Analyzer{
routes: make(APIs, 0),
globalEnv: NewEnvironment(nil),
plugins: make([]Plugin, 0),
definitions: make(Definitions),
k: k,
}
components := spec.NewComponents()
components.Schemas = make(spec.Schemas)
doc := &spec.T{
OpenAPI: "3.0.3",
Info: &spec.Info{},
Components: components,
Paths: make(spec.Paths),
}
a.doc = doc
return a
}
func (a *Analyzer) Plugin(plugins ...Plugin) *Analyzer {
for _, plugin := range plugins {
err := plugin.Mount(a.k)
if err != nil {
panic(fmt.Sprintf("mount plugin '%s' failed. error: %s", plugin.Name(), err.Error()))
}
}
a.plugins = append(a.plugins, plugins...)
return a
}
func (a *Analyzer) Depends(pkgNames ...string) *Analyzer {
a.depends = append(a.depends, pkgNames...)
return a
}
func (a *Analyzer) Process(packagePath string) *Analyzer {
if len(a.plugins) <= 0 {
panic("must register plugin before processing")
}
packagePath, err := filepath.Abs(packagePath)
if err != nil {
panic("invalid package path: " + err.Error())
}
pkgList := a.load(packagePath)
for _, pkg := range pkgList {
a.definitions = make(Definitions)
for _, p := range pkg {
a.loadDefinitionsFromPkg(p, p.Module.Dir)
}
a.processPkg(pkg)
}
return a
}
func (a *Analyzer) APIs() *APIs {
return &a.routes
}
func (a *Analyzer) Doc() *spec.T {
return a.doc
}
func (a *Analyzer) analyze(ctx *Context, node ast.Node) {
for _, plugin := range a.plugins {
plugin.Analyze(ctx, node)
}
}
const entryPackageName = "command-line-arguments"
func (a *Analyzer) load(pkgPath string) [][]*packages.Package {
absPath, err := filepath.Abs(pkgPath)
if err != nil {
panic("invalid package path: " + pkgPath)
}
var pkgList []*build.Package
filepath.Walk(absPath, func(path string, info fs.FileInfo, err error) error {
if !info.IsDir() {
return nil
}
pkg, err := build.Default.ImportDir(path, build.ImportComment)
if err != nil {
var noGoErr = &build.NoGoError{}
if errors.As(err, &noGoErr) {
return nil
}
panic("import directory failed: " + err.Error())
}
pkgList = append(pkgList, pkg)
return filepath.SkipDir
})
config := &packages.Config{
Mode: packages.NeedName |
packages.NeedImports |
packages.NeedDeps |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedModule |
packages.NeedTypesInfo |
0,
BuildFlags: []string{},
Tests: false,
Dir: absPath,
}
var res [][]*packages.Package
for _, pkg := range pkgList {
var files []string
for _, filename := range append(pkg.GoFiles, pkg.CgoFiles...) {
files = append(files, filepath.Join(pkg.Dir, filename))
}
packs, err := packages.Load(config, files...)
if err != nil {
panic("load packages failed: " + err.Error())
}
// 前面的 packages.Load() 方法不能解析出以第一层的 Module
// 所以这里手动解析 go.mod
for _, p := range packs {
if p.Module != nil {
continue
}
module := a.parseGoModule(pkgPath)
if module == nil {
panic("failed to parse go.mod file in " + pkgPath)
}
p.Module = module
p.PkgPath = entryPackageName
p.ID = module.Path
}
res = append(res, packs)
}
return res
}
func (a *Analyzer) processPkg(pkgList []*packages.Package) {
for _, pkg := range pkgList {
moduleDir := pkg.Module.Dir
InspectPackage(pkg, func(pkg *packages.Package) bool {
if pkg.Module == nil || pkg.Module.Dir != moduleDir {
return false
}
ctx := a.context().Block().WithPackage(pkg)
for _, file := range pkg.Syntax {
a.processFile(ctx.Block().WithFile(file), file, pkg)
}
return true
})
}
}
func (a *Analyzer) processFile(ctx *Context, file *ast.File, pkg *packages.Package) {
comment := ctx.ParseComment(file.Doc)
if comment.Ignore() {
return
}
ctx.commentStack.comment = comment
ast.Inspect(file, func(node ast.Node) bool {
switch node := node.(type) {
case *ast.FuncDecl:
a.funDecl(ctx.Block(), node, file, pkg)
return false
case *ast.BlockStmt:
a.blockStmt(ctx.Block(), node, file, pkg)
return false
}
a.analyze(ctx, node)
return true
})
}
func (a *Analyzer) funDecl(ctx *Context, node *ast.FuncDecl, file *ast.File, pkg *packages.Package) {
comment := ctx.ParseComment(node.Doc)
if comment.Ignore() {
return
}
ctx.commentStack.comment = comment
ast.Inspect(node, func(node ast.Node) bool {
switch node := node.(type) {
case *ast.BlockStmt:
a.blockStmt(ctx.Block(), node, file, pkg)
return false
}
a.analyze(ctx, node)
return true
})
}
func (a *Analyzer) loadDefinitionsFromPkg(pkg *packages.Package, moduleDir string) {
InspectPackage(pkg, func(pkg *packages.Package) bool {
if pkg.Module == nil { // Go 内置包
ignore := true
for _, depend := range a.depends {
if strings.HasPrefix(pkg.PkgPath, depend) {
ignore = false
break
}
}
if ignore {
return false
}
} else {
if pkg.Module.Dir != moduleDir && !lo.Contains(a.depends, pkg.Module.Path) {
return false
}
}
for _, file := range pkg.Syntax {
ast.Inspect(file, func(node ast.Node) bool {
switch node := node.(type) {
case *ast.FuncDecl:
a.definitions.Set(NewFuncDefinition(pkg, file, node))
return false
case *ast.TypeSpec:
a.definitions.Set(NewTypeDefinition(pkg, file, node))
return false
case *ast.GenDecl:
if node.Tok == token.CONST {
a.loadEnumDefinition(pkg, file, node)
return false
}
return true
}
return true
})
}
return true
})
}
type A int
const (
A1 A = iota + 1
A2
A3
)
func (a *Analyzer) loadEnumDefinition(pkg *packages.Package, file *ast.File, node *ast.GenDecl) {
for _, item := range node.Specs {
valueSpec, ok := item.(*ast.ValueSpec)
if !ok {
continue
}
for _, name := range valueSpec.Names {
c := pkg.TypesInfo.ObjectOf(name).(*types.Const)
t, ok := c.Type().(*types.Named)
if !ok {
continue
}
basicType, ok := t.Underlying().(*types.Basic)
if !ok {
continue
}
pkgPath := t.Obj().Pkg().Path()
if pkgPath != pkg.PkgPath {
continue
}
def := a.definitions.Get(t.Obj().Pkg().Path() + "." + t.Obj().Name())
if def == nil {
continue
}
typeDef := def.(*TypeDefinition)
value := ConvertStrToBasicType(c.Val().ExactString(), basicType)
enumItem := spec.NewExtendEnumItem(name.Name, value, strings.TrimSpace(valueSpec.Doc.Text()))
typeDef.Enums = append(typeDef.Enums, enumItem)
}
}
}
func (a *Analyzer) blockStmt(ctx *Context, node *ast.BlockStmt, file *ast.File, pkg *packages.Package) {
comment := ctx.ParseComment(a.context().WithPackage(pkg).WithFile(file).GetHeadingCommentOf(node.Lbrace))
if comment.Ignore() {
return
}
ctx.commentStack.comment = comment
a.analyze(ctx, node)
for _, node := range node.List {
ast.Inspect(node, func(node ast.Node) bool {
switch node := node.(type) {
case *ast.BlockStmt:
a.blockStmt(ctx.Block(), node, file, pkg)
return false
}
a.analyze(ctx, node)
return true
})
}
}
func (a *Analyzer) parseGoModule(pkgPath string) *packages.Module {
dir, fileName := a.lookupGoModFile(pkgPath)
if fileName == "" {
panic("go.mod not found in " + pkgPath)
}
content, err := os.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return nil
}
panic(err)
}
mod, err := modfile.Parse("go.mod", content, nil)
if err != nil {
panic(fmt.Sprintf("parse go.mod failed. %s. err=%s", fileName, err.Error()))
}
return &packages.Module{
Path: mod.Module.Mod.Path,
Main: true,
Dir: dir,
GoMod: fileName,
GoVersion: mod.Go.Version,
}
}
func (a *Analyzer) lookupGoModFile(pkgPath string) (string, string) {
for {
fileName := filepath.Join(pkgPath, "go.mod")
_, err := os.Stat(fileName)
if err == nil {
return strings.TrimSuffix(pkgPath, string(filepath.Separator)), fileName
}
var suffix string
pkgPath, suffix = filepath.Split(pkgPath)
if suffix == "" {
break
}
}
return "", ""
}
func (a *Analyzer) context() *Context {
return newContext(a, a.globalEnv)
}
func (a *Analyzer) AddRoutes(items ...*API) {
a.routes.add(items...)
for _, item := range items {
path := a.doc.Paths[item.FullPath]
if path == nil {
path = &spec.PathItem{}
}
item.applyToPathItem(path)
a.doc.Paths[item.FullPath] = path
}
}