Switch from viper to koanf

This commit is contained in:
2022-02-21 11:20:02 -08:00
parent 4c36144b0b
commit 4b2694ee0d
7 changed files with 130 additions and 48 deletions

View File

@@ -2,50 +2,78 @@ package main
import (
"os"
"path/filepath"
"strings"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/providers/confmap"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
func init() {
// Set up logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
// Set config settings
// Get user's configuration directory
cfgDir, err := os.UserConfigDir()
if err != nil {
panic(err)
}
// Set config defaults
setCfgDefaults()
viper.AddConfigPath("$HOME/.config")
viper.AddConfigPath("/etc")
viper.SetConfigName("itd")
viper.SetConfigType("toml")
viper.WatchConfig()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("itd")
// Ignore error because defaults set
viper.ReadInConfig()
viper.AutomaticEnv()
// Load config files
etcProvider := file.Provider("/etc/itd.toml")
cfgProvider := file.Provider(filepath.Join(cfgDir, "itd.toml"))
k.Load(etcProvider, toml.Parser())
k.Load(cfgProvider, toml.Parser())
// Watch configs for changes
cfgWatch(etcProvider)
cfgWatch(cfgProvider)
// Load envireonment variables
k.Load(env.Provider("ITD_", "_", func(s string) string {
return strings.ToLower(strings.TrimPrefix(s, "ITD_"))
}), nil)
}
func cfgWatch(provider *file.File) {
// Watch for changes and reload when detected
provider.Watch(func(_ interface{}, err error) {
if err != nil {
return
}
k.Load(provider, toml.Parser())
})
}
func setCfgDefaults() {
viper.SetDefault("socket.path", "/tmp/itd/socket")
k.Load(confmap.Provider(map[string]interface{}{
"socket.path": "/tmp/itd/socket",
viper.SetDefault("conn.reconnect", true)
"conn.reconnect": true,
viper.SetDefault("conn.whitelist.enabled", false)
viper.SetDefault("conn.whitelist.devices", []string{})
"conn.whitelist.enabled": false,
"conn.whitelist.devices": []string{},
viper.SetDefault("on.connect.notify", true)
"on.connect.notify": true,
viper.SetDefault("on.reconnect.notify", true)
viper.SetDefault("on.reconnect.setTime", true)
"on.reconnect.notify": true,
"on.reconnect.setTime": true,
viper.SetDefault("notifs.translit.use", []string{"eASCII"})
viper.SetDefault("notifs.translit.custom", []string{})
"notifs.translit.use": []string{"eASCII"},
"notifs.translit.custom": []string{},
viper.SetDefault("notifs.ignore.sender", []string{})
viper.SetDefault("notifs.ignore.summary", []string{"InfiniTime"})
viper.SetDefault("notifs.ignore.body", []string{})
"notifs.ignore.sender": []string{},
"notifs.ignore.summary": []string{"InfiniTime"},
"notifs.ignore.body": []string{},
viper.SetDefault("music.vol.interval", 5)
"music.vol.interval": 5,
}, "."), nil)
}