-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
cache.go
73 lines (60 loc) · 1.74 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
package resolvers
import (
"context"
"crypto/md5" // #nosec
"encoding/hex"
"fmt"
"io/fs"
"os"
"path/filepath"
)
type cacheResolver struct{}
var Cache = &cacheResolver{}
const tempDirName = ".aqua"
var defaultCacheDir = filepath.Join(os.TempDir(), tempDirName, "cache")
func locateCacheFS(cacheDir string) (fs.FS, error) {
dir, err := locateCacheDir(cacheDir)
if err != nil {
return nil, err
}
return os.DirFS(dir), nil
}
func locateCacheDir(cacheDir string) (string, error) {
if cacheDir == "" {
cacheDir = defaultCacheDir
}
if err := os.MkdirAll(cacheDir, 0o750); err != nil {
return "", err
}
if !isWritable(cacheDir) {
return "", fmt.Errorf("cache directory is not writable")
}
return cacheDir, nil
}
func (r *cacheResolver) Resolve(_ context.Context, _ fs.FS, opt Options) (filesystem fs.FS, prefix, downloadPath string, applies bool, err error) {
if opt.SkipCache {
opt.Debug("Cache is disabled.")
return nil, "", "", false, nil
}
cacheFS, err := locateCacheFS(opt.CacheDir)
if err != nil {
opt.Debug("No cache filesystem is available on this machine.")
return nil, "", "", false, nil
}
src := removeSubdirFromSource(opt.Source)
key := cacheKey(src, opt.Version)
opt.Debug("Trying to resolve: %s", key)
if info, err := fs.Stat(cacheFS, filepath.ToSlash(key)); err == nil && info.IsDir() {
opt.Debug("Module '%s' resolving via cache...", opt.Name)
cacheDir, err := locateCacheDir(opt.CacheDir)
if err != nil {
return nil, "", "", true, err
}
return os.DirFS(filepath.Join(cacheDir, key)), opt.OriginalSource, ".", true, nil
}
return nil, "", "", false, nil
}
func cacheKey(source, version string) string {
hash := md5.Sum([]byte(source + ":" + version)) // #nosec
return hex.EncodeToString(hash[:])
}