/
cache.go
87 lines (75 loc) · 1.89 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package aoc
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/Merovius/AdventOfCode/internal/sync"
"github.com/google/renameio/v2"
)
// Cache stores temporary data.
type Cache interface {
// Get the value associated with key.
Get(ctx context.Context, key string) ([]byte, error)
// Set the value associated with key to val.
Set(ctx context.Context, key string, val []byte) error
}
// DirCache stores data in a directory. If empty, defaults to
// filepath.Join(os.UserCacheDir(), "aoc", "cache")
type DirCache string
var userCacheDir sync.OnceValues[string, error]
func (c DirCache) dir() (string, error) {
if c != "" {
return string(c), nil
}
ucd, err := userCacheDir.Do(os.UserCacheDir)
if err != nil || ucd == "" {
return "", fmt.Errorf("could not determine default cache dir: %w", err)
}
d := filepath.Join(ucd, "aoc", "cache")
if err := os.MkdirAll(d, 0700); err != nil {
return "", err
}
return d, nil
}
// Get implements Cache.
func (c DirCache) Get(ctx context.Context, key string) ([]byte, error) {
d, err := c.dir()
if err != nil {
return nil, err
}
return os.ReadFile(filepath.Join(d, filepath.FromSlash(key)))
}
// Set implements Cache.
func (c DirCache) Set(ctx context.Context, key string, val []byte) error {
d, err := c.dir()
if err != nil {
return err
}
return renameio.WriteFile(filepath.Join(d, filepath.FromSlash(key)), val, 0600)
}
// Purge the cache.
func (c DirCache) Purge(ctx context.Context) error {
d, err := c.dir()
if err != nil {
return err
}
de, err := os.ReadDir(d)
if err != nil {
return err
}
for _, e := range de {
if err := os.RemoveAll(filepath.Join(d, e.Name())); err != nil {
return err
}
}
return nil
}
type nopCache struct{}
func (nopCache) Get(ctx context.Context, key string) ([]byte, error) {
return nil, fs.ErrNotExist
}
func (nopCache) Set(ctx context.Context, key string, val []byte) error {
return nil
}