stillbox/pkg/config/parse.go

70 lines
1.5 KiB
Go
Raw Normal View History

2024-11-24 00:40:07 -05:00
package config
import (
2024-11-24 09:10:31 -05:00
"fmt"
"strings"
2024-11-24 00:40:07 -05:00
2024-11-24 09:10:31 -05:00
"dynatron.me/x/stillbox/internal/common"
"github.com/go-viper/mapstructure/v2"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
2024-11-24 00:40:07 -05:00
"github.com/rs/zerolog/log"
2024-11-24 10:38:19 -05:00
"github.com/urfave/cli/v2"
2024-11-24 00:40:07 -05:00
)
2024-11-24 10:38:19 -05:00
func New(configFile *string) *Configuration {
if configFile == nil {
panic("configFile must not be nil")
2024-11-24 00:40:07 -05:00
}
2024-11-24 10:38:19 -05:00
return &Configuration{configPath: configFile}
}
2024-11-24 00:40:07 -05:00
2024-11-24 10:38:19 -05:00
func (c *Configuration) Before(ctx *cli.Context) error {
return c.ReadConfig()
2024-11-24 00:40:07 -05:00
}
2024-11-24 08:40:14 -05:00
func (c *Configuration) ReadConfig() error {
2024-11-24 10:38:19 -05:00
log.Info().Str("configPath", *c.configPath).Msg("read config")
2024-11-24 08:40:14 -05:00
return c.read()
}
func (c *Configuration) read() error {
2024-11-24 09:10:31 -05:00
k := koanf.New(".")
2024-11-24 10:38:19 -05:00
err := k.Load(file.Provider(*c.configPath), yaml.Parser())
2024-11-24 00:40:07 -05:00
if err != nil {
return err
}
err = k.Load(env.Provider(common.EnvPrefix, ".", func(s string) string {
2024-11-24 09:10:31 -05:00
return strings.Replace(strings.ToLower(
strings.TrimPrefix(s, common.EnvPrefix)), "_", ".", -1)
}), nil)
if err != nil {
return err
}
2024-11-24 09:10:31 -05:00
err = k.UnmarshalWithConf("", &c.Config,
koanf.UnmarshalConf{
Tag: "yaml",
DecoderConfig: &mapstructure.DecoderConfig{
2024-11-24 10:38:19 -05:00
Result: &c.Config,
2024-11-24 09:10:31 -05:00
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.TextUnmarshallerHookFunc(),
),
},
})
2024-11-24 00:40:07 -05:00
if err != nil {
2024-11-24 09:10:31 -05:00
return fmt.Errorf("unmarshal err: %w", err)
2024-11-24 00:40:07 -05:00
}
return nil
}