/
collector.go
391 lines (359 loc) · 8.39 KB
/
collector.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package internal
import (
"bufio"
"fmt"
"github.com/dave/jennifer/jen"
"github.com/reddec/godetector/deepparser"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
type Interface struct {
Name string
Comment string
Methods []*Method
Imports []*ast.ImportSpec
}
func (iface *Interface) LookupForImport(pkg string) string {
if pkg == "" {
return ""
}
// dummy lookup - expect that directory is equal to package name
// priority to aliases
for _, imp := range iface.Imports {
if imp.Name != nil {
if imp.Name.Name == pkg {
path, _ := strconv.Unquote(imp.Path.Value)
return path
}
}
}
for _, imp := range iface.Imports {
path, _ := strconv.Unquote(imp.Path.Value)
if filepath.Base(path) == pkg {
return path
}
}
return ""
}
type Method struct {
Name string
Definition *ast.Field
Type *ast.FuncType
Interface *Interface
fs *token.FileSet
file *ast.File
fileName string
}
func (mg *Method) Comment() string {
return strings.TrimSpace(mg.Definition.Doc.Text())
}
func (mg *Method) ReturnType() string {
return astPrint(mg.Type.Results.List[0].Type, mg.fs)
}
func (mg *Method) LocalTypes(parentImportPath string) []LocalType {
var usedTypes = map[string]typed{}
// collect types from arguments
for _, arg := range mg.Args() {
if !isBuiltin(arg.Type) {
usedTypes[arg.localQual()] = arg.typed
}
}
// do not forget return type
retType := mg.Return()
if !isBuiltin(retType.Type) {
usedTypes[retType.localQual()] = retType
}
// collect types definitions
var ans = make([]LocalType, 0, len(usedTypes))
for _, typeDef := range usedTypes {
definition := deepparser.FindDefinitionFromAst(typeDef.Type, typeDef.Alias, mg.file, filepath.Dir(mg.fileName))
if definition == nil {
continue
}
definition.RemoveJSONIgnoredFields()
fields := definition.StructFields()
ans = append(ans, LocalType{
Type: definition.TypeName,
Definition: astPrint(definition.Type, definition.FS),
IsStruct: definition.IsStruct() && len(fields) > 0,
StructFields: fields,
Inspect: definition,
})
}
sort.Slice(ans, func(i, j int) bool {
return ans[i].Type < ans[j].Type
})
return ans
}
type LocalType struct {
Type string
Definition string
IsStruct bool
StructFields []*deepparser.StField
Inspect *deepparser.Definition
}
type typed struct {
Type string
Import string
Alias string
Ops string
AST ast.Expr
}
func (a typed) localQual() string {
return a.Import + "@" + a.Type
}
func (a typed) Qual(parentImportPath string) jen.Code {
if a.Import == "" {
if parentImportPath == "" || !ast.IsExported(a.Type) {
return jen.Op(a.Ops).Id(a.Type)
}
return jen.Op(a.Ops).Qual(parentImportPath, a.Type)
}
return jen.Op(a.Ops).Qual(a.Import, a.Type)
}
func (a typed) globalQual(parentImport string) string {
if a.Import == "" {
return parentImport + "@" + a.Type
}
return a.localQual()
}
type arg struct {
Name string
typed
}
func (mg *Method) Args() []arg {
if mg.Type.Params == nil || len(mg.Type.Params.List) == 0 {
return nil
}
var args []arg
for _, t := range mg.Type.Params.List {
alias := detectPackageInType(t.Type)
var importPath = mg.Interface.LookupForImport(alias)
for _, name := range t.Names {
args = append(args, arg{
Name: name.Name,
typed: typed{
Ops: rebuildOps(t.Type),
Type: rebuildTypeNameWithoutPackage(t.Type),
Import: importPath,
Alias: alias,
AST: t.Type,
},
})
}
}
if len(args) == 0 {
return nil
}
return args[1:]
}
func (mg *Method) Return() typed {
if mg.Type.Results == nil || len(mg.Type.Results.List) == 0 {
return typed{}
}
retType := mg.Type.Results.List[0].Type
alias := detectPackageInType(retType)
var importPath = mg.Interface.LookupForImport(alias)
return typed{
Ops: rebuildOps(retType),
Type: rebuildTypeNameWithoutPackage(retType),
Import: importPath,
Alias: alias,
AST: retType,
}
}
func detectPackageInType(t ast.Expr) string {
if acc, ok := t.(*ast.SelectorExpr); ok {
return acc.X.(*ast.Ident).Name
} else if ptr, ok := t.(*ast.StarExpr); ok {
return detectPackageInType(ptr.X)
} else if arr, ok := t.(*ast.ArrayType); ok {
return detectPackageInType(arr.Elt)
}
return ""
}
func rebuildOps(t ast.Expr) string {
if ptr, ok := t.(*ast.StarExpr); ok {
return "*" + rebuildOps(ptr.X)
}
if arr, ok := t.(*ast.ArrayType); ok {
return "[]" + rebuildOps(arr.Elt)
}
return ""
}
func rebuildTypeNameWithoutPackage(t ast.Expr) string {
if v, ok := t.(*ast.Ident); ok {
return v.Name
}
if ptr, ok := t.(*ast.StarExpr); ok {
return rebuildTypeNameWithoutPackage(ptr.X)
}
if acc, ok := t.(*ast.SelectorExpr); ok {
return acc.Sel.Name
}
if arr, ok := t.(*ast.ArrayType); ok {
return rebuildTypeNameWithoutPackage(arr.Elt)
}
return ""
}
func CollectInfo(search string, file *ast.File, fs *token.FileSet, fileName string) (*Interface, error) {
var (
name string
comment string
prevComment string
imports []*ast.ImportSpec
)
dir := filepath.Dir(fileName)
var srv *Interface
for _, def := range file.Decls {
ast.Inspect(def, func(node ast.Node) bool {
switch v := node.(type) {
case *ast.ImportSpec:
imports = append(imports, v)
case *ast.CommentGroup:
prevComment = v.Text()
case *ast.TypeSpec:
name = v.Name.Name
comment = strings.TrimSpace(prevComment)
prevComment = ""
case *ast.InterfaceType:
if name != search {
comment = ""
return true
}
srv = &Interface{
Name: name,
Comment: comment,
Methods: nil,
}
for _, fn := range v.Methods.List {
if len(fn.Names) == 0 || !ast.IsExported(fn.Names[0].Name) {
continue
}
tp := fn.Type.(*ast.FuncType)
if !isMethodValid(srv, tp, file, dir) {
log.Println("method", fn.Names[0].Name, "has unsupported signature")
continue
}
srv.Methods = append(srv.Methods, &Method{
Name: fn.Names[0].Name,
Definition: fn,
Type: tp,
Interface: srv,
fs: fs,
file: file,
fileName: fileName,
})
}
return false
}
return true
})
}
if srv == nil {
return nil, fmt.Errorf("interface %v not found", search)
}
srv.Imports = imports
return srv, nil
}
func isMethodValid(iface *Interface, tp *ast.FuncType, file *ast.File, dir string) bool {
if tp.Results == nil || tp.Params == nil {
return false
}
list := tp.Results.List
if len(list) != 2 {
// payload + error
return false
}
if len(tp.Params.List) == 0 {
// first should be context
return false
}
ctx := tp.Params.List[0]
alias := detectPackageInType(ctx.Type)
def := deepparser.FindDefinitionFromAst(rebuildTypeNameWithoutPackage(ctx.Type), alias, file, dir)
if def == nil {
return false
}
if !(def.Import.Path == "context" && def.TypeName == "Context" && rebuildOps(ctx.Type) == "") {
return false
}
return true
}
func FindPackage(dir string) (string, error) {
const Vendor = "vendor/"
if strings.HasPrefix(dir, Vendor) {
return dir[len(Vendor):], nil
}
dir, _ = filepath.Abs(dir)
return findPackage(dir)
}
func findPackage(dir string) (string, error) {
if dir == "" {
return "", os.ErrNotExist
}
if isRootPackage(dir) {
return "", nil
}
pkg, ok := isVendorPackage(dir)
if ok {
return pkg, nil
}
mod := filepath.Base(dir)
top, err := findPackage(filepath.Dir(dir))
if err != nil {
return "", err
}
if top != "" {
return top + "/" + mod, nil
}
return mod, nil
}
func isVendorPackage(path string) (string, bool) {
path = filepath.Join(path, "go.mod")
if fs, err := os.Stat(path); err != nil {
return "", false
} else if fs.IsDir() {
return "", false
}
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanWords)
if !(scanner.Scan() && scanner.Scan()) {
return "", false
}
pkg := scanner.Text()
return pkg, true
}
func isRootPackage(path string) bool {
GOPATH := filepath.Join(os.Getenv("GOPATH"), "src")
GOROOT := filepath.Join(os.Getenv("GOROOT"), "src")
return isRootOf(path, GOPATH) || isRootOf(path, GOROOT)
}
func isRootOf(path, root string) bool {
root, _ = filepath.Abs(root)
path, _ = filepath.Abs(path)
return root == path
}
func isBuiltin(name string) bool {
for _, k := range types.Typ {
if k.Name() == name {
return true
}
}
if name == "error" {
return true
}
return false
}