/
config.go
87 lines (72 loc) · 2.42 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
// Package config handles configurations for go-music, it saves config files about
// color themes, libraries caches and so on in software's work dir(in user's home dir).
package config
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
)
// const (
// ConfigVersionNum = "0.5.0"
// VersionNum = "0.5.0"
// )
const WorkDirName = "go-music"
type Configuration interface {
FileName() string
Marshal() ([]byte, error)
Unmarshal([]byte) error
}
// LoadConfigFromWorkDir reads config file in software's work dir(in user's home dir)
// and fills given Configuration with unmarshal config.
func LoadConfigFromWorkDir(c Configuration) error {
path, err := os.UserConfigDir()
if err != nil {
return errors.New("load config file from work dir: " + err.Error())
}
path = filepath.Join(path, WorkDirName, c.FileName())
// check path validity
if _, err = os.Stat(path); err != nil {
return errors.New("load config file from work dir: " + err.Error())
}
// load config
if data, err := ioutil.ReadFile(path); err != nil {
return errors.New("load config file from work dir: " + err.Error())
} else {
return c.Unmarshal(data)
}
}
func SaveConfigInWorkDir(c Configuration) error {
path, err := os.UserConfigDir() // "$HOME/.config" on Linux
if err != nil {
return errors.New("save config file in work dir: " + err.Error())
}
path = filepath.Join(path, WorkDirName)
os.Mkdir(path, os.ModePerm) // TODO: The os.ModePerm may give unnessary x permission.
path = filepath.Join(path, c.FileName()) // path including filename
if data, err := c.Marshal(); err != nil {
return errors.New("save config file in work dir: " + err.Error())
} else {
// TODO: The os.ModePerm may give unnessary x permission.
return ioutil.WriteFile(path, append(fileHeader(), data...), os.ModePerm)
}
}
func GenerateFile(path string, c Configuration) error {
path = filepath.Clean(path) // config file dir
if _, err := os.Stat(path); err != nil {
return errors.New("generate config file: " + err.Error())
}
path = filepath.Join(path, c.FileName()) // path including filename
data, err := c.Marshal()
if err != nil {
return errors.New("generate config file: " + err.Error())
}
err = ioutil.WriteFile(path, append(fileHeader(), data...), os.ModeSetuid)
if err != nil {
return errors.New("generate config file: " + err.Error())
}
return nil
}
func fileHeader() []byte {
return []byte("# This is the config file of go-music\n\n")
}