2023-04-20 09:44:39 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2024-03-11 14:55:50 +00:00
|
|
|
"errors"
|
2023-04-20 09:44:39 +00:00
|
|
|
"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 = "_"
|
|
|
|
)
|
|
|
|
|
2024-03-11 14:55:50 +00:00
|
|
|
var errProvideViperInOpts = errors.New("provide viper in opts")
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
func CreateViper(opts ...Option) (*viper.Viper, error) {
|
|
|
|
o := defaultOpts()
|
2023-04-20 09:44:39 +00:00
|
|
|
for i := range opts {
|
|
|
|
opts[i](o)
|
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
var v *viper.Viper
|
|
|
|
if o.v != nil {
|
|
|
|
v = o.v
|
|
|
|
} else {
|
|
|
|
v = viper.New()
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.envPrefix != "" {
|
|
|
|
v.SetEnvPrefix(o.envPrefix)
|
2023-04-20 09:44:39 +00:00
|
|
|
v.AutomaticEnv()
|
|
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(Separator, EnvSeparator))
|
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
if o.path != "" {
|
|
|
|
v.SetConfigFile(o.path)
|
2023-04-20 09:44:39 +00:00
|
|
|
|
|
|
|
err := v.ReadInConfig()
|
|
|
|
if err != nil {
|
2023-04-25 07:04:26 +00:00
|
|
|
return nil, fmt.Errorf("failed to read config: %w", err)
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
if o.configDir != "" {
|
|
|
|
if err := config.ReadConfigDir(v, o.configDir); err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read config dir: %w", err)
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
return v, nil
|
2023-04-20 09:44:39 +00:00
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
func ReloadViper(opts ...Option) error {
|
|
|
|
o := defaultOpts()
|
|
|
|
for i := range opts {
|
|
|
|
opts[i](o)
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.v == nil {
|
2024-03-11 14:55:50 +00:00
|
|
|
return errProvideViperInOpts
|
2023-04-25 07:04:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if o.path != "" {
|
|
|
|
err := o.v.ReadInConfig()
|
2023-04-20 09:44:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("rereading configuration file: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-25 07:04:26 +00:00
|
|
|
if o.configDir != "" {
|
|
|
|
if err := config.ReadConfigDir(o.v, o.configDir); err != nil {
|
2023-04-20 09:44:39 +00:00
|
|
|
return fmt.Errorf("rereading configuration dir: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|