/
storage.go
108 lines (90 loc) · 2.15 KB
/
storage.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
106
107
108
// (c) Copyright 2021, zotools' Authors.
//
// Licensed under the terms of the GNU AGPL License version 3.
package storage
import (
"encoding/json"
"io/fs"
"os"
"github.com/acidghost/zotools/internal/utils"
"github.com/acidghost/zotools/internal/zotero"
)
var defaultFS fs.FS = &utils.DummyFS{}
type Storage struct {
filename string
Data StoredData
}
type StoredData struct {
Lib Library
Search *SearchResults
}
type Library struct {
Version uint
Items []Item
}
type Item struct {
Key string
Version uint
Title string
Abstract string
ItemType string
Creators []zotero.Creator
Attachments []Attachment
}
type Attachment struct {
Key string
Version uint
ContentType string
Filename string
}
type SearchResults struct {
Term string
Items []SearchResultsItem
}
type SearchResultsItem struct {
Key string
Filename string
ContentType string
}
type errSpec string
const (
errReadStorageSpec = errSpec("wrap:could not read storage from file {{filename string %q}}")
errNotJSONSpec = errSpec("wrap:failed to parse JSON from {{filename string %q}}")
errSerializeSpec = errSpec("wrap:failed to serialize as JSON")
errWriteSpec = errSpec("wrap:failed to write to {{filename string %q}}")
errDropSpec = errSpec("wrap:failed to delete {{filename string %q}}")
)
//go:generate gorror -type=errSpec -suffix=Spec
func New(filename string) Storage {
var data StoredData
data.Lib = Library{0, []Item{}}
return Storage{filename, data}
}
func (s *Storage) Load() error {
storeBytes, err := fs.ReadFile(defaultFS, s.filename)
if err != nil {
return newErrReadStorage(s.filename, err)
}
if err := json.Unmarshal(storeBytes, &s.Data); err != nil {
return newErrNotJSON(s.filename, err)
}
return nil
}
func (s *Storage) Persist() error {
serialized, err := json.Marshal(s.Data)
if err != nil {
return newErrSerialize(err)
}
err = os.WriteFile(s.filename, serialized, 0644)
if err != nil {
return newErrWrite(s.filename, err)
}
return nil
}
func (s *Storage) Drop() (err error) {
err = os.Remove(s.filename)
if err != nil {
err = newErrDrop(s.filename, err)
}
return
}