Skip to content

Commit

Permalink
chore: Migrate logger from zerolog to slog
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Sep 23, 2024
1 parent 777d6c5 commit 73f03c9
Show file tree
Hide file tree
Showing 13 changed files with 232 additions and 207 deletions.
14 changes: 5 additions & 9 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"strings"
Expand All @@ -15,7 +16,6 @@ import (
"github.com/clevyr/yampl/internal/visitor"
"github.com/mattn/go-isatty"
"github.com/muesli/termenv"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
Expand All @@ -38,7 +38,7 @@ func New(opts ...Option) *cobra.Command {
conf := config.New()
conf.RegisterFlags(cmd)
conf.RegisterCompletions(cmd)
visitor.RegisterCompletion(cmd, conf)
visitor.RegisterCompletion(cmd)
cmd.SetContext(config.WithContext(context.Background(), conf))

for _, opt := range opts {
Expand All @@ -55,12 +55,8 @@ func validArgs(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCom
var ErrStdinInplace = errors.New("-i or --inplace may not be used with stdin")

func run(cmd *cobra.Command, args []string) error {
conf, ok := config.FromContext(cmd.Context())
if !ok {
panic("config missing from command context")
}

if err := conf.Load(cmd); err != nil {
conf, err := config.Load(cmd)
if err != nil {
return err
}

Expand Down Expand Up @@ -173,7 +169,7 @@ func openAndTemplateFile(conf *config.Config, w io.Writer, dir, path string, wit
}

if err := os.Rename(temp.Name(), path); err != nil {
log.Trace().Msg("failed to rename file, attempting to copy contents")
slog.Debug("Failed to rename file. Attempting to copy contents.")

in, err := os.Open(temp.Name())
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ require (
github.com/Masterminds/sprig/v3 v3.3.0
github.com/fatih/color v1.17.0
github.com/goccy/go-yaml v1.12.0
github.com/lmittmann/tint v1.0.5
github.com/mattn/go-isatty v0.0.20
github.com/muesli/termenv v0.15.2
github.com/rs/zerolog v1.33.0
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.9.0
Expand Down
10 changes: 2 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand All @@ -19,7 +18,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/goccy/go-yaml v1.12.0 h1:/1WHjnMsI1dlIBQutrvSMGZRQufVO3asrHfTwfACoPM=
github.com/goccy/go-yaml v1.12.0/go.mod h1:wKnAMd44+9JAAnGQpWVEgBzGt3YuTaQ4uXoHvE4m7WU=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand All @@ -32,12 +30,13 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lmittmann/tint v1.0.5 h1:NQclAutOfYsqs2F1Lenue6OoWCajs5wJcP3DfWVpePw=
github.com/lmittmann/tint v1.0.5/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
Expand All @@ -48,16 +47,12 @@ github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zx
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
Expand All @@ -74,7 +69,6 @@ golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU=
Expand Down
18 changes: 2 additions & 16 deletions internal/config/completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package config
import (
"errors"

"github.com/rs/zerolog"
"github.com/spf13/cobra"
)

Expand All @@ -12,11 +11,6 @@ const (
Zsh = "zsh"
Fish = "fish"
Powershell = "powershell"

Auto = "auto"
Color = "color"
Plain = "plain"
JSON = "json"
)

func (c *Config) RegisterCompletions(cmd *cobra.Command) {
Expand All @@ -31,20 +25,12 @@ func (c *Config) RegisterCompletions(cmd *cobra.Command) {
cmd.RegisterFlagCompletionFunc(StripFlag, BoolCompletion),
cmd.RegisterFlagCompletionFunc(LogLevelFlag,
func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{
zerolog.TraceLevel.String(),
zerolog.DebugLevel.String(),
zerolog.InfoLevel.String(),
zerolog.WarnLevel.String(),
zerolog.ErrorLevel.String(),
zerolog.FatalLevel.String(),
zerolog.PanicLevel.String(),
}, cobra.ShellCompDirectiveNoFileComp
return LogLevelStrings(), cobra.ShellCompDirectiveNoFileComp
},
),
cmd.RegisterFlagCompletionFunc(LogFormatFlag,
func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{Auto, Color, Plain, JSON}, cobra.ShellCompDirectiveNoFileComp
return LogFormatStrings(), cobra.ShellCompDirectiveNoFileComp
},
),
cmd.RegisterFlagCompletionFunc(CompletionFlag,
Expand Down
8 changes: 5 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package config

import (
"log/slog"
"strings"

"github.com/clevyr/yampl/internal/config/flag"
"github.com/rs/zerolog"
)

type Config struct {
Expand Down Expand Up @@ -38,7 +40,7 @@ func New() *Config {

IgnoreUnsetErrors: true,

LogLevel: zerolog.InfoLevel.String(),
LogFormat: Auto,
LogLevel: strings.ToLower(slog.LevelInfo.String()),
LogFormat: FormatAuto.String(),
}
}
6 changes: 3 additions & 3 deletions internal/config/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package config
import (
"bytes"
"errors"
"log/slog"

"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -66,13 +66,13 @@ func (c *Config) RegisterFlags(cmd *cobra.Command) {
panic(err)
}

initLog(cmd)
c.InitLog(cmd.ErrOrStderr())
cmd.Flags().SetOutput(DeprecatedWriter{})
}

type DeprecatedWriter struct{}

func (d DeprecatedWriter) Write(b []byte) (int, error) {
log.Warn().Msg(string(bytes.TrimSpace(b)))
slog.Warn(string(bytes.TrimSpace(b)))
return len(b), nil
}
27 changes: 17 additions & 10 deletions internal/config/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ import (

const EnvPrefix = "YAMPL_"

func (c *Config) Load(cmd *cobra.Command) error {
var ErrCmdMissingConfig = errors.New("config missing from command context")

func Load(cmd *cobra.Command) (*Config, error) {
conf, ok := FromContext(cmd.Context())
if !ok {
return nil, ErrCmdMissingConfig
}

IgnoredEnvs := []string{
CompletionFlag,
}
Expand All @@ -30,27 +37,27 @@ func (c *Config) Load(cmd *cobra.Command) error {
}
})
if len(errs) != 0 {
return errors.Join(errs...)
return nil, errors.Join(errs...)
}

initLog(cmd)
conf.InitLog(cmd.ErrOrStderr())

if !strings.HasPrefix(c.Prefix, "#") {
c.Prefix = "#" + c.Prefix
if !strings.HasPrefix(conf.Prefix, "#") {
conf.Prefix = "#" + conf.Prefix
}

c.Vars.Fill(c.valuesStringToString.Value())
conf.Vars.Fill(conf.valuesStringToString.Value())

if f := cmd.Flags().Lookup(FailFlag); f.Changed {
val, err := cmd.Flags().GetBool(FailFlag)
if err != nil {
return err
return nil, err
}
c.IgnoreUnsetErrors = !val
c.IgnoreTemplateErrors = !val
conf.IgnoreUnsetErrors = !val
conf.IgnoreTemplateErrors = !val
}

return nil
return conf, nil
}

func EnvName(name string) string {
Expand Down
109 changes: 58 additions & 51 deletions internal/config/log.go
Original file line number Diff line number Diff line change
@@ -1,72 +1,79 @@
package config

import (
"fmt"
"io"
"log/slog"
"os"
"strings"
"time"

"github.com/clevyr/yampl/internal/colorize"
"github.com/fatih/color"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
)

func logLevel(level string) zerolog.Level {
parsedLevel, err := zerolog.ParseLevel(level)
if err != nil || parsedLevel == zerolog.NoLevel {
if level == "warning" {
parsedLevel = zerolog.WarnLevel
} else {
log.Warn().Str("value", level).Msg("invalid log level. defaulting to info.")
parsedLevel = zerolog.InfoLevel
}
//go:generate enumer -type LogFormat -trimprefix Format -transform lower -text

type LogFormat uint8

const (
FormatAuto LogFormat = iota
FormatColor
FormatPlain
FormatJSON
)

func (c *Config) InitLog(w io.Writer) {
var level slog.Level
if err := level.UnmarshalText([]byte(c.LogLevel)); err != nil {
slog.Warn("Invalid log level. Defaulting to info.", "value", c.LogLevel)
level = slog.LevelInfo
c.LogLevel = strings.ToLower(level.String())
}
return parsedLevel

var format LogFormat
if err := format.UnmarshalText([]byte(c.LogFormat)); err != nil {
slog.Warn("Invalid log format. Defaulting to auto.", "value", c.LogFormat)
format = FormatAuto
c.LogFormat = format.String()
}

InitLog(w, level, format)
}

func logFormat(out io.Writer, format string) io.Writer {
func InitLog(w io.Writer, level slog.Level, format LogFormat) {
switch format {
case JSON:
return out
case FormatJSON:
slog.SetDefault(slog.New(
slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: level,
}),
))
default:
sprintf := fmt.Sprintf
var useColor bool
var color bool
switch format {
case Auto:
if useColor = colorize.ShouldColor(out); !useColor {
break
case FormatAuto:
if f, ok := w.(*os.File); ok {
color = isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd())
}
fallthrough
case Color:
useColor = true
color.NoColor = false
sprintf = color.New(color.Bold).Sprintf
case Plain:
default:
log.Warn().Str("value", format).Msg("invalid log formatter. defaulting to auto.")
return logFormat(out, Auto)
case FormatColor:
color = true
}

return zerolog.ConsoleWriter{
Out: out,
NoColor: !useColor,
FormatMessage: func(i any) string {
return sprintf("%-45s", i)
},
}
slog.SetDefault(slog.New(
tint.NewHandler(w, &tint.Options{
Level: level,
TimeFormat: time.DateTime,
NoColor: !color,
}),
))
}
}

func initLog(cmd *cobra.Command) {
level, err := cmd.Flags().GetString("log-level")
if err != nil {
panic(err)
}
zerolog.SetGlobalLevel(logLevel(level))

format, err := cmd.Flags().GetString("log-format")
if err != nil {
panic(err)
func LogLevelStrings() []string {
return []string{
strings.ToLower(slog.LevelDebug.String()),
strings.ToLower(slog.LevelInfo.String()),
strings.ToLower(slog.LevelWarn.String()),
strings.ToLower(slog.LevelError.String()),
}
log.Logger = log.Output(logFormat(cmd.ErrOrStderr(), format))
}
Loading

0 comments on commit 73f03c9

Please sign in to comment.