forked from sourcegraph/gen-mocks
/
gen_mocks.go
349 lines (314 loc) · 8.55 KB
/
gen_mocks.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
package main // import "sourcegraph.com/sourcegraph/gen-mocks"
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/printer"
"go/token"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/tools/imports"
)
var (
ifacePkgDir = flag.String("p", ".", "directory of package containing interface types")
ifacePat = flag.String("i", ".+Service", "regexp pattern for selecting interface types by name")
writeFiles = flag.Bool("w", false, "write over existing files in output directory (default: writes to stdout)")
outDir = flag.String("o", ".", "output directory")
outPkg = flag.String("outpkg", "", "output pkg name (default: same as input pkg)")
namePrefix = flag.String("name_prefix", "Mock", "output: name prefix of mock impl types (e.g., T -> MockT)")
noPassArgs = flag.String("no_pass_args", "", "don't pass args with this name from the interface method to the mock impl func")
fset = token.NewFileSet()
)
func main() {
flag.Parse()
log.SetFlags(0)
bpkg, err := build.Import(*ifacePkgDir, ".", build.FindOnly)
if err != nil {
log.Fatal(err)
}
pat, err := regexp.Compile(*ifacePat)
if err != nil {
log.Fatal(err)
}
pkgs, err := parser.ParseDir(fset, *ifacePkgDir, nil, parser.AllErrors)
if err != nil {
log.Fatal(err)
}
for _, pkg := range pkgs {
if pkg.Name == "main" || strings.HasSuffix(pkg.Name, "_test") {
continue
}
ifaces, err := readIfaces(pkg, pat)
if err != nil {
log.Fatal(err)
}
if len(ifaces) == 0 {
log.Printf("warning: package %q has no interface types matching %q", pkg.Name, *ifacePat)
continue
}
var pkgName string
if *outPkg == "" {
pkgName = pkg.Name
} else {
pkgName = *outPkg
}
if err := writeMockImplFiles(*outDir, pkgName, pkg.Name, bpkg.ImportPath, ifaces); err != nil {
log.Fatal(err)
}
}
}
// readIfaces returns a list of interface types in pkg that should be
// mocked.
func readIfaces(pkg *ast.Package, pat *regexp.Regexp) ([]*ast.TypeSpec, error) {
var ifaces []*ast.TypeSpec
ast.Walk(visitFn(func(node ast.Node) bool {
switch node := node.(type) {
case *ast.GenDecl:
if node.Tok == token.TYPE {
for _, spec := range node.Specs {
tspec := spec.(*ast.TypeSpec)
if _, ok := tspec.Type.(*ast.InterfaceType); !ok {
continue
}
if name := tspec.Name.Name; pat.MatchString(name) {
ifaces = append(ifaces, tspec)
}
}
}
return false
default:
return true
}
}), pkg)
return ifaces, nil
}
type visitFn func(node ast.Node) (descend bool)
func (v visitFn) Visit(node ast.Node) ast.Visitor {
descend := v(node)
if descend {
return v
} else {
return nil
}
}
func genFuncDecl(mockTypeName string, methName string, method *ast.FuncType) *ast.FuncDecl {
f := &ast.FuncDecl{
Recv: &ast.FieldList{List: []*ast.Field{
{
Names: []*ast.Ident{ast.NewIdent("s")},
Type: &ast.StarExpr{X: ast.NewIdent(mockTypeName)},
},
}},
Name: ast.NewIdent(methName),
Type: method,
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.ExprStmt{
&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent("s"),
Sel: ast.NewIdent(methName + "_"),
},
Args: fieldListToIdentList(method.Params),
Ellipsis: ellipsisIfNeeded(method.Params),
},
},
}},
}
if method.Results != nil {
f.Body = &ast.BlockStmt{List: []ast.Stmt{
&ast.ReturnStmt{
Results: []ast.Expr{f.Body.List[0].(*ast.ExprStmt).X},
},
}}
}
return f
}
func writeMockImplFiles(outDir, outPkg, ifacePkgName, ifacePkgPath string, svcIfaces []*ast.TypeSpec) error {
if err := os.MkdirAll(outDir, 0700); err != nil {
return err
}
decls := map[string][]ast.Decl{} // file -> decls
for _, iface := range svcIfaces {
filename := fset.Position(iface.Pos()).Filename
filename = filepath.Join(outDir, strings.TrimSuffix(filepath.Base(filename), ".go")+"_mock.go")
// mock method fields on struct
var methFields []*ast.Field
for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
if meth, ok := methField.Type.(*ast.FuncType); ok {
methFields = append(methFields, &ast.Field{
Names: []*ast.Ident{ast.NewIdent(methField.Names[0].Name + "_")},
Type: omitNoPassArgs(meth),
})
}
}
// struct implementation type
mockTypeName := *namePrefix + iface.Name.Name
implType := &ast.GenDecl{Tok: token.TYPE, Specs: []ast.Spec{&ast.TypeSpec{
Name: ast.NewIdent(mockTypeName),
Type: &ast.StructType{Fields: &ast.FieldList{List: methFields}},
}}}
decls[filename] = append(decls[filename], implType)
// struct methods
for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
if meth, ok := methField.Type.(*ast.FuncType); ok {
synthesizeFieldNamesIfMissing(meth.Params)
if ifacePkgName != outPkg {
// TODO(sqs): check for import paths or dirs unequal, not pkg name
qualifyPkgRefs(meth, ifacePkgName)
}
decls[filename] = append(decls[filename], genFuncDecl(mockTypeName, methField.Names[0].Name, meth))
}
}
// compile-time implements checks
var ifaceType ast.Expr
if ifacePkgName == outPkg {
ifaceType = ast.NewIdent(iface.Name.Name)
} else {
ifaceType = &ast.SelectorExpr{X: ast.NewIdent(ifacePkgName), Sel: ast.NewIdent(iface.Name.Name)}
}
decls[filename] = append(decls[filename], &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{ast.NewIdent("_")},
Type: ifaceType,
Values: []ast.Expr{
&ast.CallExpr{
Fun: &ast.ParenExpr{X: &ast.StarExpr{X: ast.NewIdent(mockTypeName)}},
Args: []ast.Expr{ast.NewIdent("nil")},
},
},
},
},
})
}
for filename, decls := range decls {
file := &ast.File{
Name: ast.NewIdent(outPkg),
Decls: decls,
}
log.Println("#", filename)
var w io.Writer
if *writeFiles {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
w = f
} else {
w = os.Stdout
}
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, file); err != nil {
return err
}
// Always put blank lines between funcs.
src := bytes.Replace(buf.Bytes(), []byte("}\nfunc"), []byte("}\n\nfunc"), -1)
var err error
src, err = imports.Process(filename, src, nil)
if err != nil {
return err
}
fmt.Fprintln(w, "// generated by gen-mocks; DO NOT EDIT")
fmt.Fprintln(w)
w.Write(src)
}
return nil
}
// qualifyPkgRefs qualifies all refs to non-package-qualified non-builtin types in f so that they refer to definitions in pkg. E.g., 'func(x MyType) -> func (x pkg.MyType)'.
func qualifyPkgRefs(f *ast.FuncType, pkg string) {
var qualify func(x ast.Expr) ast.Expr
qualify = func(x ast.Expr) ast.Expr {
switch y := x.(type) {
case *ast.Ident:
if ast.IsExported(y.Name) {
return &ast.SelectorExpr{X: ast.NewIdent(pkg), Sel: y}
}
case *ast.StarExpr:
y.X = qualify(y.X)
case *ast.ArrayType:
y.Elt = qualify(y.Elt)
case *ast.MapType:
y.Key = qualify(y.Key)
y.Value = qualify(y.Value)
}
return x
}
for _, p := range f.Params.List {
p.Type = qualify(p.Type)
}
for _, r := range f.Results.List {
r.Type = qualify(r.Type)
}
}
// synthesizeFieldNamesIfMissing adds synthesized variable names to fl
// if it contains fields with no name. E.g., the field list in
// `func(string, int)` would be converted to `func(v0 string, v1
// int)`.
func synthesizeFieldNamesIfMissing(fl *ast.FieldList) {
for i, f := range fl.List {
if len(f.Names) == 0 {
f.Names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("v%d", i))}
}
}
}
func fieldListToIdentList(fl *ast.FieldList) []ast.Expr {
var fs []ast.Expr
for _, f := range fl.List {
for _, name := range f.Names {
if *noPassArgs == name.Name {
continue
}
x := ast.Expr(ast.NewIdent(name.Name))
fs = append(fs, x)
}
}
return fs
}
func hasEllipsis(fl *ast.FieldList) bool {
if fl.List == nil {
return false
}
lastField := fl.List[len(fl.List)-1]
if len(lastField.Names) > 0 && lastField.Names[0].Name == *noPassArgs {
return false
}
_, ok := lastField.Type.(*ast.Ellipsis)
return ok
}
func ellipsisIfNeeded(fl *ast.FieldList) token.Pos {
if hasEllipsis(fl) {
return 1
}
return 0
}
func omitNoPassArgs(ft *ast.FuncType) *ast.FuncType {
tmp := *ft // copy
ft = &tmp
tmp2 := *ft.Params
ft.Params = &tmp2
var keepParams []*ast.Field
for _, p := range ft.Params.List {
if len(p.Names) == 1 && p.Names[0].Name == *noPassArgs {
continue
}
keepParams = append(keepParams, p)
}
ft.Params.List = keepParams
return ft
}
func astString(x ast.Expr) string {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, x); err != nil {
panic(err)
}
return buf.String()
}