Skip to content

Commit

Permalink
fix: handle unpacked slice (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane authored Jun 21, 2024
1 parent 8307697 commit 878f379
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
7 changes: 5 additions & 2 deletions sloglint.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down
3 changes: 3 additions & 0 deletions testdata/src/attr_only/attr_only.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}
3 changes: 3 additions & 0 deletions testdata/src/kv_only/kv_only.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}

0 comments on commit 878f379

Please sign in to comment.