2023-10-08 16:46:03 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/knadh/koanf/parsers/yaml"
|
|
|
|
"github.com/knadh/koanf/providers/env"
|
|
|
|
"github.com/knadh/koanf/providers/file"
|
|
|
|
"github.com/knadh/koanf/providers/structs"
|
|
|
|
"github.com/knadh/koanf/v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var k = koanf.New(".")
|
|
|
|
|
|
|
|
func Load(path string) (*Config, error) {
|
|
|
|
|
|
|
|
err := k.Load(structs.Provider(defaultConfig, "koanf"), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if path != "" {
|
|
|
|
_ = k.Load(file.Provider(path), yaml.Parser()) // its ok if file doesnt exist
|
|
|
|
}
|
|
|
|
|
2023-10-13 08:03:02 +00:00
|
|
|
err = k.Load(env.Provider("TSTOR_", ".", func(s string) string {
|
2023-10-08 16:46:03 +00:00
|
|
|
return strings.Replace(strings.ToLower(
|
2023-10-13 08:03:02 +00:00
|
|
|
strings.TrimPrefix(s, "TSTOR_")), "_", ".", -1)
|
2023-10-08 16:46:03 +00:00
|
|
|
}), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := k.Marshal(yaml.Parser())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
err = os.WriteFile(path, data, os.ModePerm)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
conf := Config{}
|
2023-12-21 23:15:39 +00:00
|
|
|
err = k.Unmarshal("", &conf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-10-08 16:46:03 +00:00
|
|
|
|
|
|
|
return &conf, nil
|
|
|
|
}
|