2023-04-20 09:44:39 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/util/config"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Separator = "."
|
|
|
|
|
|
|
|
// EnvSeparator is a section separator in ENV variables.
|
|
|
|
EnvSeparator = "_"
|
|
|
|
)
|
|
|
|
|
2023-04-24 07:09:04 +00:00
|
|
|
func CreateViper(opts ...Option) (*viper.Viper, *Opts, error) {
|
2023-04-20 09:44:39 +00:00
|
|
|
v := viper.New()
|
|
|
|
|
|
|
|
o := DefaultOpts()
|
|
|
|
for i := range opts {
|
|
|
|
opts[i](o)
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.EnvPrefix != "" {
|
|
|
|
v.SetEnvPrefix(o.EnvPrefix)
|
|
|
|
v.AutomaticEnv()
|
|
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(Separator, EnvSeparator))
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.Path != "" {
|
|
|
|
v.SetConfigFile(o.Path)
|
|
|
|
|
|
|
|
err := v.ReadInConfig()
|
|
|
|
if err != nil {
|
2023-04-24 07:09:04 +00:00
|
|
|
return nil, nil, fmt.Errorf("failed to read config: %w", err)
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.ConfigDir != "" {
|
|
|
|
if err := config.ReadConfigDir(v, o.ConfigDir); err != nil {
|
2023-04-24 07:09:04 +00:00
|
|
|
return nil, nil, fmt.Errorf("failed to read config dir: %w", err)
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 07:09:04 +00:00
|
|
|
return v, o, nil
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func ReloadViper(v *viper.Viper, o Opts) error {
|
|
|
|
if o.Path != "" {
|
|
|
|
err := v.ReadInConfig()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("rereading configuration file: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.ConfigDir != "" {
|
|
|
|
if err := config.ReadConfigDir(v, o.ConfigDir); err != nil {
|
|
|
|
return fmt.Errorf("rereading configuration dir: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|