From 878f37984f6dc58aea8295e285c1bf90bc848b4e Mon Sep 17 00:00:00 2001 From: Tom <73077675+tmzane@users.noreply.github.com> Date: Fri, 21 Jun 2024 18:28:31 +0300 Subject: [PATCH] fix: handle unpacked slice (#51) --- sloglint.go | 7 +++++-- testdata/src/attr_only/attr_only.go | 3 +++ testdata/src/kv_only/kv_only.go | 3 +++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/sloglint.go b/sloglint.go index ee6e5e8..bff37b7 100644 --- a/sloglint.go +++ b/sloglint.go @@ -242,21 +242,24 @@ func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node) 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]) + case "[]any", "[]log/slog.Attr": + continue // the last argument may be an unpacked slice, skip it. } } switch { case opts.KVOnly && len(attrs) > 0: pass.Reportf(call.Pos(), "attributes should not be used") - case opts.AttrOnly && len(attrs) < len(args): + case opts.AttrOnly && len(keys) > 0: pass.Reportf(call.Pos(), "key-value pairs should not be used") - case opts.NoMixedArgs && 0 < len(attrs) && len(attrs) < len(args): + case opts.NoMixedArgs && len(attrs) > 0 && len(keys) > 0: pass.Reportf(call.Pos(), "key-value pairs and attributes should not be mixed") } diff --git a/testdata/src/attr_only/attr_only.go b/testdata/src/attr_only/attr_only.go index b189d2a..1b4f44e 100644 --- a/testdata/src/attr_only/attr_only.go +++ b/testdata/src/attr_only/attr_only.go @@ -12,4 +12,7 @@ func tests() { slog.Info("msg", "foo", 1, "bar", 2) // want `key-value pairs should not be used` slog.Info("msg", "foo", 1, slog.Int("bar", 2)) // want `key-value pairs should not be used` slog.With("foo", 1, slog.Int("bar", 2)).Info("msg") // want `key-value pairs should not be used` + + args := []slog.Attr{slog.Int("foo", 1), slog.Int("bar", 2)} + slog.LogAttrs(nil, slog.LevelInfo, "msg", args...) } diff --git a/testdata/src/kv_only/kv_only.go b/testdata/src/kv_only/kv_only.go index 6b3d37d..f498e89 100644 --- a/testdata/src/kv_only/kv_only.go +++ b/testdata/src/kv_only/kv_only.go @@ -15,4 +15,7 @@ func tests() { slog.With(slog.Int("foo", 1)).Info("msg") // want `attributes should not be used` slog.With(slog.Int("foo", 1), slog.Int("bar", 2)).Info("msg") // want `attributes should not be used` slog.With("foo", 1, slog.Int("bar", 2)).Info("msg") // want `attributes should not be used` + + args := []any{"foo", 1, "bar", 2} + slog.Log(nil, slog.LevelInfo, "msg", args...) }