/
sloglint.go
489 lines (431 loc) 路 14.4 KB
/
sloglint.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Package sloglint implements the sloglint analyzer.
package sloglint
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"slices"
"strconv"
"strings"
"github.com/ettle/strcase"
"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"
)
// Options are options for the sloglint analyzer.
type Options struct {
NoMixedArgs bool // Enforce not mixing key-value pairs and attributes (default true).
KVOnly bool // Enforce using key-value pairs only (overrides NoMixedArgs, incompatible with AttrOnly).
AttrOnly bool // Enforce using attributes only (overrides NoMixedArgs, incompatible with KVOnly).
NoGlobal string // Enforce not using global loggers ("all" or "default").
ContextOnly string // Enforce using methods that accept a context ("all" or "scope").
StaticMsg bool // Enforce using static log messages.
NoRawKeys bool // Enforce using constants instead of raw keys.
KeyNamingCase string // Enforce a single key naming convention ("snake", "kebab", "camel", or "pascal").
ForbiddenKeys []string // Enforce not using specific keys.
ArgsOnSepLines bool // Enforce putting arguments on separate lines.
}
// New creates a new sloglint analyzer.
func New(opts *Options) *analysis.Analyzer {
if opts == nil {
opts = &Options{NoMixedArgs: true}
}
return &analysis.Analyzer{
Name: "sloglint",
Doc: "ensure consistent code style when using log/slog",
Flags: flags(opts),
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: func(pass *analysis.Pass) (any, error) {
if opts.KVOnly && opts.AttrOnly {
return nil, fmt.Errorf("sloglint: Options.KVOnly and Options.AttrOnly: %w", errIncompatible)
}
switch opts.NoGlobal {
case "", "all", "default":
default:
return nil, fmt.Errorf("sloglint: Options.NoGlobal=%s: %w", opts.NoGlobal, errInvalidValue)
}
switch opts.ContextOnly {
case "", "all", "scope":
default:
return nil, fmt.Errorf("sloglint: Options.ContextOnly=%s: %w", opts.ContextOnly, errInvalidValue)
}
switch opts.KeyNamingCase {
case "", snakeCase, kebabCase, camelCase, pascalCase:
default:
return nil, fmt.Errorf("sloglint: Options.KeyNamingCase=%s: %w", opts.KeyNamingCase, errInvalidValue)
}
run(pass, opts)
return nil, nil
},
}
}
var (
errIncompatible = errors.New("incompatible options")
errInvalidValue = errors.New("invalid value")
)
func flags(opts *Options) flag.FlagSet {
fset := flag.NewFlagSet("sloglint", flag.ContinueOnError)
boolVar := func(value *bool, name, usage string) {
fset.Func(name, usage, func(s string) error {
v, err := strconv.ParseBool(s)
*value = v
return err
})
}
strVar := func(value *string, name, usage string) {
fset.Func(name, usage, func(s string) error {
*value = s
return nil
})
}
boolVar(&opts.NoMixedArgs, "no-mixed-args", "enforce not mixing key-value pairs and attributes (default true)")
boolVar(&opts.KVOnly, "kv-only", "enforce using key-value pairs only (overrides -no-mixed-args, incompatible with -attr-only)")
boolVar(&opts.AttrOnly, "attr-only", "enforce using attributes only (overrides -no-mixed-args, incompatible with -kv-only)")
strVar(&opts.NoGlobal, "no-global", "enforce not using global loggers (all|default)")
strVar(&opts.ContextOnly, "context-only", "enforce using methods that accept a context (all|scope)")
boolVar(&opts.StaticMsg, "static-msg", "enforce using static log messages")
boolVar(&opts.NoRawKeys, "no-raw-keys", "enforce using constants instead of raw keys")
strVar(&opts.KeyNamingCase, "key-naming-case", "enforce a single key naming convention (snake|kebab|camel|pascal)")
boolVar(&opts.ArgsOnSepLines, "args-on-sep-lines", "enforce putting arguments on separate lines")
fset.Func("forbidden-keys", "enforce not using specific keys (comma-separated)", func(s string) error {
opts.ForbiddenKeys = append(opts.ForbiddenKeys, strings.Split(s, ",")...)
return nil
})
return *fset
}
var slogFuncs = map[string]struct {
argsPos int
skipContextCheck bool
}{
// funcName: {argsPos, skipContextCheck}
"log/slog.With": {argsPos: 0, skipContextCheck: true},
"log/slog.Log": {argsPos: 3},
"log/slog.LogAttrs": {argsPos: 3},
"log/slog.Debug": {argsPos: 1},
"log/slog.Info": {argsPos: 1},
"log/slog.Warn": {argsPos: 1},
"log/slog.Error": {argsPos: 1},
"log/slog.DebugContext": {argsPos: 2},
"log/slog.InfoContext": {argsPos: 2},
"log/slog.WarnContext": {argsPos: 2},
"log/slog.ErrorContext": {argsPos: 2},
"(*log/slog.Logger).With": {argsPos: 0, skipContextCheck: true},
"(*log/slog.Logger).Log": {argsPos: 3},
"(*log/slog.Logger).LogAttrs": {argsPos: 3},
"(*log/slog.Logger).Debug": {argsPos: 1},
"(*log/slog.Logger).Info": {argsPos: 1},
"(*log/slog.Logger).Warn": {argsPos: 1},
"(*log/slog.Logger).Error": {argsPos: 1},
"(*log/slog.Logger).DebugContext": {argsPos: 2},
"(*log/slog.Logger).InfoContext": {argsPos: 2},
"(*log/slog.Logger).WarnContext": {argsPos: 2},
"(*log/slog.Logger).ErrorContext": {argsPos: 2},
}
var attrFuncs = map[string]struct{}{
"log/slog.String": {},
"log/slog.Int64": {},
"log/slog.Int": {},
"log/slog.Uint64": {},
"log/slog.Float64": {},
"log/slog.Bool": {},
"log/slog.Time": {},
"log/slog.Duration": {},
"log/slog.Group": {},
"log/slog.Any": {},
}
const (
snakeCase = "snake"
kebabCase = "kebab"
camelCase = "camel"
pascalCase = "pascal"
)
func run(pass *analysis.Pass, opts *Options) {
visitor := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
filter := []ast.Node{(*ast.CallExpr)(nil)}
// WithStack is ~2x slower than Preorder, use it only when stack is needed.
if opts.ContextOnly == "scope" {
visitor.WithStack(filter, func(node ast.Node, _ bool, stack []ast.Node) bool {
visit(pass, opts, node, stack)
return false
})
return
}
visitor.Preorder(filter, func(node ast.Node) {
visit(pass, opts, node, nil)
})
}
// NOTE: stack is nil if Preorder is used.
func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node) {
call := node.(*ast.CallExpr)
fn := typeutil.StaticCallee(pass.TypesInfo, call)
if fn == nil {
return
}
name := fn.FullName()
funcInfo, ok := slogFuncs[name]
if !ok {
return
}
switch opts.NoGlobal {
case "all":
if strings.HasPrefix(name, "log/slog.") || globalLoggerUsed(pass.TypesInfo, call.Fun) {
pass.Reportf(call.Pos(), "global logger should not be used")
}
case "default":
if strings.HasPrefix(name, "log/slog.") {
pass.Reportf(call.Pos(), "default logger should not be used")
}
}
// NOTE: "With" functions are not checked for context.Context.
if !funcInfo.skipContextCheck {
switch opts.ContextOnly {
case "all":
typ := pass.TypesInfo.TypeOf(call.Args[0])
if typ != nil && typ.String() != "context.Context" {
pass.Reportf(call.Pos(), "%sContext should be used instead", fn.Name())
}
case "scope":
typ := pass.TypesInfo.TypeOf(call.Args[0])
if typ != nil && typ.String() != "context.Context" && hasContextInScope(pass.TypesInfo, stack) {
pass.Reportf(call.Pos(), "%sContext should be used instead", fn.Name())
}
}
}
if opts.StaticMsg && !staticMsg(call.Args[funcInfo.argsPos-1]) {
pass.Reportf(call.Pos(), "message should be a string literal or a constant")
}
// NOTE: we assume that the arguments have already been validated by govet.
args := call.Args[funcInfo.argsPos:]
if len(args) == 0 {
return
}
var keys []ast.Expr
var attrs []ast.Expr
for i := 0; i < len(args); i++ {
typ := pass.TypesInfo.TypeOf(args[i])
if typ == nil {
continue
}
switch typ.String() {
case "string":
keys = append(keys, args[i])
i++ // skip the value.
case "log/slog.Attr":
attrs = append(attrs, args[i])
}
}
switch {
case opts.KVOnly && len(attrs) > 0:
pass.Reportf(call.Pos(), "attributes should not be used")
case opts.AttrOnly && len(attrs) < len(args):
pass.Reportf(call.Pos(), "key-value pairs should not be used")
case opts.NoMixedArgs && 0 < len(attrs) && len(attrs) < len(args):
pass.Reportf(call.Pos(), "key-value pairs and attributes should not be mixed")
}
if opts.NoRawKeys && rawKeysUsed(pass.TypesInfo, keys, attrs) {
pass.Reportf(call.Pos(), "raw keys should not be used")
}
if opts.ArgsOnSepLines && argsOnSameLine(pass.Fset, call, keys, attrs) {
pass.Reportf(call.Pos(), "arguments should be put on separate lines")
}
if len(opts.ForbiddenKeys) > 0 {
if name, found := badKeyNames(pass.TypesInfo, isForbiddenKey(opts.ForbiddenKeys), keys, attrs); found {
pass.Reportf(call.Pos(), "%q key is forbidden and should not be used", name)
}
}
switch {
case opts.KeyNamingCase == snakeCase:
if _, found := badKeyNames(pass.TypesInfo, valueChanged(strcase.ToSnake), keys, attrs); found {
pass.Reportf(call.Pos(), "keys should be written in snake_case")
}
case opts.KeyNamingCase == kebabCase:
if _, found := badKeyNames(pass.TypesInfo, valueChanged(strcase.ToKebab), keys, attrs); found {
pass.Reportf(call.Pos(), "keys should be written in kebab-case")
}
case opts.KeyNamingCase == camelCase:
if _, found := badKeyNames(pass.TypesInfo, valueChanged(strcase.ToCamel), keys, attrs); found {
pass.Reportf(call.Pos(), "keys should be written in camelCase")
}
case opts.KeyNamingCase == pascalCase:
if _, found := badKeyNames(pass.TypesInfo, valueChanged(strcase.ToPascal), keys, attrs); found {
pass.Reportf(call.Pos(), "keys should be written in PascalCase")
}
}
}
func isForbiddenKey(forbiddenKeys []string) func(string) bool {
return func(name string) bool {
return slices.Contains(forbiddenKeys, name)
}
}
func valueChanged(handler func(string) string) func(string) bool {
return func(name string) bool {
return handler(name) != name
}
}
func globalLoggerUsed(info *types.Info, expr ast.Expr) bool {
selector, ok := expr.(*ast.SelectorExpr)
if !ok {
return false
}
ident, ok := selector.X.(*ast.Ident)
if !ok {
return false
}
obj := info.ObjectOf(ident)
return obj.Parent() == obj.Pkg().Scope()
}
func hasContextInScope(info *types.Info, stack []ast.Node) bool {
for i := len(stack) - 1; i >= 0; i-- {
decl, ok := stack[i].(*ast.FuncDecl)
if !ok {
continue
}
params := decl.Type.Params
if len(params.List) == 0 || len(params.List[0].Names) == 0 {
continue
}
typ := info.TypeOf(params.List[0].Names[0])
if typ != nil && typ.String() == "context.Context" {
return true
}
}
return false
}
func staticMsg(expr ast.Expr) bool {
switch msg := expr.(type) {
case *ast.BasicLit: // e.g. slog.Info("msg")
return msg.Kind == token.STRING
case *ast.Ident: // e.g. const msg = "msg"; slog.Info(msg)
return msg.Obj != nil && msg.Obj.Kind == ast.Con
default:
return false
}
}
func rawKeysUsed(info *types.Info, keys, attrs []ast.Expr) bool {
isConst := func(expr ast.Expr) bool {
ident, ok := expr.(*ast.Ident)
return ok && ident.Obj != nil && ident.Obj.Kind == ast.Con
}
for _, key := range keys {
if !isConst(key) {
return true
}
}
for _, attr := range attrs {
switch attr := attr.(type) {
case *ast.CallExpr: // e.g. slog.Int()
fn := typeutil.StaticCallee(info, attr)
if _, ok := attrFuncs[fn.FullName()]; ok && !isConst(attr.Args[0]) {
return true
}
case *ast.CompositeLit: // slog.Attr{}
isRawKey := func(kv *ast.KeyValueExpr) bool {
return kv.Key.(*ast.Ident).Name == "Key" && !isConst(kv.Value)
}
switch len(attr.Elts) {
case 1: // slog.Attr{Key: ...} | slog.Attr{Value: ...}
kv := attr.Elts[0].(*ast.KeyValueExpr)
if isRawKey(kv) {
return true
}
case 2: // slog.Attr{..., ...} | slog.Attr{Key: ..., Value: ...}
kv1, ok := attr.Elts[0].(*ast.KeyValueExpr)
if ok {
kv2 := attr.Elts[1].(*ast.KeyValueExpr)
if isRawKey(kv1) || isRawKey(kv2) {
return true
}
} else if !isConst(attr.Elts[0]) {
return true
}
}
}
}
return false
}
func badKeyNames(info *types.Info, validationFn func(string) bool, keys, attrs []ast.Expr) (string, bool) {
for _, key := range keys {
if name, ok := getKeyName(key); ok && validationFn(name) {
return name, true
}
}
for _, attr := range attrs {
var expr ast.Expr
switch attr := attr.(type) {
case *ast.CallExpr: // e.g. slog.Int()
fn := typeutil.StaticCallee(info, attr)
if fn == nil {
continue
}
if _, ok := attrFuncs[fn.FullName()]; !ok {
continue
}
expr = attr.Args[0]
case *ast.CompositeLit: // slog.Attr{}
switch len(attr.Elts) {
case 1: // slog.Attr{Key: ...} | slog.Attr{Value: ...}
if kv := attr.Elts[0].(*ast.KeyValueExpr); kv.Key.(*ast.Ident).Name == "Key" {
expr = kv.Value
}
case 2: // slog.Attr{..., ...} | slog.Attr{Key: ..., Value: ...}
expr = attr.Elts[0]
if kv1, ok := attr.Elts[0].(*ast.KeyValueExpr); ok && kv1.Key.(*ast.Ident).Name == "Key" {
expr = kv1.Value
}
if kv2, ok := attr.Elts[1].(*ast.KeyValueExpr); ok && kv2.Key.(*ast.Ident).Name == "Key" {
expr = kv2.Value
}
}
}
if name, ok := getKeyName(expr); ok && validationFn(name) {
return name, true
}
}
return "", false
}
func getKeyName(expr ast.Expr) (string, bool) {
if expr == nil {
return "", false
}
if ident, ok := expr.(*ast.Ident); ok {
if ident.Obj == nil || ident.Obj.Decl == nil || ident.Obj.Kind != ast.Con {
return "", false
}
if spec, ok := ident.Obj.Decl.(*ast.ValueSpec); ok && len(spec.Values) > 0 {
// TODO: support len(spec.Values) > 1; e.g. "const foo, bar = 1, 2"
expr = spec.Values[0]
}
}
if lit, ok := expr.(*ast.BasicLit); ok && lit.Kind == token.STRING {
// string literals are always quoted.
value, err := strconv.Unquote(lit.Value)
if err != nil {
panic("unreachable")
}
return value, true
}
return "", false
}
func argsOnSameLine(fset *token.FileSet, call ast.Expr, keys, attrs []ast.Expr) bool {
if len(keys)+len(attrs) <= 1 {
return false // special case: slog.Info("msg", "key", "value") is ok.
}
l := len(keys) + len(attrs) + 1
args := make([]ast.Expr, 0, l)
args = append(args, call)
args = append(args, keys...)
args = append(args, attrs...)
lines := make(map[int]struct{}, l)
for _, arg := range args {
line := fset.Position(arg.Pos()).Line
if _, ok := lines[line]; ok {
return true
}
lines[line] = struct{}{}
}
return false
}