diff --git a/sloglint.go b/sloglint.go index bff37b7..97199b4 100644 --- a/sloglint.go +++ b/sloglint.go @@ -265,7 +265,18 @@ func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node) if opts.NoRawKeys { forEachKey(pass.TypesInfo, keys, attrs, func(key ast.Expr) { - if ident, ok := key.(*ast.Ident); !ok || ident.Obj == nil || ident.Obj.Kind != ast.Con { + if selector, ok := key.(*ast.SelectorExpr); ok { + key = selector.Sel // the key is defined in another package, e.g. pkg.ConstKey. + } + isConst := false + if ident, ok := key.(*ast.Ident); ok { + if obj := pass.TypesInfo.ObjectOf(ident); obj != nil { + if _, ok := obj.(*types.Const); ok { + isConst = true + } + } + } + if !isConst { pass.Reportf(call.Pos(), "raw keys should not be used") } }) diff --git a/testdata/src/no_raw_keys/keys/keys.go b/testdata/src/no_raw_keys/keys/keys.go new file mode 100644 index 0000000..a09a176 --- /dev/null +++ b/testdata/src/no_raw_keys/keys/keys.go @@ -0,0 +1,3 @@ +package keys + +const Foo = "foo" diff --git a/testdata/src/no_raw_keys/no_raw_keys.go b/testdata/src/no_raw_keys/no_raw_keys.go index c8f5f7e..20c1b02 100644 --- a/testdata/src/no_raw_keys/no_raw_keys.go +++ b/testdata/src/no_raw_keys/no_raw_keys.go @@ -1,6 +1,9 @@ package no_raw_keys -import "log/slog" +import ( + "log/slog" + "no_raw_keys/keys" +) const foo = "foo" @@ -11,6 +14,7 @@ func Foo(value int) slog.Attr { func tests() { slog.Info("msg") slog.Info("msg", foo, 1) + slog.Info("msg", keys.Foo, 1) slog.Info("msg", Foo(1)) slog.Info("msg", slog.Int(foo, 1)) slog.Info("msg", slog.Attr{})