Skip to content

Commit 72654a4

Browse files
authored
fix(no-raw-keys): do not report constants from other packages (#67)
1 parent df1283f commit 72654a4

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

Diff for: sloglint.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,18 @@ func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node)
265265

266266
if opts.NoRawKeys {
267267
forEachKey(pass.TypesInfo, keys, attrs, func(key ast.Expr) {
268-
if ident, ok := key.(*ast.Ident); !ok || ident.Obj == nil || ident.Obj.Kind != ast.Con {
268+
if selector, ok := key.(*ast.SelectorExpr); ok {
269+
key = selector.Sel // the key is defined in another package, e.g. pkg.ConstKey.
270+
}
271+
isConst := false
272+
if ident, ok := key.(*ast.Ident); ok {
273+
if obj := pass.TypesInfo.ObjectOf(ident); obj != nil {
274+
if _, ok := obj.(*types.Const); ok {
275+
isConst = true
276+
}
277+
}
278+
}
279+
if !isConst {
269280
pass.Reportf(call.Pos(), "raw keys should not be used")
270281
}
271282
})

Diff for: testdata/src/no_raw_keys/keys/keys.go

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package keys
2+
3+
const Foo = "foo"

Diff for: testdata/src/no_raw_keys/no_raw_keys.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package no_raw_keys
22

3-
import "log/slog"
3+
import (
4+
"log/slog"
5+
"no_raw_keys/keys"
6+
)
47

58
const foo = "foo"
69

@@ -11,6 +14,7 @@ func Foo(value int) slog.Attr {
1114
func tests() {
1215
slog.Info("msg")
1316
slog.Info("msg", foo, 1)
17+
slog.Info("msg", keys.Foo, 1)
1418
slog.Info("msg", Foo(1))
1519
slog.Info("msg", slog.Int(foo, 1))
1620
slog.Info("msg", slog.Attr{})

0 commit comments

Comments
 (0)