-
Notifications
You must be signed in to change notification settings - Fork 3
/
dataio.go
68 lines (55 loc) · 1.06 KB
/
dataio.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
package data
import (
"code.google.com/p/goprotobuf/proto"
"io/ioutil"
"os"
)
// Saves Protocol Message to file
func Save(ps Persistable) error {
_, err := os.Stat(ps.Location())
if os.IsNotExist(err) {
return write(ps)
}
return err
}
func Update(ps Persistable) error {
return write(ps)
}
func Persisted(ps Persistable) bool {
if Load(ps) != nil {
return false
}
return true
}
func write(ps Persistable) error {
data, err := proto.Marshal(ps)
if err != nil {
return err
}
// create dir if doesn't exists, etc
err = ps.prepareForSave()
if err != nil {
return err
}
return ioutil.WriteFile(ps.Location(), data, 0666)
}
func Load(ps Persistable) error {
return LoadFromPath(ps.Location(), ps)
}
func LoadFromPath(path string, ps Persistable) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return proto.Unmarshal(data, ps)
}
func Destroy(ps Destroyable) error {
err := os.Remove(ps.Location())
if os.IsNotExist(err) {
err = nil
} else if err != nil {
return err
}
err = ps.cleanupAfterRemove()
return err
}