forked from samber/slog-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
groups.go
39 lines (32 loc) · 933 Bytes
/
groups.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package slogcommon
import (
"log/slog"
"slices"
"github.com/samber/lo"
)
func AppendAttrsToGroup(groups []string, actualAttrs []slog.Attr, newAttrs ...slog.Attr) []slog.Attr {
actualAttrs = slices.Clone(actualAttrs)
if len(groups) == 0 {
return UniqAttrs(append(actualAttrs, newAttrs...))
}
for i := range actualAttrs {
attr := actualAttrs[i]
if attr.Key == groups[0] && attr.Value.Kind() == slog.KindGroup {
actualAttrs[i] = slog.Group(groups[0], lo.ToAnySlice(AppendAttrsToGroup(groups[1:], attr.Value.Group(), newAttrs...))...)
return actualAttrs
}
}
return UniqAttrs(
append(
actualAttrs,
slog.Group(
groups[0],
lo.ToAnySlice(AppendAttrsToGroup(groups[1:], []slog.Attr{}, newAttrs...))...,
),
),
)
}
// @TODO: should be recursive
func UniqAttrs(attrs []slog.Attr) []slog.Attr {
return slices.CompactFunc(attrs, func(a slog.Attr, b slog.Attr) bool { return a.Key == b.Key })
}