-
Notifications
You must be signed in to change notification settings - Fork 2
/
snapshot.go
105 lines (91 loc) · 2.28 KB
/
snapshot.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
package processor
import (
"errors"
"gdiamond/util/fileutil"
"io"
"io/ioutil"
"os"
"path/filepath"
)
//SnapshotConfigInfoProcessor local snapshot file processor
type SnapshotConfigInfoProcessor struct {
dir string //snapshot data dir
}
//NewSnapshotConfigInfoProcessor new
func NewSnapshotConfigInfoProcessor(dir string) *SnapshotConfigInfoProcessor {
processor := &SnapshotConfigInfoProcessor{
dir: dir,
}
fileutil.CreateDirIfNecessary(dir)
return processor
}
//GetConfigInfomation read snapshot data from local file
//if err return it come from ioutil.ReadFile
func (p *SnapshotConfigInfoProcessor) GetConfigInfomation(dataId, group string) (string, error) {
if dataId == "" || group == "" {
return "", nil
}
path := filepath.Join(p.dir, group)
if !fileutil.IsExist(path) {
return "", nil
}
filePath := filepath.Join(path, dataId)
if !fileutil.IsExist(filePath) {
return "", nil
}
buf, err := ioutil.ReadFile(filePath)
if err != nil {
return "", err
}
return string(buf), nil
}
//SaveSnaptshot save config data to snapshot local file
//if dataId or group it will return err
func (p *SnapshotConfigInfoProcessor) SaveSnaptshot(dataId, group, config string) error {
if dataId == "" {
errors.New("blank dataId")
}
if group == "" {
errors.New("blank group")
}
if config == "" {
config = ""
}
f, err := p.getTargetFile(dataId, group)
if err != nil {
return err
}
writeN, err := io.WriteString(f, config)
if writeN == 0 || err != nil {
return err
}
return nil
}
/*
RemoveSnapshot remove snapshot config local file,if the dir is empty it will remove the dir
*/
func (p *SnapshotConfigInfoProcessor) RemoveSnapshot(dataId, group string) {
if dataId == "" || group == "" {
return
}
path := filepath.Join(p.dir, group)
if !fileutil.IsExist(path) {
return
}
filePath := filepath.Join(path, dataId)
if !fileutil.IsExist(filePath) {
return
}
os.Remove(filePath)
// 如果目录没有文件了,删除目录
list, _ := ioutil.ReadDir(path)
if list == nil || len(list) == 0 {
os.Remove(path)
}
}
func (p *SnapshotConfigInfoProcessor) getTargetFile(dataId, group string) (*os.File, error) {
path := filepath.Join(p.dir, group)
fileutil.CreateDirIfNecessary(path)
filePath := filepath.Join(path, dataId)
return fileutil.CreateFileIfNessary(filePath)
}