♲ 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,22 +1,35 @@
package formatters
import (
"context"
"fmt"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/internal/testutil/bep"
"codeberg.org/danjones000/my-log/models"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func setupJsonTestContext(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
v.Set("formatters.json.pretty_print", false)
return config.AddToContext(t.Context(), v)
}
func TestJsonName(t *testing.T) {
f, _ := New("json")
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
be.Equal(t, f.Name(), "json")
}
func TestJsonMeta(t *testing.T) {
f, _ := New("json")
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
exp := `{"foo":42}`
o, err := f.Meta(m)
@ -25,8 +38,9 @@ func TestJsonMeta(t *testing.T) {
}
func TestJsonEntry(t *testing.T) {
ctx := setupJsonTestContext(t)
when := time.Now()
f, _ := New("json")
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
e := models.Entry{
Title: "Homer",
@ -40,8 +54,9 @@ func TestJsonEntry(t *testing.T) {
}
func TestJsonLog(t *testing.T) {
ctx := setupJsonTestContext(t)
when := time.Now()
f, _ := New("json")
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
e := models.Entry{
Title: "Homer",
@ -56,7 +71,8 @@ func TestJsonLog(t *testing.T) {
}
func TestJsonNoLogs(t *testing.T) {
f, _ := New("json")
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
o, err := f.Logs([]models.Log{})
var exp []byte
be.Err(t, err, nil)
@ -64,7 +80,8 @@ func TestJsonNoLogs(t *testing.T) {
}
func TestJsonErr(t *testing.T) {
f, _ := New("json")
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
o, err := f.Meta(models.Meta{Key: "foo", Value: make(chan bool)})
var exp []byte
be.Err(t, err)