This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
91 lines (72 loc) · 1.79 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
88
89
90
91
package goldsmith
import (
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sort"
)
type cache struct {
baseDir string
}
func (self *cache) retrieveFile(context *Context, outputPath string, inputFiles []*File) (*File, error) {
cachePath, err := self.buildCachePath(context, outputPath, inputFiles)
if err != nil {
return nil, err
}
outputFile, err := context.CreateFileFromAsset(outputPath, cachePath)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
return outputFile, nil
}
func (self *cache) storeFile(context *Context, outputFile *File, inputFiles []*File) error {
cachePath, err := self.buildCachePath(context, outputFile.Path(), inputFiles)
if err != nil {
return err
}
if err := os.MkdirAll(self.baseDir, 0755); err != nil {
return err
}
fp, err := os.Create(cachePath)
if err != nil {
return err
}
defer fp.Close()
offset, err := outputFile.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
if _, err := outputFile.Seek(0, io.SeekStart); err != nil {
return err
}
if _, err := outputFile.WriteTo(fp); err != nil {
return err
}
if _, err := outputFile.Seek(offset, io.SeekStart); err != nil {
return err
}
return nil
}
func (self *cache) buildCachePath(context *Context, outputPath string, inputFiles []*File) (string, error) {
hasher := crc32.NewIEEE()
hasher.Write([]byte(outputPath))
sort.Sort(filesByPath(inputFiles))
for _, inputFile := range inputFiles {
modTimeBuff := make([]byte, 8)
binary.LittleEndian.PutUint64(modTimeBuff, uint64(inputFile.ModTime().UnixNano()))
hasher.Write([]byte(inputFile.Path()))
hasher.Write(modTimeBuff)
}
cachePath := filepath.Join(self.baseDir, fmt.Sprintf(
"gs_%.8x%s",
hasher.Sum32(),
filepath.Ext(outputPath),
))
return cachePath, nil
}