-
-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathcache.go
More file actions
68 lines (59 loc) · 1.46 KB
/
Copy pathcache.go
File metadata and controls
68 lines (59 loc) · 1.46 KB
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 main
import (
"encoding/json"
"errors"
"os"
"github.com/sachaos/todoist/lib"
)
const currentSchemaVersion = todoist.CurrentSchemaVersion
func LoadCache(filename string, s *todoist.Store) error {
err := ReadCache(filename, s)
if err != nil {
err = WriteCache(cachePath, s)
if err != nil {
return err
}
}
return nil
}
func ReadCache(filename string, s *todoist.Store) error {
jsonBytes, err := os.ReadFile(filename)
if err != nil {
return CommandFailed
}
// Two-pass: check schema version before full unmarshal so that a
// schema change never leaves the cache in a broken state.
var meta struct {
SchemaVersion int `json:"schema_version"`
}
json.Unmarshal(jsonBytes, &meta) // error ignored: missing field yields 0
if meta.SchemaVersion != currentSchemaVersion {
// Old or mismatched cache: force a full resync on next sync call.
s.SyncToken = "*"
s.SchemaVersion = currentSchemaVersion
if err := WriteCache(filename, s); err != nil {
return err
}
return nil
}
if err := json.Unmarshal(jsonBytes, s); err != nil {
return CommandFailed
}
s.ConstructItemTree()
return nil
}
func WriteCache(filename string, s *todoist.Store) error {
buf, err := json.MarshalIndent(s, "", " ")
if err != nil {
return CommandFailed
}
err = AssureExists(filename)
if err != nil {
return err
}
err2 := os.WriteFile(filename, buf, os.ModePerm)
if err2 != nil {
return errors.New("Couldn't write to the cache file")
}
return nil
}