-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcache.go
95 lines (80 loc) · 2.28 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
92
93
94
95
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
// CacheDir is directory for caching LICENSE files
CacheDirName = ".lcns"
// CacheDuration is duration for storing cache
CacheDuration = 30 * 24 * time.Hour
)
// setCache saves body as file (named key + Unix time) in provided
// path. Any errors that occur are returned.
func setCache(body, key, path string) error {
// Create cache directory if not exist
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.MkdirAll(path, 0777)
if err != nil {
return err
}
}
// Delete old caches before create new
cleanCache(key, path)
// Create new cache file
timeStr := strconv.Itoa(int(time.Now().Unix()))
cacheFileName := filepath.Join(path, key+"-"+timeStr)
Debugf("Cache filename: %s", cacheFileName)
cacheWriter, err := os.Create(cacheFileName)
if err != nil {
return err
}
r := strings.NewReader(body)
_, err = io.Copy(cacheWriter, r)
return err
}
// getCache read cache contents from provided path.
// Any errors that occur are returned.
func getCache(key, path string) (string, error) {
cacheFiles, err := filepath.Glob(filepath.Join(path, key+"-"+"*"))
// Check cache file is exist or not
if len(cacheFiles) == 0 {
return "", fmt.Errorf("cache file is not exist in %s", path)
}
// Check cache is latest or not
cache := cacheFiles[0]
createdUnix, err := strconv.Atoi(strings.Split(cache, "-")[len(strings.Split(cache, "-"))-1])
if err != nil {
return "", fmt.Errorf("invalid cache file name: %s", cache)
}
createdTime := time.Unix(int64(createdUnix), 0)
Debugf("Cache was created at %s", createdTime.String())
if time.Now().Sub(createdTime) > CacheDuration {
return "", fmt.Errorf("cache file is old")
}
b, err := ioutil.ReadFile(cache)
if err != nil {
return "", err
}
return string(b), nil
}
// cleanCache deletes old cache files. Any errors that occur are returned.
func cleanCache(key, path string) {
oldCacheFiles, err := filepath.Glob(filepath.Join(path, key+"-"+"*"))
if err != nil {
Debugf("Failed to glob cache files: %s", err.Error())
}
for _, of := range oldCacheFiles {
Debugf("Delete old cache file: %s", of)
err := os.Remove(of)
if err != nil {
Debugf("Failed to delete old cache file %s: %s", of, err.Error())
}
}
}