forked from gabe565/nightscout-menu-bar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
66 lines (53 loc) · 1.35 KB
/
viper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"errors"
"log"
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/gabe565/nightscout-menu-bar/internal/ticker"
"github.com/gabe565/nightscout-menu-bar/internal/tray"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
var cfgFile string
func init() {
flag.StringVarP(&cfgFile, "config", "c", "", "Config file (default is $HOME/.config/nightscout-menu-bar.yaml)")
}
func InitViper() error {
flag.Parse()
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := os.UserHomeDir()
if err != nil {
return err
}
configDir := filepath.Join(home, ".config")
viper.SetConfigName("nightscout-menu-bar")
viper.SetConfigType("yaml")
viper.AddConfigPath(configDir)
if err := viper.SafeWriteConfig(); err != nil {
if !errors.Is(err, err.(viper.ConfigFileAlreadyExistsError)) {
return err
}
} else {
log.Println("Created config file")
}
}
viper.AutomaticEnv()
viper.SetEnvPrefix("nightscout")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
if err := viper.ReadInConfig(); err != nil {
return err
}
log.Println("Loaded config:", viper.ConfigFileUsed())
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Println("Config file changed:", e.Name)
ticker.ReloadConfig()
tray.ReloadConfig <- struct{}{}
})
return nil
}