-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatastore.go
74 lines (67 loc) · 1.37 KB
/
datastore.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
// Copyright (c) 2023 Julian Müller (ChaoticByte)
package main
import (
"encoding/json"
"io/fs"
"os"
)
type DataStore struct {
filepath string
prettyJSON bool
data any
fileMode fs.FileMode
}
func (ds *DataStore) save() error {
var err error
var data []byte
if ds.prettyJSON {
data, err = json.MarshalIndent(ds.data, "", " ")
} else {
data, err = json.Marshal(ds.data)
}
if err != nil { return err }
err = os.WriteFile(ds.filepath, data, ds.fileMode)
return err
}
func (ds *DataStore) load() error {
data, err := os.ReadFile(ds.filepath)
if err != nil { return err }
switch ds.data.(type) {
case Config:
d, _ := ds.data.(Config);
err = json.Unmarshal(data, &d)
if err != nil { return err }
ds.data = d
case PersistentData:
d, _ := ds.data.(PersistentData);
err = json.Unmarshal(data, &d)
if err != nil { return err }
ds.data = d
}
return err
}
func (ds *DataStore) init() error {
err := ds.load()
if err != nil {
if !os.IsNotExist(err) {
return err
} else {
// Write initial data
err = ds.save()
}
}
return err
}
func NewDataStore(savePath string, data any, prettyJSON bool, fileMode fs.FileMode) DataStore {
// Initial data
ds := DataStore{}
ds.filepath = savePath
ds.data = data
ds.prettyJSON = prettyJSON
ds.fileMode = fileMode
if err := ds.init(); err != nil {
// We don't like that, we panic
panic(err)
}
return ds
}