-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
119 lines (99 loc) · 2.24 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"encoding/json"
"io"
"log"
"os"
"os/user"
"path"
"sync"
)
// config has the user's saved stocks.
type config struct {
// Stocks are the config's stocks. Capitalized for JSON decoding.
Stocks []configStock
}
// configStock represents a single user's stock.
type configStock struct {
// Symbol is the stock's symbol. Capitalized for JSON decoding.
Symbol string
}
// configMutex prevents config file reads and writes from conflicting.
var configMutex sync.RWMutex
// loadConfig loads the user's config from disk.
func loadConfig() (config, error) {
configMutex.RLock()
defer configMutex.RUnlock()
cfgPath, err := getUserConfigPath()
if err != nil {
return config{}, err
}
file, err := os.Open(cfgPath)
if err != nil && !os.IsNotExist(err) {
return config{}, err
}
defer file.Close()
if os.IsNotExist(err) {
return config{}, nil
}
cfg := config{}
d := json.NewDecoder(file)
if err := d.Decode(&cfg); err != nil && err != io.EOF {
return config{}, err
}
return cfg, nil
}
// saveConfig saves the user's config to disk.
func saveConfig(cfg config) error {
configMutex.Lock()
defer configMutex.Unlock()
cfgPath, err := getUserConfigPath()
if err != nil {
return err
}
file, err := os.OpenFile(cfgPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0660)
if err != nil {
return err
}
defer file.Close()
return json.NewEncoder(file).Encode(&cfg)
}
func getUserConfigPath() (string, error) {
dirPath, err := getUserConfigDir()
if err != nil {
return "", err
}
return path.Join(dirPath, "config.json"), nil
}
func getUserConfigDir() (string, error) {
u, err := user.Current()
if err != nil {
return "", err
}
p := path.Join(u.HomeDir, ".config", "ponzi")
if err := os.MkdirAll(p, 0755); err != nil {
return "", err
}
return p, nil
}
func initLogger() (*os.File, error) {
configMutex.Lock()
defer configMutex.Unlock()
logPath, err := getUserLogPath()
if err != nil {
return nil, err
}
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0660)
if err != nil {
return nil, err
}
log.SetOutput(file)
return file, nil
}
func getUserLogPath() (string, error) {
dirPath, err := getUserConfigDir()
if err != nil {
return "", err
}
return path.Join(dirPath, "log.txt"), nil
}