-
Notifications
You must be signed in to change notification settings - Fork 15
/
store.go
100 lines (82 loc) · 1.88 KB
/
store.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
package lungo
import (
"bytes"
"os"
"go.mongodb.org/mongo-driver/bson"
"github.com/256dpi/lungo/dbkit"
)
// Store is the interface that describes storage adapters.
type Store interface {
Load() (*Catalog, error)
Store(*Catalog) error
}
// MemoryStore holds the catalog in memory.
type MemoryStore struct {
catalog *Catalog
}
// NewMemoryStore creates and returns a new memory store.
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
catalog: NewCatalog(),
}
}
// Load will return the catalog.
func (m *MemoryStore) Load() (*Catalog, error) {
return m.catalog, nil
}
// Store will store the catalog.
func (m *MemoryStore) Store(data *Catalog) error {
m.catalog = data
return nil
}
// FileStore writes the catalog to a single file on disk.
type FileStore struct {
path string
mode os.FileMode
}
// NewFileStore creates and returns a new file store.
func NewFileStore(path string, mode os.FileMode) *FileStore {
return &FileStore{
path: path,
mode: mode,
}
}
// Load will read the catalog from disk and return it. If no file exists at the
// specified location an empty catalog is returned.
func (s *FileStore) Load() (*Catalog, error) {
// load file
buf, err := os.ReadFile(s.path)
if os.IsNotExist(err) {
return NewCatalog(), nil
} else if err != nil {
return nil, err
}
// decode file
var file File
err = bson.Unmarshal(buf, &file)
if err != nil {
return nil, err
}
// build catalog from file
catalog, err := file.BuildCatalog()
if err != nil {
return nil, err
}
return catalog, nil
}
// Store will atomically write the catalog to disk.
func (s *FileStore) Store(catalog *Catalog) error {
// build file from catalog
file := BuildFile(catalog)
// encode file
buf, err := bson.Marshal(file)
if err != nil {
return err
}
// write file
err = dbkit.AtomicWriteFile(s.path, bytes.NewReader(buf), s.mode)
if err != nil {
return err
}
return nil
}