-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
77 lines (64 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
73
74
75
76
77
package main
import (
"encoding/json"
"io/ioutil"
"os"
"path"
"github.com/tjhorner/fs/shorty"
)
type config struct {
ProjectID string `json:"projectId"`
BucketName string `json:"bucketName"`
Host string `json:"host"`
Shorten bool `json:"shorten"`
ShortyConfig *shorty.Config `json:"shorty"`
}
func newConfig() *config {
return &config{
ProjectID: "",
BucketName: "",
Host: "",
Shorten: false,
ShortyConfig: &shorty.Config{
BaseURL: "",
},
}
}
func defaultConfigDirectory() string {
home, err := os.UserHomeDir()
if err != nil {
home = ""
}
return path.Join(home, ".config", "fs")
}
func defaultConfigPath() string {
return path.Join(defaultConfigDirectory(), "config.json")
}
func defaultServiceAccountPath() string {
return path.Join(defaultConfigDirectory(), "service_account.json")
}
func loadConfig(path string) *config {
raw, err := ioutil.ReadFile(path)
if err != nil {
saveConfig(newConfig(), path)
return newConfig()
}
var conf config
err = json.Unmarshal(raw, &conf)
if err != nil {
return newConfig()
}
return &conf
}
func saveConfig(conf *config, fp string) error {
enc, err := json.MarshalIndent(conf, "", " ")
if err != nil {
return err
}
os.MkdirAll(path.Dir(fp), os.ModePerm)
err = ioutil.WriteFile(fp, enc, 0644)
if err != nil {
return err
}
return nil
}