-
Notifications
You must be signed in to change notification settings - Fork 531
/
goanalysis.go
395 lines (356 loc) · 9.75 KB
/
goanalysis.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
392
393
394
395
// Package goanalysis provides a toolset for statically analysing Go applications
package goanalysis
import (
"go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/ignite/cli/v29/ignite/pkg/errors"
)
const (
mainPackage = "main"
goFileExtension = ".go"
toolsBuildTag = "//go:build tools\n\n"
)
// ErrMultipleMainPackagesFound is returned when multiple main packages found while expecting only one.
var ErrMultipleMainPackagesFound = errors.New("multiple main packages found")
// DiscoverMain finds main Go packages under path.
func DiscoverMain(path string) (pkgPaths []string, err error) {
uniquePaths := make(map[string]struct{})
err = filepath.Walk(path, func(filePath string, f os.FileInfo, err error) error {
if f.IsDir() || !strings.HasSuffix(filePath, goFileExtension) {
return err
}
parsed, err := parser.ParseFile(token.NewFileSet(), filePath, nil, parser.PackageClauseOnly)
if err != nil {
return err
}
if mainPackage == parsed.Name.Name {
dir := filepath.Dir(filePath)
uniquePaths[dir] = struct{}{}
}
return nil
})
if err != nil {
return nil, err
}
for path := range uniquePaths {
pkgPaths = append(pkgPaths, path)
}
return pkgPaths, nil
}
// DiscoverOneMain tries to find only one main Go package under path.
func DiscoverOneMain(path string) (pkgPath string, err error) {
pkgPaths, err := DiscoverMain(path)
if err != nil {
return "", err
}
count := len(pkgPaths)
if count == 0 {
return "", errors.New("main package cannot be found")
}
if count > 1 {
return "", ErrMultipleMainPackagesFound
}
return pkgPaths[0], nil
}
// FuncVarExists finds a genesis variable goImport into the go file.
func FuncVarExists(f *ast.File, goImport, methodSignature string) bool {
var (
importAlias = ""
imports = FormatImports(f)
)
for alias, imp := range imports {
if imp == goImport {
importAlias = alias
}
}
if importAlias == "" {
return false
}
methodDecl := importAlias + "." + methodSignature
for _, d := range f.Decls {
if declVarExists(d, methodDecl) {
return true
}
}
return false
}
// declVarExists find a variable declaration into a ast.Decl.
func declVarExists(decl ast.Decl, methodDecl string) bool {
switch d := decl.(type) {
case *ast.FuncDecl:
for _, stmt := range d.Body.List {
switch v := stmt.(type) {
case *ast.DeclStmt:
if declVarExists(v.Decl, methodDecl) {
return true
}
case *ast.AssignStmt:
if len(v.Rhs) == 0 {
continue
}
decl, err := getCallExprName(v.Rhs[0])
if err != nil {
continue
}
if decl == methodDecl {
return true
}
case *ast.IfStmt:
stmt, ok := v.Init.(*ast.AssignStmt)
if !ok || len(stmt.Rhs) == 0 {
continue
}
decl, err := getCallExprName(stmt.Rhs[0])
if err != nil {
continue
}
if decl == methodDecl {
return true
}
}
}
case *ast.GenDecl:
decls, err := getGenDeclNames(d)
if err != nil {
return false
}
for _, decl := range decls {
if decl == methodDecl {
return true
}
}
}
return false
}
// getGenDeclNames returns a list of the method declaration inside the ast.GenDecl.
func getGenDeclNames(genDecl *ast.GenDecl) ([]string, error) {
if genDecl.Tok != token.VAR {
return nil, errors.Errorf("genDecl is not a var token: %v", genDecl.Tok)
}
var decls []string
for _, spec := range genDecl.Specs {
valueDecl, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for _, id := range valueDecl.Names {
vSpec, ok := id.Obj.Decl.(*ast.ValueSpec)
if !ok || len(vSpec.Values) == 0 {
continue
}
cursorDecl, err := getCallExprName(vSpec.Values[0])
if err != nil {
continue
}
decls = append(decls, cursorDecl)
}
}
if len(decls) == 0 {
return nil, errors.Errorf("empty method declarations")
}
return decls, nil
}
// getGenDeclNames returns the method declaration inside the ast.Expr.
func getCallExprName(expr ast.Expr) (string, error) {
call, ok := expr.(*ast.CallExpr)
if !ok {
return "", errors.Errorf("expression is not a *ast.CallExpr: %v", expr)
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return "", errors.Errorf("expression function is not a *ast.SelectorExpr: %v", call.Fun)
}
x, ok := sel.X.(*ast.Ident)
if !ok {
return "", errors.Errorf("selector expression function is not a *ast.Ident: %v", sel.X)
}
return x.String() + "." + sel.Sel.String(), nil
}
// FindBlankImports find all blank imports ('_') into a file.
func FindBlankImports(node *ast.File) []string {
// Iterate through the import declarations and find the blank imports.
blankImports := make([]string, 0)
for _, imp := range node.Imports {
if imp.Name != nil && imp.Name.Name == "_" {
blankImports = append(blankImports, strings.ReplaceAll(imp.Path.Value, `"`, ""))
}
}
return blankImports
}
// FormatImports translate f.Imports into a map where name -> package.
// Name is the alias if declared, or the last element of the package path.
func FormatImports(f *ast.File) map[string]string {
m := make(map[string]string) // name -> import
for _, imp := range f.Imports {
var importName string
if imp.Name != nil && imp.Name.Name != "_" && imp.Name.Name != "." {
importName = imp.Name.Name
} else {
importParts := strings.Split(imp.Path.Value, "/")
importName = importParts[len(importParts)-1]
}
name := strings.Trim(importName, "\"")
m[name] = strings.Trim(imp.Path.Value, "\"")
}
return m
}
// UpdateInitImports helper function to remove and add underscore (init) imports to an *ast.File.
func UpdateInitImports(file *ast.File, writer io.Writer, importsToAdd, importsToRemove []string) error {
// Create a map for faster lookup of items to remove
importMap := make(map[string]bool)
for _, astImport := range file.Imports {
value, err := strconv.Unquote(astImport.Path.Value)
if err != nil {
return err
}
importMap[value] = true
}
for _, removeImport := range importsToRemove {
importMap[removeImport] = false
}
for _, addImport := range importsToAdd {
importMap[addImport] = true
}
// Add the imports
for _, d := range file.Decls {
if dd, ok := d.(*ast.GenDecl); ok {
if dd.Tok == token.IMPORT {
file.Imports = make([]*ast.ImportSpec, 0)
dd.Specs = make([]ast.Spec, 0)
for imp, exist := range importMap {
if exist {
spec := createUnderscoreImport(imp)
file.Imports = append(file.Imports, spec)
dd.Specs = append(dd.Specs, spec)
}
}
}
}
}
if _, err := writer.Write([]byte(toolsBuildTag)); err != nil {
return errors.Errorf("failed to write the build tag: %w", err)
}
return format.Node(writer, token.NewFileSet(), file)
}
// createUnderscoreImports helper function to create an AST underscore import with given path.
func createUnderscoreImport(imp string) *ast.ImportSpec {
return &ast.ImportSpec{
Name: ast.NewIdent("_"),
Path: &ast.BasicLit{
Kind: token.STRING,
Value: strconv.Quote(imp),
},
}
}
// ReplaceCode replace a function implementation into a package path. The method will find
// the method signature and re-write the method implementation based in the new function.
func ReplaceCode(pkgPath, oldFunctionName, newFunction string) (err error) {
absPath, err := filepath.Abs(pkgPath)
if err != nil {
return err
}
fileSet := token.NewFileSet()
all, err := parser.ParseDir(fileSet, absPath, func(os.FileInfo) bool { return true }, parser.ParseComments)
if err != nil {
return err
}
for _, pkg := range all {
for _, f := range pkg.Files {
found := false
ast.Inspect(f, func(n ast.Node) bool {
if funcDecl, ok := n.(*ast.FuncDecl); ok {
// Check if the function has the name you want to replace.
if funcDecl.Name.Name == oldFunctionName {
// Replace the function body with the replacement code.
replacementExpr, err := parser.ParseExpr(newFunction)
if err != nil {
return false
}
funcDecl.Body = &ast.BlockStmt{List: []ast.Stmt{
&ast.ExprStmt{X: replacementExpr},
}}
found = true
return false
}
}
return true
})
if err != nil {
return err
}
if !found {
continue
}
filePath := fileSet.Position(f.Package).Filename
outFile, err := os.Create(filePath)
if err != nil {
return err
}
// Format and write the modified AST to the output file.
if err := format.Node(outFile, fileSet, f); err != nil {
return err
}
if err := outFile.Close(); err != nil {
return err
}
}
}
return nil
}
// HasAnyStructFieldsInPkg finds the struct within a package folder and checks
// if any of the fields are defined in the struct.
func HasAnyStructFieldsInPkg(pkgPath, structName string, fields []string) (bool, error) {
absPath, err := filepath.Abs(pkgPath)
if err != nil {
return false, err
}
fileSet := token.NewFileSet()
all, err := parser.ParseDir(fileSet, absPath, nil, parser.ParseComments)
if err != nil {
return false, err
}
fieldsNames := make(map[string]struct{})
for _, field := range fields {
fieldsNames[strings.ToLower(field)] = struct{}{}
}
exist := false
for _, pkg := range all {
for _, f := range pkg.Files {
ast.Inspect(f, func(x ast.Node) bool {
typeSpec, ok := x.(*ast.TypeSpec)
if !ok {
return true
}
if _, ok := typeSpec.Type.(*ast.StructType); !ok ||
typeSpec.Name.Name != structName ||
typeSpec.Type == nil {
return true
}
// Check if the struct has fields.
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
return true
}
// Iterate through the fields of the struct.
for _, field := range structType.Fields.List {
for _, fieldName := range field.Names {
if _, ok := fieldsNames[strings.ToLower(fieldName.Name)]; !ok {
continue
}
exist = true
return false
}
}
return true
})
}
}
return exist, nil
}