2021-05-21 11:50:40 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2021-05-21 17:36:37 +00:00
|
|
|
"github.com/nspcc-dev/neofs-node/cmd/neofs-node/config/internal"
|
2021-05-21 11:50:40 +00:00
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Config represents a group of named values structured
|
|
|
|
// by tree type.
|
|
|
|
//
|
|
|
|
// Sub-trees are named configuration sub-sections,
|
|
|
|
// leaves are named configuration values.
|
|
|
|
// Names are of string type.
|
2021-05-21 17:28:06 +00:00
|
|
|
type Config struct {
|
|
|
|
v *viper.Viper
|
|
|
|
|
2022-09-30 13:33:30 +00:00
|
|
|
opts opts
|
|
|
|
|
2021-10-18 13:36:56 +00:00
|
|
|
defaultPath []string
|
|
|
|
path []string
|
2021-05-21 17:28:06 +00:00
|
|
|
}
|
2021-05-21 11:50:40 +00:00
|
|
|
|
2021-05-21 17:36:37 +00:00
|
|
|
const separator = "."
|
2021-05-21 11:50:40 +00:00
|
|
|
|
|
|
|
// Prm groups required parameters of the Config.
|
|
|
|
type Prm struct{}
|
|
|
|
|
|
|
|
// New creates a new Config instance.
|
|
|
|
//
|
|
|
|
// If file option is provided (WithConfigFile),
|
|
|
|
// configuration values are read from it.
|
|
|
|
// Otherwise, Config is a degenerate tree.
|
|
|
|
func New(_ Prm, opts ...Option) *Config {
|
|
|
|
v := viper.New()
|
|
|
|
|
2021-05-21 17:36:37 +00:00
|
|
|
v.SetEnvPrefix(internal.EnvPrefix)
|
2021-05-21 17:30:19 +00:00
|
|
|
v.AutomaticEnv()
|
2021-05-21 17:36:37 +00:00
|
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(separator, internal.EnvSeparator))
|
2021-05-21 17:30:19 +00:00
|
|
|
|
2021-05-21 11:50:40 +00:00
|
|
|
o := defaultOpts()
|
|
|
|
for i := range opts {
|
|
|
|
opts[i](o)
|
|
|
|
}
|
|
|
|
|
|
|
|
if o.path != "" {
|
|
|
|
v.SetConfigFile(o.path)
|
|
|
|
|
|
|
|
err := v.ReadInConfig()
|
|
|
|
if err != nil {
|
2021-06-02 12:44:41 +00:00
|
|
|
panic(fmt.Errorf("failed to read config: %w", err))
|
2021-05-21 11:50:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-21 17:28:06 +00:00
|
|
|
return &Config{
|
2022-09-30 13:33:30 +00:00
|
|
|
v: v,
|
|
|
|
opts: *o,
|
2021-05-21 17:28:06 +00:00
|
|
|
}
|
2021-05-21 11:50:40 +00:00
|
|
|
}
|
2022-09-30 13:33:30 +00:00
|
|
|
|
|
|
|
// Reload reads configuration path if any was provided
|
|
|
|
// to the New. Returns any
|
|
|
|
func (x *Config) Reload() error {
|
|
|
|
if x.opts.path != "" {
|
|
|
|
err := x.v.ReadInConfig()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("rereading configuration file: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|