-
Notifications
You must be signed in to change notification settings - Fork 929
/
config_disk_persistor.go
77 lines (63 loc) · 1.33 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
package configuration
import (
"errors"
"fmt"
. "github.com/cloudfoundry/cli/cf/i18n"
"io/ioutil"
"os"
"path/filepath"
)
const (
filePermissions = 0600
dirPermissions = 0700
)
type Persistor interface {
Delete()
Load() (*Data, error)
Save(*Data) error
}
type DiskPersistor struct {
filePath string
}
func NewDiskPersistor(path string) (dp DiskPersistor) {
return DiskPersistor{filePath: path}
}
func (dp DiskPersistor) Delete() {
os.Remove(dp.filePath)
}
func (dp DiskPersistor) Load() (data *Data, err error) {
data, err = dp.read()
if err != nil {
err = dp.write(data)
}
return
}
func (dp DiskPersistor) Save(data *Data) (err error) {
return dp.write(data)
}
func (dp DiskPersistor) read() (data *Data, err error) {
data = NewData()
err = os.MkdirAll(filepath.Dir(dp.filePath), dirPermissions)
if err != nil {
return
}
jsonBytes, err := ioutil.ReadFile(dp.filePath)
if err != nil {
return
}
err = JsonUnmarshalV3(jsonBytes, data)
return
}
func (dp DiskPersistor) write(data *Data) (err error) {
bytes, err := JsonMarshalV3(data)
if err != nil {
return
}
err = ioutil.WriteFile(dp.filePath, bytes, filePermissions)
if err != nil {
err = errors.New(fmt.Sprintf(T("Error writing to manifest file:{{.FilePath}}\n{{.Err}}",
map[string]interface{}{"FilePath": dp.filePath, "Err": err})))
return
}
return
}