-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage_analyzer.go
More file actions
79 lines (69 loc) · 1.91 KB
/
Copy pathusage_analyzer.go
File metadata and controls
79 lines (69 loc) · 1.91 KB
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
package unusedsqlc
import (
"go/ast"
"go/token"
"strings"
)
// UsageAnalyzer analyzes Go AST to find sqlc query usage.
type UsageAnalyzer struct {
config *Config
}
// NewUsageAnalyzer creates a new UsageAnalyzer with the given configuration.
func NewUsageAnalyzer(config *Config) *UsageAnalyzer {
if config == nil {
config = DefaultConfig()
}
return &UsageAnalyzer{
config: config,
}
}
// FindUsedQueries analyzes AST files to find which sqlc queries are actually used.
func (a *UsageAnalyzer) FindUsedQueries(files []*ast.File, fset *token.FileSet, queries []*SQLQuery) map[string]bool {
usedQueries := make(map[string]bool)
queryMap := make(map[string]*SQLQuery)
for _, query := range queries {
queryMap[query.Name] = query
}
for _, file := range files {
if a.config.IgnoreGenerated {
pos := fset.Position(file.Pos())
if strings.Contains(pos.Filename, ".sql.go") ||
strings.Contains(pos.Filename, "_gen.go") ||
strings.Contains(pos.Filename, "generated") {
continue
}
}
ast.Inspect(file, func(n ast.Node) bool {
switch node := n.(type) {
case *ast.CallExpr:
a.checkCallExpr(node, queryMap, usedQueries)
case *ast.SelectorExpr:
if _, exists := queryMap[node.Sel.Name]; exists {
usedQueries[node.Sel.Name] = true
}
}
return true
})
}
return usedQueries
}
func (a *UsageAnalyzer) checkCallExpr(call *ast.CallExpr, queryMap map[string]*SQLQuery, usedQueries map[string]bool) {
if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
methodName := sel.Sel.Name
if _, exists := queryMap[methodName]; exists {
usedQueries[methodName] = true
}
}
for _, arg := range call.Args {
switch argExpr := arg.(type) {
case *ast.SelectorExpr:
if _, exists := queryMap[argExpr.Sel.Name]; exists {
usedQueries[argExpr.Sel.Name] = true
}
case *ast.Ident:
if _, exists := queryMap[argExpr.Name]; exists {
usedQueries[argExpr.Name] = true
}
}
}
}