-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
72 lines (62 loc) · 1.49 KB
/
helper.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
package toolsconfig
import (
"log"
"os"
"path"
"strings"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
var readConfiguration = defaultReadConfiguration
func defaultReadConfiguration() *Config {
var config Config
filename := viper.ConfigFileUsed()
file, err := os.Open(filename)
if err != nil {
return &Config{}
}
decoder := yaml.NewDecoder(file)
if err := decoder.Decode(&config); err != nil {
log.Fatal(err)
}
return &config
}
var saveConfiguration = defaultSaveConfiguration
func defaultSaveConfiguration(config *Config) error {
dir := path.Dir(viper.ConfigFileUsed())
if _, err := os.Stat(dir); os.IsNotExist(err) {
os.Mkdir(dir, 0700)
}
file, err := os.Create(viper.ConfigFileUsed())
if err != nil {
return err
}
encoder := yaml.NewEncoder(file)
encoder.SetIndent(2)
if err := encoder.Encode(config); err != nil {
log.Fatal(err)
}
return nil
}
func configFileName(dir, file string) (*string, error) {
var filePath string
if path.IsAbs(dir) {
filePath = path.Join(dir, file)
return &filePath, nil
}
if dir == "." {
fileName := path.Join(dir, file)
return &fileName, nil
}
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
fileName := path.Join(home, dir, file)
return &fileName, nil
}
func toEnvironmentKey(key string, additionalElements ...string) string {
prefix := strings.ReplaceAll(key, ".", "_")
prefix = strings.ReplaceAll(prefix, "-", "_")
return strings.ToUpper(strings.Join(append([]string{prefix}, additionalElements...), "_"))
}