forked from juruen/rmapi
-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
95 lines (73 loc) · 2.15 KB
/
config.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
package config
import (
"fmt"
"os"
"path/filepath"
"github.com/juruen/rmapi/log"
"github.com/juruen/rmapi/model"
"gopkg.in/yaml.v2"
)
const (
defaultConfigFile = ".rmapi"
defaultConfigFileXDG = "rmapi.conf"
appName = "rmapi"
configFileEnvVar = "RMAPI_CONFIG"
)
/*
ConfigPath returns the path to the config file. It will check the following in order:
- If the RMAPI_CONFIG environment variable is set, it will use that path.
- If a config file exists in the user's home dir as described by os.UserHomeDir, it will use that.
- Otherwise, it will use the XDG config dir, as described by os.UserConfigDir.
*/
func ConfigPath() (string, error) {
if config, ok := os.LookupEnv(configFileEnvVar); ok {
return config, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get current user: %w", err)
}
config := filepath.Join(home, defaultConfigFile)
//return config in home if exists
if _, err := os.Stat(config); err == nil {
return config, nil
}
configDir, err := os.UserConfigDir()
if err != nil {
log.Warning.Println("cannot determine config dir, using HOME", err)
return config, nil
}
xdgConfigDir := filepath.Join(configDir, appName)
if err := os.MkdirAll(xdgConfigDir, 0700); err != nil {
log.Error.Panicln("cannot create config dir "+xdgConfigDir, err)
}
config = filepath.Join(xdgConfigDir, defaultConfigFileXDG)
return config, nil
}
func LoadTokens(path string) model.AuthTokens {
tokens := model.AuthTokens{}
if _, err := os.Stat(path); os.IsNotExist(err) {
log.Trace.Printf("config fail %s doesn't exist/n", path)
return tokens
}
content, err := os.ReadFile(path)
if err != nil {
log.Warning.Printf("failed to open %s with %s/n", path, err)
return tokens
}
err = yaml.Unmarshal(content, &tokens)
if err != nil {
log.Error.Fatalln("failed to parse", path)
}
return tokens
}
func SaveTokens(path string, tokens model.AuthTokens) {
content, err := yaml.Marshal(tokens)
if err != nil {
log.Warning.Println("failed to marsha tokens", err)
}
os.WriteFile(path, content, 0600)
if err != nil {
log.Warning.Println("failed to save config to", path)
}
}