-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
cache.go
79 lines (69 loc) · 1.97 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
package image
import (
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"github.com/BigJk/end_of_eden/internal/fs"
"github.com/samber/lo"
"os"
"path/filepath"
"strings"
)
func init() {
_ = os.Mkdir("./cache", 0755)
}
// hashFile returns a hash for the given file. If the file is not found in the
// search paths, an error is returned.
func hashFile(path string) (string, error) {
for i := range searchPaths {
data, err := fs.ReadFile(filepath.Join(searchPaths[i], path))
if err != nil {
continue
}
return fmt.Sprintf("%x", md5.Sum(data)), nil
}
return "", errors.New("could not load imag: file not found")
}
// hash returns a hash for the given image and options. As terminal image generation
// is based on the terminal size, the hash is based on the image hash and the options.
func hash(name string, options Options) (string, error) {
fileHash, err := hashFile(name)
if err != nil {
return "", err
}
combined := fmt.Sprintf("%s-%s", fileHash, options.String())
return fmt.Sprintf("%x", md5.Sum([]byte(combined))), nil
}
// getCache returns the cached data for the given hash.
func getCache(hash string) (interface{}, error) {
path := filepath.Join("./cache", hash)
data, err := fs.ReadFile(path)
if err != nil {
return nil, err
}
lines := strings.Split(string(data), "\n")
if len(lines) == 1 {
return base64.StdEncoding.DecodeString(lines[0])
}
return lo.Map(lines, func(item string, i int) string {
res, _ := base64.StdEncoding.DecodeString(item)
return string(res)
}), nil
}
// setCache stores the given data in the cache directory.
func setCache(hash string, data interface{}) error {
var lines []string
switch d := data.(type) {
case string:
lines = []string{
base64.StdEncoding.EncodeToString([]byte(d)),
}
case []string:
lines = lo.Map(d, func(item string, i int) string {
return base64.StdEncoding.EncodeToString([]byte(item))
})
}
path := filepath.Join("./cache", hash)
return fs.WriteFile(path, []byte(strings.Join(lines, "\n")))
}