♲ Refactor configuration to use viper with context propagation

- Replace global ConfigPath and Overrides with viper-based configuration
- Add viper.New() to create configurable viper instances
- Store viper and unmarshaled Config struct in context for testability
- Add RetrieveFromContext and AddToContext helper functions
- Update files.Append to accept context and retrieve config from it
- Update formatters.Preferred and formatters.New to accept context
- Add PersistentPreRunE in CLI to create and configure viper instance
- Support -c flag for custom config file path
- Support -v flag for config value overrides
- Update all test files to create viper and add to context
- Remove unused config types and load functions
- Add viper as dependency with automatic env var support (MYLOG_*)
This commit is contained in:
Dan Jones 2026-03-08 22:59:33 -05:00
commit 9f05f933dd
21 changed files with 338 additions and 360 deletions

View file

@ -1,13 +1,13 @@
package formatters
import (
"fmt"
"os"
"context"
"slices"
"testing"
"codeberg.org/danjones000/my-log/config"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func TestKinds(t *testing.T) {
@ -17,33 +17,25 @@ func TestKinds(t *testing.T) {
}
}
func setupNewTest(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
v.Set("output.stdout.config.format", "plain")
v.Set("formatters.json.pretty_print", false)
return config.AddToContext(t.Context(), v)
}
func TestNewUnsupported(t *testing.T) {
f, err := New("nope")
ctx := setupNewTest(t)
f, err := New(ctx, "nope")
be.Equal(t, f, nil)
be.Err(t, err)
}
func TestNewCantGetConfig(t *testing.T) {
f, _ := os.CreateTemp("", "test")
oldConf := config.ConfigPath
config.ConfigPath = f.Name()
defer f.Close()
defer func() {
config.ConfigPath = oldConf
}()
fmt.Fprint(f, `{"not":"toml"}`)
form, err := New("plain")
be.Equal(t, form, nil)
be.Err(t, err)
form, err = Preferred()
be.Equal(t, form, nil)
be.Err(t, err)
}
func TestPreferred(t *testing.T) {
form, err := Preferred()
ctx := setupNewTest(t)
form, err := Preferred(ctx)
be.Err(t, err, nil)
be.True(t, form != nil)
}