forked from haramako/cfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
118 lines (101 loc) · 2.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
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
package cfs
import (
"fmt"
"os"
"path/filepath"
"github.com/go-yaml/yaml"
)
type SettingInfo struct {
HomeRoot string `yaml:"HomeRoot"`
}
var globalCacheDir string
var globalDataCacheDir string
var globalSettingPath string
var Setting *SettingInfo
// CFSのキャッシュディレクトリを取得する
// ~/.cfs/cache がなければ作成してそれを返す
func GlobalCacheDir() string {
if globalCacheDir != "" {
return globalCacheDir
}
globalCacheDir := filepath.Join(HomeDir(), "cache")
_, err := os.Stat(globalCacheDir)
if os.IsNotExist(err) {
err := os.MkdirAll(globalCacheDir, 0777)
if err != nil {
panic(err)
}
}
return globalCacheDir
}
// CFSのデータキャッシュディレクトリを取得する
// ~/.cfs/data がなければ作成してそれを返す
func GlobalDataCacheDir() string {
if globalDataCacheDir != "" {
return globalDataCacheDir
}
globalDataCacheDir := filepath.Join(HomeDir(), "datacache")
_, err := os.Stat(globalDataCacheDir)
if os.IsNotExist(err) {
err := os.MkdirAll(globalDataCacheDir, 0777)
if err != nil {
panic(err)
}
}
return globalDataCacheDir
}
// CFSの設定ファイルのパスを返す
func GlobalSettingPath() string {
if globalSettingPath != "" {
return globalSettingPath
}
homeRoot, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
panic("cannot get home dir")
}
globalSettingPath := filepath.Join(homeRoot, ".cfs_setting")
return globalSettingPath
}
// ユーザーのホームディレクトリを取得する
func HomeDir() string {
InitDefaultSetting() // TODO: remove from here, and load automatically
home := filepath.Join(Setting.HomeRoot, ".cfs")
_, err := os.Stat(home)
if os.IsNotExist(err) {
err := os.MkdirAll(home, 0777)
if err != nil {
panic(err)
}
}
return home
}
// Settingに初期設定を行う
func InitDefaultSetting() {
homeRoot, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
panic("cannot get home dir")
}
Setting = &SettingInfo{
HomeRoot: homeRoot,
}
err = Setting.Load()
if err != nil {
fmt.Println(err)
}
}
// .cfs_settingファイルを読み込んで設定を反映する
func (s *SettingInfo) Load() error {
_, err := os.Stat(GlobalSettingPath())
if os.IsNotExist(err) {
return nil
}
f, err := os.Open(GlobalSettingPath())
if err != nil {
return err
}
defer f.Close()
err = yaml.NewDecoder(f).Decode(&s)
return err
}