-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenx.go
106 lines (89 loc) · 1.86 KB
/
genx.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
package main
import (
"go/parser"
"go/token"
"golang.org/x/tools/go/packages"
"log"
"os"
"path/filepath"
"strings"
)
var (
ignores = []string{"_genx.go", "_test.go", "_example.go"}
)
func resolvePkg(pkg *packages.Package) {
for _, f := range pkg.GoFiles {
ignore := false
for _, s := range ignores {
if strings.HasSuffix(f, s) {
ignore = true
break
}
}
if ignore {
continue
}
handlers := resolveFile(f, pkg)
if len(handlers) == 0 {
continue
}
NewGenerator(handlers).Generate()
}
}
func resolveFile(path string, pkg *packages.Package) []*ApiHandler {
set := token.NewFileSet()
astFile, err := parser.ParseFile(set, path, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
gf := NewGoFile(pkg, astFile, path)
funcs := resolveHandlerFunc(gf, commentMatcher)
handlers := make([]*ApiHandler, 0, len(funcs))
for _, fn := range funcs {
if len(fn.errors) > 0 {
log.Println(fn.errors)
continue
}
handler, err := NewApiHandler(fn)
if err != nil {
log.Println(err)
continue
}
handlers = append(handlers, handler)
}
return handlers
}
func resolveHandlerFunc(gf *GoFile, matcher FuncMatcher) []*GoFunc {
var handlers []*GoFunc
gf.traversalFuncByMatch(matcher, func(handler *GoFunc) {
handler.ResolveTypeInfo()
if len(handler.errors) > 0 {
log.Printf("%s: %s", handler.Name(), handler.errors)
return
}
handlers = append(handlers, handler)
})
return handlers
}
func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
pkgConfig := &packages.Config{
Mode: packages.NeedImports |
packages.NeedName |
packages.NeedFiles |
packages.NeedDeps |
packages.NeedModule |
packages.NeedSyntax,
Dir: dir,
}
pkgs, err := packages.Load(pkgConfig, "")
if err != nil {
log.Fatal(err)
}
for _, p := range pkgs {
resolvePkg(p)
}
}