-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
73 lines (64 loc) · 1.33 KB
/
Copy pathcache.go
File metadata and controls
73 lines (64 loc) · 1.33 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
69
70
71
72
73
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
"time"
)
const cacheTTL = 24 * time.Hour
type cacheEntry struct {
Timestamp time.Time `json:"timestamp"`
Arcs []Arc `json:"arcs"`
}
func cacheDir() string {
dir, err := os.UserCacheDir()
if err != nil {
dir = os.TempDir()
}
return filepath.Join(dir, "one-pace-map")
}
func cacheFile() string {
return filepath.Join(cacheDir(), "arcs.json")
}
func loadCache() ([]Arc, bool) {
data, err := os.ReadFile(cacheFile())
if err != nil {
return nil, false
}
var entry cacheEntry
if err := json.Unmarshal(data, &entry); err != nil {
log.Printf("WARN corrupt cache file, ignoring: %v", err)
return nil, false
}
if time.Since(entry.Timestamp) > cacheTTL {
return nil, false
}
return entry.Arcs, true
}
func saveCache(arcs []Arc) error {
dir := cacheDir()
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
entry := cacheEntry{Timestamp: time.Now(), Arcs: arcs}
data, err := json.Marshal(entry)
if err != nil {
return err
}
tmp, err := os.CreateTemp(dir, "arcs-*.json.tmp")
if err != nil {
return err
}
tmpName := tmp.Name()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
os.Remove(tmpName)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(tmpName)
return err
}
return os.Rename(tmpName, cacheFile())
}