-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
74 lines (60 loc) · 1.99 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
67
68
69
70
71
72
73
74
package cmd
import (
"os"
"path/filepath"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/rs/zerolog/log"
)
func initViper() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.SetConfigFile(filepath.Join(home, ".config", "hey", "config.yaml"))
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
log.Debug().Msgf("Using config file: %s", viper.ConfigFileUsed())
}
log.Debug().Msg("Viper Initialized!")
}
func initViperConfigFile() {
configFilePath := viper.ConfigFileUsed()
log.Debug().Msgf("Checking if config file %s exists", configFilePath)
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
log.Debug().Msg("Config file doesn't exist. Creating now.")
mkdir_err := os.MkdirAll(filepath.Dir(configFilePath), os.ModePerm)
if mkdir_err != nil {
log.Error().Err(mkdir_err).Msgf("Error creating directory for config file: %s", configFilePath)
os.Exit(1)
}
file_write_err := viper.SafeWriteConfigAs(configFilePath)
if file_write_err != nil {
log.Error().Err(file_write_err).Msgf("Error creating configuration file: %s", configFilePath)
os.Exit(1)
} else {
log.Debug().Msgf("Successfully created the configuration file: %s", configFilePath)
}
read_config_err := viper.ReadInConfig()
if read_config_err != nil {
log.Error().Err(read_config_err).Msg("Error reading configuration file")
} else {
log.Debug().Msg("Config file read!")
}
}
}
func saveCurrentViperConfig() {
configFilePath := viper.ConfigFileUsed()
file_write_err := viper.WriteConfigAs(configFilePath)
if file_write_err != nil {
log.Error().Err(file_write_err).Msgf("Error writing to configuration file: %s", configFilePath)
os.Exit(1)
} else {
log.Debug().Msgf("Successfully updated configuration file: %s", configFilePath)
}
}