Skip to content

Commit

Permalink
refactor: use maps instead of sorted slices
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane committed Sep 23, 2023
1 parent 62eb5ff commit 1adfde8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 48 deletions.
75 changes: 31 additions & 44 deletions sloggen.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"bytes"
"cmp"
"fmt"
"go/format"
"io"
Expand All @@ -14,6 +13,8 @@ import (
"gopkg.in/yaml.v3"
)

// NOTE: when iterating over a map, text/template visits the elements in sorted key order.

var tmpl = template.Must(template.New("").Funcs(funcs).Parse(
`// Code generated by go-simpler.org/sloggen. DO NOT EDIT.
Expand All @@ -23,24 +24,24 @@ package {{$.Pkg}}
import "{{.}}"
{{end}}
{{range $.Levels -}}
const Level{{title .Name}} = slog.Level({{.Severity}})
{{range $severity, $name := $.Levels -}}
const Level{{title $name}} = slog.Level({{$severity}})
{{end}}
{{range $.Consts -}}
const {{snakeToCamel .}} = "{{.}}"
{{end}}
{{range $.Attrs -}}
func {{snakeToCamel .Key}}(value {{.Type}}) slog.Attr { return slog.{{slogFunc .Type}}("{{.Key}}", value) }
{{range $key, $type := $.Attrs -}}
func {{snakeToCamel $key}}(value {{$type}}) slog.Attr { return slog.{{slogFunc $type}}("{{$key}}", value) }
{{end}}
{{if $.HasCustomLevels}}
func ParseLevel(s string) (slog.Level, error) {
switch strings.ToUpper(s) {
{{range $.Levels -}}
case "{{upper .Name}}":
return Level{{title .Name}}, nil
{{range $_, $name := $.Levels -}}
case "{{upper $name}}":
return Level{{title $name}}, nil
{{end -}}
default:
return 0, fmt.Errorf("slog: level string %q: unknown name", s)
Expand All @@ -52,9 +53,9 @@ func ReplaceAttr(_ []string, attr slog.Attr) slog.Attr {
return attr
}
switch attr.Value.Any().(slog.Level) {
{{range $.Levels -}}
case Level{{title .Name}}:
attr.Value = slog.StringValue("{{upper .Name}}")
{{range $_, $name := $.Levels -}}
case Level{{title $name}}:
attr.Value = slog.StringValue("{{upper $name}}")
{{end -}}
}
return attr
Expand All @@ -63,9 +64,9 @@ func ReplaceAttr(_ []string, attr slog.Attr) slog.Attr {
{{if $l := $.Logger}}
type Logger struct{ Logger *slog.Logger }
{{range $l.Levels}}
func (l *Logger) {{title .Name}}({{if $l.Context}}ctx context.Context, {{end}}msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) {
l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, {{if not $.HasCustomLevels}}slog.{{end}}Level{{title .Name}}, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}})
{{range $_, $name := $l.Levels}}
func (l *Logger) {{title $name}}({{if $l.Context}}ctx context.Context, {{end}}msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) {
l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, {{if not $.HasCustomLevels}}slog.{{end}}Level{{title $name}}, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}})
}
{{end}}
func (l *Logger) log(ctx context.Context, level slog.Level, msg string, {{if $l.AttrAPI}}attrs []slog.Attr{{else}}args []any{{end}}) {
Expand Down Expand Up @@ -106,22 +107,14 @@ type (
config struct {
Pkg string
Imports []string
Levels []level
Levels map[int]string // severity:name
Consts []string
Attrs []attr
Attrs map[string]string // key:type
Logger *logger
HasCustomLevels bool
}
level struct {
Name string
Severity int
}
attr struct {
Key string
Type string
}
logger struct {
Levels []level
Levels map[int]string
AttrAPI bool
Context bool
}
Expand All @@ -131,9 +124,9 @@ func readConfig(r io.Reader) (*config, error) {
var data struct {
Pkg string `yaml:"pkg"`
Imports []string `yaml:"imports"`
Levels []map[string]int `yaml:"levels"` // name:severity
Levels []map[string]int `yaml:"levels"`
Consts []string `yaml:"consts"`
Attrs []map[string]string `yaml:"attrs"` // key:type
Attrs []map[string]string `yaml:"attrs"`
Logger *struct {
API string `yaml:"api"`
Context bool `yaml:"context"`
Expand All @@ -146,37 +139,31 @@ func readConfig(r io.Reader) (*config, error) {
cfg := config{
Pkg: data.Pkg,
Imports: data.Imports,
Levels: make([]level, len(data.Levels)),
Levels: make(map[int]string, len(data.Levels)),
Consts: data.Consts,
Attrs: make([]attr, len(data.Attrs)),
Attrs: make(map[string]string, len(data.Attrs)),
Logger: nil,
HasCustomLevels: false,
}
if cfg.Pkg == "" {
cfg.Pkg = "slogx"
}

for i, m := range data.Levels {
for _, m := range data.Levels {
name, severity := getKV(m)
cfg.Levels[i] = level{name, severity}
cfg.Levels[severity] = name

switch slog.Level(severity) {
case slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError:
default:
cfg.HasCustomLevels = true
}
}
slices.SortFunc(cfg.Levels, func(l1, l2 level) int {
return cmp.Compare(l1.Severity, l2.Severity)
})

for i, m := range data.Attrs {
for _, m := range data.Attrs {
key, typ := getKV(m)
cfg.Attrs[i] = attr{key, typ}
cfg.Attrs[key] = typ
}
slices.SortFunc(cfg.Attrs, func(a1, a2 attr) int {
return cmp.Compare(a1.Key, a2.Key)
})

if data.Logger != nil {
cfg.Logger = &logger{
Expand All @@ -186,11 +173,11 @@ func readConfig(r io.Reader) (*config, error) {
}

if len(cfg.Levels) == 0 {
cfg.Logger.Levels = []level{
{"debug", int(slog.LevelDebug)},
{"info", int(slog.LevelInfo)},
{"warn", int(slog.LevelWarn)},
{"error", int(slog.LevelError)},
cfg.Logger.Levels = map[int]string{
int(slog.LevelDebug): "debug",
int(slog.LevelInfo): "info",
int(slog.LevelWarn): "warn",
int(slog.LevelError): "error",
}
}

Expand Down
8 changes: 4 additions & 4 deletions sloggen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import (
var cfg = config{
Pkg: "test",
Imports: []string{"fmt", "log/slog", "strings", "time"},
Levels: []level{{Name: "custom", Severity: -8}},
Levels: map[int]string{-8: "custom"},
Consts: []string{"foo"},
Attrs: []attr{
{Key: "bar", Type: "time.Time"},
{Key: "baz", Type: "time.Duration"},
Attrs: map[string]string{
"bar": "time.Time",
"baz": "time.Duration",
},
HasCustomLevels: true,
}
Expand Down

0 comments on commit 1adfde8

Please sign in to comment.