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"
|
|
|
|
// "github.com/knadh/koanf/providers/posflag"
|
2024-11-24 00:40:07 -05:00
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2024-11-24 08:40:14 -05:00
|
|
|
func (c *Configuration) PreRunE() func(*cobra.Command, []string) error {
|
2024-11-24 00:40:07 -05:00
|
|
|
return func(cmd *cobra.Command, args []string) error {
|
|
|
|
return c.ReadConfig()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-24 08:40:14 -05:00
|
|
|
func New(rootCommand *cobra.Command) *Configuration {
|
|
|
|
c := &Configuration{}
|
2024-11-24 00:40:07 -05:00
|
|
|
|
|
|
|
rootCommand.PersistentFlags().StringVarP(&c.configPath, "config", "c", "config.yaml", "configuration file")
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2024-11-24 08:40:14 -05:00
|
|
|
func (c *Configuration) ReadConfig() error {
|
|
|
|
log.Info().Str("configPath", c.configPath).Msg("read config")
|
|
|
|
|
|
|
|
return c.read()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Configuration) read() error {
|
2024-11-24 09:10:31 -05:00
|
|
|
k := koanf.New(".")
|
|
|
|
err := k.Load(file.Provider(c.configPath), yaml.Parser())
|
2024-11-24 00:40:07 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-11-24 09:10:31 -05:00
|
|
|
k.Load(env.Provider(common.EnvPrefix, ".", func(s string) string {
|
|
|
|
return strings.Replace(strings.ToLower(
|
|
|
|
strings.TrimPrefix(s, common.EnvPrefix)), "_", ".", -1)
|
|
|
|
}), nil)
|
|
|
|
|
|
|
|
err = k.UnmarshalWithConf("", &c.Config,
|
|
|
|
koanf.UnmarshalConf{
|
|
|
|
Tag: "yaml",
|
|
|
|
DecoderConfig: &mapstructure.DecoderConfig{
|
|
|
|
Result: &c.Config,
|
|
|
|
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
|
|
|
|
}
|