/
common.go
85 lines (77 loc) · 1.74 KB
/
common.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
package sync15
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"os"
"path"
"sort"
"github.com/juruen/rmapi/log"
)
func HashEntries(entries []*Entry) (string, error) {
sort.Slice(entries, func(i, j int) bool { return entries[i].DocumentID < entries[j].DocumentID })
hasher := sha256.New()
for _, d := range entries {
//TODO: back and forth converting
bh, err := hex.DecodeString(d.Hash)
if err != nil {
return "", err
}
hasher.Write(bh)
}
hash := hasher.Sum(nil)
hashStr := hex.EncodeToString(hash)
return hashStr, nil
}
func getCachedTreePath() (string, error) {
cachedir, err := os.UserCacheDir()
if err != nil {
return "", err
}
rmapiFolder := path.Join(cachedir, "rmapi")
err = os.MkdirAll(rmapiFolder, 0700)
if err != nil {
return "", err
}
cacheFile := path.Join(rmapiFolder, ".tree")
return cacheFile, nil
}
const cacheVersion = 3
func loadTree() (*HashTree, error) {
cacheFile, err := getCachedTreePath()
if err != nil {
return nil, err
}
tree := &HashTree{}
if _, err := os.Stat(cacheFile); err == nil {
b, err := os.ReadFile(cacheFile)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, tree)
if err != nil {
log.Error.Println("cache corrupt")
return tree, nil
}
if tree.CacheVersion != cacheVersion {
log.Info.Println("wrong cache file version, resync")
return &HashTree{}, nil
}
}
log.Info.Println("cache loaded: ", cacheFile)
return tree, nil
}
func saveTree(tree *HashTree) error {
cacheFile, err := getCachedTreePath()
log.Info.Println("Writing cache: ", cacheFile)
if err != nil {
return err
}
tree.CacheVersion = cacheVersion
b, err := json.MarshalIndent(tree, "", "")
if err != nil {
return err
}
err = os.WriteFile(cacheFile, b, 0644)
return err
}