-
Notifications
You must be signed in to change notification settings - Fork 0
/
loggercheck.go
238 lines (198 loc) · 5.84 KB
/
loggercheck.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
package loggercheck
import (
"flag"
"fmt"
"go/ast"
"go/types"
"os"
"sync"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
"github.com/george-maroun/tracecheck/internal/checkers"
"github.com/george-maroun/tracecheck/internal/rules"
"github.com/george-maroun/tracecheck/internal/sets"
)
const Doc = `Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).`
func NewAnalyzer(opts ...Option) *analysis.Analyzer {
l := newLoggerCheck(opts...)
a := &analysis.Analyzer{
Name: "loggercheck",
Doc: Doc,
Flags: *l.fs,
Run: l.run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
return a
}
type loggercheck struct {
fs *flag.FlagSet
disable sets.StringSet // flag -disable
ruleFile string // flag -rulefile
requireStringKey bool // flag -requirestringkey
noPrintfLike bool // flag -noprintflike
rules []string // used for external integration, for example golangci-lint
rulesetList []rules.Ruleset // populate at runtime
rulesetIndicesByImport map[string][]int // ruleset index, populate at runtime
mu sync.Mutex
CallToFile map[*ast.CallExpr]*ast.File
}
func newLoggerCheck(opts ...Option) *loggercheck {
fs := flag.NewFlagSet("loggercheck", flag.ExitOnError)
l := &loggercheck{
fs: fs,
disable: sets.NewString("kitlog"),
rulesetList: append([]rules.Ruleset{}, staticRuleList...), // ensure we make a clone of static rules first
// CalltoFile allows us to access the current file in the checker
CallToFile: make(map[*ast.CallExpr]*ast.File),
}
fs.StringVar(&l.ruleFile, "rulefile", "", "path to a file contains a list of rules")
fs.Var(&l.disable, "disable", "comma-separated list of disabled logger checker (kitlog,klog,logr,zap)")
fs.BoolVar(&l.requireStringKey, "requirestringkey", false, "require all logging keys to be inlined constant strings")
fs.BoolVar(&l.noPrintfLike, "noprintflike", false, "require printf-like format specifier not present in args")
for _, opt := range opts {
opt(l)
}
return l
}
func (l *loggercheck) isCheckerDisabled(name string) bool {
return l.disable.Has(name)
}
// vendorLessPath returns the devendorized version of the import path ipath.
// For example: "a/vendor/github.com/go-logr/logr" will become "github.com/go-logr/logr".
func vendorLessPath(ipath string) string {
if i := strings.LastIndex(ipath, "/vendor/"); i >= 0 {
return ipath[i+len("/vendor/"):]
}
return ipath
}
func (l *loggercheck) getCheckerForFunc(fn *types.Func) checkers.Checker {
pkg := fn.Pkg()
if pkg == nil {
return nil
}
pkgPath := vendorLessPath(pkg.Path())
indices := l.rulesetIndicesByImport[pkgPath]
for _, idx := range indices {
rs := &l.rulesetList[idx]
if l.isCheckerDisabled(rs.Name) {
// Skip ignored logger checker.
continue
}
// Only check functions where `WithValues` is called.
fullFuncName := fn.FullName()
if !strings.HasSuffix(fullFuncName, "WithValues") {
continue
}
if !rs.Match(fn) {
continue
}
checker := checkerByRulesetName[rs.Name]
if checker == nil {
return checkers.General{}
}
return checker
}
return nil
}
func (l *loggercheck) checkLoggerArguments(pass *analysis.Pass, call *ast.CallExpr) {
fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func)
if fn == nil {
return // function pointer is not supported
}
sig, ok := fn.Type().(*types.Signature)
if !ok || !sig.Variadic() {
return // not variadic
}
// ellipsis args is hard, just skip
if call.Ellipsis.IsValid() {
return
}
checker := l.getCheckerForFunc(fn)
if checker == nil {
return
}
// Retrieve the current file from the map
file := l.CallToFile[call]
checkers.ExecuteChecker(checker, pass, checkers.CallContext{
Expr: call,
Func: fn,
Signature: sig,
File: file, // pass the file here
}, checkers.Config{
RequireStringKey: l.requireStringKey,
NoPrintfLike: l.noPrintfLike,
})
}
func (l *loggercheck) processConfig() error {
l.mu.Lock() // lock
defer l.mu.Unlock()
if l.ruleFile != "" { // flags takes precedence over configs
f, err := os.Open(l.ruleFile)
if err != nil {
return fmt.Errorf("failed to open rule file: %w", err)
}
defer f.Close()
custom, err := rules.ParseRuleFile(f)
if err != nil {
return fmt.Errorf("failed to parse rule file: %w", err)
}
l.rulesetList = append(l.rulesetList, custom...)
} else if len(l.rules) > 0 {
custom, err := rules.ParseRules(l.rules)
if err != nil {
return fmt.Errorf("failed to parse rules: %w", err)
}
l.rulesetList = append(l.rulesetList, custom...)
}
// Build index
indices := make(map[string][]int)
for i, rs := range l.rulesetList {
indices[rs.PackageImport] = append(indices[rs.PackageImport], i)
}
l.rulesetIndicesByImport = indices
return nil
}
func (l *loggercheck) run(pass *analysis.Pass) (interface{}, error) {
err := l.processConfig()
if err != nil {
return nil, err
}
insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.CallExpr)(nil),
}
insp.Preorder(nodeFilter, func(node ast.Node) {
call := node.(*ast.CallExpr)
tokFile := pass.Fset.File(call.Pos())
if tokFile == nil {
return
}
// Find the corresponding ast.File
var file *ast.File
for _, f := range pass.Files {
if pass.Fset.File(f.Pos()) == tokFile {
file = f
break
}
}
if file == nil {
return
}
// Save the current file to the map
// Lock the mutex before accessing the shared resource
l.mu.Lock()
l.CallToFile[call] = file
// Unlock it afterwards
defer l.mu.Unlock()
typ := pass.TypesInfo.Types[call.Fun].Type
if typ == nil {
// Skip checking functions with unknown type.
return
}
l.checkLoggerArguments(pass, call)
})
return nil, nil
}