-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig_disk_persistor.go
87 lines (69 loc) · 1.42 KB
/
config_disk_persistor.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 configuration
import (
"io/ioutil"
"os"
)
const (
filePermissions = 0600
dirPermissions = 0700
)
//go:generate counterfeiter . Persistor
type Persistor interface {
Delete()
Exists() bool
Load(DataInterface) error
Save(DataInterface) error
}
//go:generate counterfeiter . DataInterface
type DataInterface interface {
JSONMarshalV3() ([]byte, error)
JSONUnmarshalV3([]byte) error
}
type DiskPersistor struct {
filePath string
}
func NewDiskPersistor(path string) (dp DiskPersistor) {
return DiskPersistor{
filePath: path,
}
}
func (dp DiskPersistor) Exists() bool {
_, err := os.Stat(dp.filePath)
if err != nil && !os.IsExist(err) {
return false
}
return true
}
func (dp DiskPersistor) Delete() {
os.Remove(dp.filePath)
}
func (dp DiskPersistor) Load(data DataInterface) error {
err := dp.read(data)
if os.IsPermission(err) {
return err
}
if err != nil {
err = dp.write(data)
}
return err
}
func (dp DiskPersistor) Save(data DataInterface) (err error) {
return dp.write(data)
}
func (dp DiskPersistor) read(data DataInterface) error {
dp.makeDirectory()
jsonBytes, err := ioutil.ReadFile(dp.filePath)
if err != nil {
return err
}
err = data.JSONUnmarshalV3(jsonBytes)
return err
}
func (dp DiskPersistor) write(data DataInterface) error {
bytes, err := data.JSONMarshalV3()
if err != nil {
return err
}
err = ioutil.WriteFile(dp.filePath, bytes, filePermissions)
return err
}