♲ 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:
parent
d34363b8c0
commit
9f05f933dd
21 changed files with 338 additions and 360 deletions
|
|
@ -1,12 +1,13 @@
|
|||
package formatters
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"codeberg.org/danjones000/my-log/config"
|
||||
)
|
||||
|
||||
type formatMaker func(config.Formatters) (Formatter, error)
|
||||
type formatMaker func(config map[string]any) (Formatter, error)
|
||||
|
||||
var formatterMap = map[string]formatMaker{
|
||||
"plain": newPlain,
|
||||
|
|
@ -14,23 +15,22 @@ var formatterMap = map[string]formatMaker{
|
|||
"zero": newNull,
|
||||
}
|
||||
|
||||
func Preferred() (f Formatter, err error) {
|
||||
conf, err := config.Load()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
std, _ := conf.Outputs.Stdout()
|
||||
return New(std.Format)
|
||||
func Preferred(ctx context.Context) (f Formatter, err error) {
|
||||
v, _ := config.RetrieveFromContext(ctx)
|
||||
format := v.GetString("output.stdout.config.format")
|
||||
return New(ctx, format)
|
||||
}
|
||||
|
||||
func New(kind string) (f Formatter, err error) {
|
||||
conf, err := config.Load()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
func New(ctx context.Context, kind string) (f Formatter, err error) {
|
||||
_, c := config.RetrieveFromContext(ctx)
|
||||
conf := c.Formatters
|
||||
|
||||
if make, ok := formatterMap[kind]; ok {
|
||||
return make(conf.Formatters)
|
||||
var formatterConf map[string]any
|
||||
if cf, ok := conf[kind]; ok {
|
||||
formatterConf = cf
|
||||
}
|
||||
return make(formatterConf)
|
||||
}
|
||||
|
||||
return nil, errors.New("unimplemented")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue