-
Notifications
You must be signed in to change notification settings - Fork 413
/
parse.go
294 lines (253 loc) · 6.9 KB
/
parse.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
package pkg
import (
"context"
"fmt"
"go/ast"
"go/types"
"os"
"path/filepath"
"sort"
"strings"
"github.com/rs/zerolog"
"github.com/vektra/mockery/v2/pkg/logging"
"golang.org/x/tools/go/packages"
)
type parserEntry struct {
fileName string
pkg *packages.Package
syntax *ast.File
interfaces []string
}
type packageLoadEntry struct {
pkgs []*packages.Package
err error
}
type Parser struct {
entries []*parserEntry
entriesByFileName map[string]*parserEntry
parserPackages []*types.Package
conf packages.Config
packageLoadCache map[string]packageLoadEntry
}
func NewParser(buildTags []string) *Parser {
var conf packages.Config
conf.Mode = packages.LoadSyntax
if len(buildTags) > 0 {
conf.BuildFlags = []string{"-tags", strings.Join(buildTags, ",")}
}
return &Parser{
parserPackages: make([]*types.Package, 0),
entriesByFileName: map[string]*parserEntry{},
conf: conf,
packageLoadCache: map[string]packageLoadEntry{},
}
}
func (p *Parser) loadPackages(fpath string) ([]*packages.Package, error) {
if result, ok := p.packageLoadCache[fpath]; ok {
return result.pkgs, result.err
}
pkgs, err := packages.Load(&p.conf, "file="+fpath)
p.packageLoadCache[fpath] = packageLoadEntry{pkgs, err}
return pkgs, err
}
func (p *Parser) Parse(ctx context.Context, path string) error {
// To support relative paths to mock targets w/ vendor deps, we need to provide eventual
// calls to build.Context.Import with an absolute path. It needs to be absolute because
// Import will only find the vendor directory if our target path for parsing is under
// a "root" (GOROOT or a GOPATH). Only absolute paths will pass the prefix-based validation.
//
// For example, if our parse target is "./ifaces", Import will check if any "roots" are a
// prefix of "ifaces" and decide to skip the vendor search.
path, err := filepath.Abs(path)
if err != nil {
return err
}
dir := filepath.Dir(path)
files, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, fi := range files {
log := zerolog.Ctx(ctx).With().
Str(logging.LogKeyDir, dir).
Str(logging.LogKeyFile, fi.Name()).
Logger()
ctx = log.WithContext(ctx)
if filepath.Ext(fi.Name()) != ".go" || strings.HasSuffix(fi.Name(), "_test.go") || strings.HasPrefix(fi.Name(), "mock_") {
continue
}
log.Debug().Msgf("parsing")
fname := fi.Name()
fpath := filepath.Join(dir, fname)
if _, ok := p.entriesByFileName[fpath]; ok {
continue
}
pkgs, err := p.loadPackages(fpath)
if err != nil {
return err
}
if len(pkgs) == 0 {
continue
}
if len(pkgs) > 1 {
names := make([]string, len(pkgs))
for i, p := range pkgs {
names[i] = p.Name
}
panic(fmt.Sprintf("file %s resolves to multiple packages: %s", fpath, strings.Join(names, ", ")))
}
pkg := pkgs[0]
if len(pkg.Errors) > 0 {
return pkg.Errors[0]
}
if len(pkg.GoFiles) == 0 {
continue
}
for idx, f := range pkg.GoFiles {
if _, ok := p.entriesByFileName[f]; ok {
continue
}
entry := parserEntry{
fileName: f,
pkg: pkg,
syntax: pkg.Syntax[idx],
}
p.entries = append(p.entries, &entry)
p.entriesByFileName[f] = &entry
}
}
return nil
}
type NodeVisitor struct {
declaredInterfaces []string
}
func NewNodeVisitor() *NodeVisitor {
return &NodeVisitor{
declaredInterfaces: make([]string, 0),
}
}
func (nv *NodeVisitor) DeclaredInterfaces() []string {
return nv.declaredInterfaces
}
func (nv *NodeVisitor) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.TypeSpec:
switch n.Type.(type) {
case *ast.InterfaceType, *ast.FuncType:
nv.declaredInterfaces = append(nv.declaredInterfaces, n.Name.Name)
}
}
return nv
}
func (p *Parser) Load() error {
for _, entry := range p.entries {
nv := NewNodeVisitor()
ast.Walk(nv, entry.syntax)
entry.interfaces = nv.DeclaredInterfaces()
}
return nil
}
func (p *Parser) Find(name string) (*Interface, error) {
for _, entry := range p.entries {
for _, iface := range entry.interfaces {
if iface == name {
list := p.packageInterfaces(entry.pkg.Types, entry.fileName, []string{name}, nil)
if len(list) > 0 {
return list[0], nil
}
}
}
}
return nil, ErrNotInterface
}
type Method struct {
Name string
Signature *types.Signature
}
// Interface type represents the target type that we will generate a mock for.
// It could be an interface, or a function type.
// Function type emulates: an interface it has 1 method with the function signature
// and a general name, e.g. "Execute".
type Interface struct {
Name string // Name of the type to be mocked.
QualifiedName string // Path to the package of the target type.
FileName string
File *ast.File
Pkg *types.Package
NamedType *types.Named
IsFunction bool // If true, this instance represents a function, otherwise it's an interface.
ActualInterface *types.Interface // Holds the actual interface type, in case it's an interface.
SingleFunction *Method // Holds the function type information, in case it's a function type.
}
func (iface *Interface) Methods() []*Method {
if iface.IsFunction {
return []*Method{iface.SingleFunction}
}
methods := make([]*Method, iface.ActualInterface.NumMethods())
for i := 0; i < iface.ActualInterface.NumMethods(); i++ {
fn := iface.ActualInterface.Method(i)
methods[i] = &Method{Name: fn.Name(), Signature: fn.Type().(*types.Signature)}
}
return methods
}
type sortableIFaceList []*Interface
func (s sortableIFaceList) Len() int {
return len(s)
}
func (s sortableIFaceList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortableIFaceList) Less(i, j int) bool {
return strings.Compare(s[i].Name, s[j].Name) == -1
}
func (p *Parser) Interfaces() []*Interface {
ifaces := make(sortableIFaceList, 0)
for _, entry := range p.entries {
declaredIfaces := entry.interfaces
ifaces = p.packageInterfaces(entry.pkg.Types, entry.fileName, declaredIfaces, ifaces)
}
sort.Sort(ifaces)
return ifaces
}
func (p *Parser) packageInterfaces(
pkg *types.Package,
fileName string,
declaredInterfaces []string,
ifaces []*Interface) []*Interface {
scope := pkg.Scope()
for _, name := range declaredInterfaces {
obj := scope.Lookup(name)
if obj == nil {
continue
}
typ, ok := obj.Type().(*types.Named)
if !ok {
continue
}
name = typ.Obj().Name()
if typ.Obj().Pkg() == nil {
continue
}
elem := &Interface{
Name: name,
Pkg: pkg,
QualifiedName: pkg.Path(),
FileName: fileName,
NamedType: typ,
}
iface, ok := typ.Underlying().(*types.Interface)
if ok {
elem.IsFunction = false
elem.ActualInterface = iface
} else {
sig, ok := typ.Underlying().(*types.Signature)
if !ok {
continue
}
elem.IsFunction = true
elem.SingleFunction = &Method{Name: "Execute", Signature: sig}
}
ifaces = append(ifaces, elem)
}
return ifaces
}