Allow formatters to use sub-config with their own config structs

This commit is contained in:
Dan Jones 2026-03-08 23:29:36 -05:00
commit 6c6a959af4
4 changed files with 21 additions and 21 deletions

View file

@ -3,23 +3,24 @@ package formatters
import (
"bytes"
"encoding/json"
"fmt"
"time"
"codeberg.org/danjones000/my-log/models"
"github.com/spf13/viper"
)
func newJson(ff map[string]any) (Formatter, error) {
prettyPrint := false
if jf, ok := ff["json"].(map[string]any); ok {
if pp, ok := jf["pretty_print"].(bool); ok {
prettyPrint = pp
}
func newJson(ff *viper.Viper) (Formatter, error) {
js := new(Json)
err := ff.Unmarshal(js)
if err != nil {
return nil, fmt.Errorf("failed to get json config: %w", err)
}
return &Json{prettyPrint}, nil
return js, nil
}
type Json struct {
prettPrint bool
prettPrint bool `mapstructure:"pretty_print"`
}
func (js *Json) Name() string {

View file

@ -2,12 +2,13 @@ package formatters
import (
"context"
"errors"
"fmt"
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/viper"
)
type formatMaker func(config map[string]any) (Formatter, error)
type formatMaker func(config *viper.Viper) (Formatter, error)
var formatterMap = map[string]formatMaker{
"plain": newPlain,
@ -22,18 +23,14 @@ func Preferred(ctx context.Context) (f Formatter, err error) {
}
func New(ctx context.Context, kind string) (f Formatter, err error) {
_, c := config.RetrieveFromContext(ctx)
conf := c.Formatters
v, _ := config.RetrieveFromContext(ctx)
formatterConf := v.Sub("formatters." + kind)
if make, ok := formatterMap[kind]; ok {
var formatterConf map[string]any
if cf, ok := conf[kind]; ok {
formatterConf = cf
}
return make(formatterConf)
if maker, ok := formatterMap[kind]; ok {
return maker(formatterConf)
}
return nil, errors.New("unimplemented")
return nil, fmt.Errorf("unimplemented format: %s", kind)
}
func Kinds() []string {

View file

@ -2,9 +2,10 @@ package formatters
import (
"codeberg.org/danjones000/my-log/models"
"github.com/spf13/viper"
)
func newNull(ff map[string]any) (Formatter, error) {
func newNull(ff *viper.Viper) (Formatter, error) {
return &Null{}, nil
}

View file

@ -5,9 +5,10 @@ import (
"codeberg.org/danjones000/my-log/models"
"codeberg.org/danjones000/my-log/tools"
"github.com/spf13/viper"
)
func newPlain(ff map[string]any) (Formatter, error) {
func newPlain(ff *viper.Viper) (Formatter, error) {
return &PlainText{}, nil
}