-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
107 lines (92 loc) · 2.48 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bytes"
"fmt"
"os"
"path"
"regexp"
"github.com/getsops/sops/v3/decrypt"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
configFileType = "yaml"
configFileName = ".clinar"
)
const (
GITLAB_HOST = "GITLAB_HOST"
GTILAB_TOKEN = "GITLAB_TOKEN"
APPROVE = "approve"
EXCLUDE = "exclude"
INCLUDE = "include"
LOG_LEVEL = "LOG_LEVEL"
)
func InitConfig() {
viper.SetDefault(LOG_LEVEL, "info")
viper.SetDefault(GITLAB_HOST, "https://gitlab.com")
viper.SetDefault(GTILAB_TOKEN, "")
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(home)
viper.SetConfigType(configFileType)
viper.SetConfigName(configFileName)
viper.AutomaticEnv()
setLogLevel()
usedConfigFile := getConfigFilename(home)
if usedConfigFile != "" {
cleartext, err := decrypt.File(usedConfigFile, configFileType)
if err != nil {
logger.Warnf("Error decrypting. %s. Maybe you're not using an encrypted config?", err)
if err := viper.ReadInConfig(); err != nil {
logger.Warnf("Error reading config. %s. Are you using a config?", err)
} else {
setLogLevel()
logger.Debug("Using config file:", viper.ConfigFileUsed())
}
} else {
if err := viper.ReadConfig(bytes.NewBuffer(cleartext)); err != nil {
logger.Fatal(err)
} else {
setLogLevel()
logger.Debug("Using sops encrypted config file:", viper.ConfigFileUsed())
}
}
} else {
logger.Debug("No config file used!")
}
clinar.ExcludeFilter = viper.GetStringSlice("exclude")
if viper.GetString(INCLUDE) != "" {
rex, err := regexp.Compile(viper.GetString(INCLUDE))
if err != nil {
logger.Fatal(err)
}
clinar.IncludePattern = rex
}
}
func getConfigFilename(homedir string) string {
pathWithoutExt := path.Join(homedir, configFileName)
logger.Debugf("Check if %s exists", pathWithoutExt)
if _, err := os.Stat(pathWithoutExt); err == nil {
return pathWithoutExt
}
pathWithExt := fmt.Sprintf("%s.%s", pathWithoutExt, configFileType)
logger.Debugf("Check if %s exists", pathWithExt)
if _, err := os.Stat(pathWithExt); err == nil {
return pathWithExt
}
pathWithExt = fmt.Sprintf("%s.%s", pathWithoutExt, "yml")
logger.Debugf("Check if %s exists", pathWithExt)
if _, err := os.Stat(pathWithExt); err == nil {
return pathWithExt
}
return ""
}
func setLogLevel() {
lvl, err := logger.ParseLevel(viper.GetString(LOG_LEVEL))
if err == nil {
logger.SetLevel(lvl)
} else {
logger.Errorf("setLogLevel: %v", err)
}
}