Debian Codegraph @

savers/filesystem.go

raw
1 package savers
2
3 /****************
4 * Date: 30/05/16
5 * Time: 5:48 PM
6 ***************/
7
8 import (
9 "encoding/gob"
10 "github.com/twinj/uuid"
11 "log"
12 "os"
13 "path"
14 "time"
15 )
16
17 var _ uuid.Saver = &FileSystemSaver{}
18
19 // This implements the Saver interface for UUIDs
20 type FileSystemSaver struct {
21 // A file to save the state to
22 // Used gob format on uuid.State entity
23 file *os.File
24
25 // Preferred location for the store
26 Path string
27
28 // Whether to log each save
29 Report bool
30
31 // The amount of time between each save call
32 time.Duration
33
34 // The next time to save
35 uuid.Timestamp
36 }
37
38 func (o *FileSystemSaver) Save(pStore uuid.Store) {
39
40 if pStore.Timestamp >= o.Timestamp {
41 err := o.openAndDo(o.encode, &pStore)
42 if err == nil {
43 if o.Report {
44 log.Printf("UUID Saved State Storage: %s", pStore)
45 }
46 }
47 o.Timestamp = pStore.Add(o.Duration)
48 }
49 }
50
51 func (o *FileSystemSaver) Read() (err error, store uuid.Store) {
52 store = uuid.Store{}
53 gob.Register(&uuid.Store{})
54
55 if _, err = os.Stat(o.Path); os.IsNotExist(err) {
56 dir, file := path.Split(o.Path)
57 if dir == "" || dir == "/" {
58 dir = os.TempDir()
59 }
60 o.Path = path.Join(dir, file)
61
62 err = os.MkdirAll(dir, os.ModeDir|0755)
63 if err == nil {
64 // If new encode blank store
65 err = o.openAndDo(o.encode, &store)
66 if err == nil {
67 log.Println("uuid.FileSystemSaver created", o.Path)
68 }
69 }
70 log.Println("uuid.FileSystemSaver.Read: error will autogenerate", err)
71 return
72 }
73
74 o.openAndDo(o.decode, &store)
75 return
76 }
77
78 func (o *FileSystemSaver) openAndDo(fDo func(*uuid.Store), pStore *uuid.Store) (err error) {
79 o.file, err = os.OpenFile(o.Path, os.O_RDWR|os.O_CREATE, os.ModeExclusive)
80 defer o.file.Close()
81 if err == nil {
82 fDo(pStore)
83 } else {
84 log.Println("uuid.FileSystemSaver.openAndDo error:", err)
85 }
86 return
87 }
88
89 func (o *FileSystemSaver) encode(pStore *uuid.Store) {
90 // ensure reader state is ready for use
91 enc := gob.NewEncoder(o.file)
92 // swallow error for encode as its only for cyclic pointers
93 enc.Encode(&pStore)
94 }
95
96 func (o *FileSystemSaver) decode(pStore *uuid.Store) {
97 // ensure reader state is ready for use
98 o.file.Seek(0, 0)
99 dec := gob.NewDecoder(o.file)
100 // swallow error for encode as its only for cyclic pointers
101 dec.Decode(&pStore)
102 }