- 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_*)
53 lines
1 KiB
Go
53 lines
1 KiB
Go
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type confKeyType uint8
|
|
|
|
const (
|
|
_ confKeyType = iota
|
|
viperKey
|
|
)
|
|
|
|
func RetrieveFromContext(ctx context.Context) (*viper.Viper, Config) {
|
|
v, ok := ctx.Value(viperKey).(*viper.Viper)
|
|
if !ok {
|
|
panic("config not found in context")
|
|
}
|
|
var c Config
|
|
if err := v.Unmarshal(&c); err != nil {
|
|
panic(fmt.Errorf("failed to unmarshal config: %w", err))
|
|
}
|
|
return v, c
|
|
}
|
|
|
|
func AddToContext(ctx context.Context, v *viper.Viper) context.Context {
|
|
return context.WithValue(ctx, viperKey, v)
|
|
}
|
|
|
|
func New(ctx context.Context) (context.Context, *viper.Viper, error) {
|
|
v := viper.New()
|
|
v.SetConfigType("toml")
|
|
|
|
if err := v.ReadConfig(bytes.NewBufferString(DefaultStr())); err != nil {
|
|
return ctx, nil, err
|
|
}
|
|
|
|
v.SetConfigFile(DefaultPath())
|
|
v.SetEnvPrefix("MYLOG")
|
|
v.AutomaticEnv()
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
|
|
|
|
if err := v.ReadInConfig(); err != nil {
|
|
return ctx, nil, err
|
|
}
|
|
|
|
return AddToContext(ctx, v), v, nil
|
|
}
|