Skip to content

Commit

Permalink
fix(no-raw-keys): do not report constants from other packages (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacobbrewer1 authored Feb 6, 2025
1 parent df1283f commit 72654a4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
13 changes: 12 additions & 1 deletion sloglint.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
Expand Down
3 changes: 3 additions & 0 deletions testdata/src/no_raw_keys/keys/keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package keys

const Foo = "foo"
6 changes: 5 additions & 1 deletion testdata/src/no_raw_keys/no_raw_keys.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package no_raw_keys

import "log/slog"
import (
"log/slog"
"no_raw_keys/keys"
)

const foo = "foo"

Expand All @@ -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{})
Expand Down

0 comments on commit 72654a4

Please sign in to comment.