-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
72 lines (61 loc) · 1.38 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/urfave/cli"
)
type jsonConfig struct {
Lang string `json:"lang"`
}
var (
configDir string
configPath string
)
func setConfig(c *cli.Context) {
config := loadConfig()
if c.String("lang") != "" {
config.Lang = c.String("lang")
}
bdata, err := json.Marshal(config)
if err != nil {
fmt.Println("Cannot encode json:", err.Error())
os.Exit(ExitCodeError)
}
if _, err := os.Stat(configDir); err != nil {
os.Mkdir(configDir, 0777)
}
err = ioutil.WriteFile(configPath, []byte(bdata), os.ModePerm)
if err != nil {
fmt.Println("Cannot save json:", err.Error())
os.Exit(ExitCodeError)
}
}
func loadConfig() jsonConfig {
homeDir, err := homedir.Dir()
if err != nil {
fmt.Println("Cannot find homedir:" + err.Error())
os.Exit(ExitCodeError)
}
configDir = homeDir + "/.trivia"
configPath = configDir + "/config.json"
var config jsonConfig
if fileExists(configPath) {
bytes, err := ioutil.ReadFile(configPath)
if err != nil {
fmt.Println("Cannot read config:", err.Error())
os.Exit(ExitCodeError)
}
if err := json.Unmarshal(bytes, &config); err != nil {
fmt.Println("Cannot load config:", err.Error())
os.Exit(ExitCodeError)
}
}
return config
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}