-
Notifications
You must be signed in to change notification settings - Fork 248
/
staticmethodcollector.go
66 lines (59 loc) · 1.68 KB
/
staticmethodcollector.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
package astutils
import (
"github.com/sirupsen/logrus"
"go/ast"
"go/parser"
"go/token"
)
// StaticMethodCollector collect methods by parsing source code
type StaticMethodCollector struct {
Methods []MethodMeta
Package PackageMeta
exprString func(ast.Expr) string
}
// Visit traverse each node from source code
func (sc *StaticMethodCollector) Visit(n ast.Node) ast.Visitor {
return sc.Collect(n)
}
// Collect collects all static methods from source code
func (sc *StaticMethodCollector) Collect(n ast.Node) ast.Visitor {
switch spec := n.(type) {
case *ast.Package:
return sc
case *ast.File: // actually it is package name
sc.Package = PackageMeta{
Name: spec.Name.Name,
}
return sc
case *ast.FuncDecl:
if spec.Recv == nil {
sc.Methods = append(sc.Methods, GetMethodMeta(spec))
}
case *ast.GenDecl:
}
return nil
}
type StaticMethodCollectorOption func(collector *StaticMethodCollector)
// NewStaticMethodCollector initializes an StaticMethodCollector
func NewStaticMethodCollector(exprString func(ast.Expr) string, opts ...StaticMethodCollectorOption) *StaticMethodCollector {
sc := &StaticMethodCollector{
Methods: make([]MethodMeta, 0),
Package: PackageMeta{},
exprString: exprString,
}
for _, opt := range opts {
opt(sc)
}
return sc
}
// BuildStaticMethodCollector initializes an StaticMethodCollector and collects static methods
func BuildStaticMethodCollector(file string, exprString func(ast.Expr) string) StaticMethodCollector {
sc := NewStaticMethodCollector(exprString)
fset := token.NewFileSet()
root, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
logrus.Panicln(err)
}
ast.Walk(sc, root)
return *sc
}