/
loader.go
233 lines (204 loc) · 4.79 KB
/
loader.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
package loader
import (
"bytes"
"go/ast"
"go/printer"
"go/token"
"os"
"path/filepath"
"strconv"
"strings"
"golang.org/x/tools/go/packages"
)
type (
PackagePath = string
FileName = string
GenBy = string
Loader struct {
Flags *Flags
Cfg *packages.Config
FSet *token.FileSet
Init []*packages.Package
All map[PackagePath]*packages.Package
Gen map[FileName]GenBy
}
)
func MustNew(dir string, opts ...Option) *Loader {
l, err := New(dir, opts...)
panicIf(err)
return l
}
func New(dir string, opts ...Option) (l *Loader, err error) {
flags := &Flags{}
flags.PrintErrors = true
flags.Patterns = []string{PatternAll} // default all
for _, opt := range append(opts, skipTestMain()) {
opt(flags)
}
l = &Loader{
Flags: flags,
FSet: token.NewFileSet(),
Init: []*packages.Package{},
All: map[PackagePath]*packages.Package{},
Gen: map[FileName]GenBy{},
}
err = l.load(dir)
return
}
// dir: run the build system's query tool
func (l *Loader) load(dir string) (err error) {
dir, err = filepath.Abs(dir)
if err != nil {
return err
}
l.Cfg = l.mkLoadCfg(dir)
l.Init, err = packages.Load(l.Cfg, l.Flags.Patterns...)
if err != nil {
return err
}
if len(l.Init) == 0 {
errLog("no packages found")
}
l.loadAllPkg()
return nil
}
func (l *Loader) loadAllPkg() {
packages.Visit(l.Init, nil, func(p *packages.Package) {
if l.Flags.PrintErrors {
for _, err := range p.Errors {
errLog(err)
}
}
// Gather all packages
l.All[p.PkgPath] = p
// Gather generated files
for _, file := range p.Syntax {
if gen, is := Generator(file); is {
f := p.Fset.File(file.Pos())
l.Gen[f.Name()] = gen
}
}
})
}
func (l *Loader) mkLoadCfg(dir string) *packages.Config {
mode := loadMode
if l.Flags.LoadDepts {
mode |= loadDepts
}
cfg := &packages.Config{
Fset: l.FSet,
Mode: mode,
Tests: l.Flags.Test,
Dir: dir,
BuildFlags: []string{"-tags=" + l.Flags.BuildTag},
}
if l.Flags.Gopath != "" {
cfg.Env = append(os.Environ(), "GOPATH="+l.Flags.Gopath)
}
return cfg
}
// VisitAllFiles Walk all files in all init-pkgs (defined by load pattern)
func (l *Loader) VisitAllFiles(f func(file *File)) {
for _, pkg := range l.Init {
if l.Flags.PkgFilter == nil || l.Flags.PkgFilter(pkg) {
l.visitPkgFiles(pkg, f)
}
}
}
// VisitAllPackages in topological order
// walk files order by compiledGoFiles in same package
// walk imports order by declaration in one file
// deep first
func (l *Loader) VisitAllPackages(
pre func(*packages.Package) bool,
post func(*packages.Package),
) {
seen := map[*packages.Package]bool{}
var visit func(*packages.Package)
visit = func(pkg *packages.Package) {
if seen[pkg] {
return
}
seen[pkg] = true
if pre == nil || pre(pkg) {
l.visitPkgFiles(pkg, func(file *File) {
l.visitFileImports(file, func(name *ast.Ident, path string) {
impt := l.All[path]
if impt != nil {
visit(impt)
}
})
})
}
if post != nil {
post(pkg)
}
}
for _, pkg := range l.Init {
if l.Flags.PkgFilter == nil || l.Flags.PkgFilter(pkg) {
visit(pkg)
}
}
}
func (l *Loader) visitPkgFiles(pkg *packages.Package, f func(file *File)) {
for i, filename := range pkg.CompiledGoFiles {
file := &File{
File: pkg.Syntax[i],
Pkg: pkg,
Filename: filename,
GenBy: l.Gen[filename],
}
if l.Flags.FileFilter == nil || l.Flags.FileFilter(file) {
f(file)
}
}
}
func (l *Loader) visitFileImports(file *File, yield func(name *ast.Ident, path string)) {
for _, decl := range file.File.Decls {
d, ok := decl.(*ast.GenDecl)
if !ok || d.Tok != token.IMPORT {
continue
}
for _, spec := range d.Specs {
s := spec.(*ast.ImportSpec)
name := s.Name
path := parseImportPath(s)
yield(name, path)
}
}
}
func (l *Loader) ShowPos(n ast.Node) string {
return l.FSet.Position(n.Pos()).String()
}
func (l *Loader) ShowNode(n ast.Node) string {
// if IsPseudoNode(n) {
// return showPseudoNode(fset, n)
// }
var buf bytes.Buffer
_ = printer.Fprint(&buf, l.FSet, n)
return buf.String()
}
func parseImportPath(s *ast.ImportSpec) string {
path := s.Path.Value
xs := strings.Split(path, " ")
if len(xs) > 1 {
path = xs[1]
}
t, _ := strconv.Unquote(path) // ignored illegal path
return t
}
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ Modes ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const (
// loadDepts load all dependencies
loadDepts = packages.NeedImports | packages.NeedDeps
loadMode = packages.NeedTypesInfo |
packages.NeedName |
packages.NeedFiles |
packages.NeedExportFile |
packages.NeedCompiledGoFiles |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedTypesInfo |
packages.NeedTypesSizes |
packages.NeedModule
)