-
Notifications
You must be signed in to change notification settings - Fork 5
/
cache.go
70 lines (60 loc) · 1.33 KB
/
cache.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
package parser
import (
"bytes"
"crypto/sha512"
"encoding/gob"
"fmt"
"os"
"path/filepath"
)
func loadFromCache(
filePath string,
fileData []byte,
cacheDirectory string,
) (
saveFunc func(RootDocument),
rootdoc RootDocument,
err error,
) {
type cacheStruct struct {
Hash [sha512.Size]byte
RootDoc RootDocument
}
hashpath := sha512.Sum512([]byte(filePath))
hashfile := sha512.Sum512(fileData)
cachename := filepath.Join(
cacheDirectory,
fmt.Sprintf("%x", hashpath[0:16]),
)
saveFunc = func(saveRootDoc RootDocument) {
if err = os.MkdirAll(cacheDirectory, 0700); err != nil {
return
}
var saveFile *os.File
if saveFile, err = os.Create(cachename); err != nil {
return
}
defer saveFile.Close()
enc := gob.NewEncoder(saveFile)
if err = enc.Encode(&cacheStruct{
Hash: hashfile,
RootDoc: saveRootDoc,
}); err != nil {
return
}
}
var cachefile *os.File
if cachefile, err = os.Open(cachename); err != nil {
return saveFunc, rootdoc, ErrorCacheNotFound.New(err)
}
defer cachefile.Close()
dec := gob.NewDecoder(cachefile)
cached := cacheStruct{}
if err = dec.Decode(&cached); err != nil {
return saveFunc, rootdoc, ErrorCacheNotFound.New(err)
}
if bytes.Equal(hashfile[:], cached.Hash[:]) {
return nil, cached.RootDoc, nil
}
return saveFunc, rootdoc, ErrorCacheNotFound.New(nil)
}