forked from muja/goconfig
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
68 lines (60 loc) · 1.1 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
package goconfig
import (
"os"
"sync"
"time"
"github.com/golang/groupcache/lru"
)
var cache *lru.Cache
var mu sync.RWMutex
// cacheItem holds cache for git config.
type cacheItem struct {
config GitConfig
filename string
time time.Time
size int64
}
func (v *cacheItem) uptodate() bool {
fi, err := os.Stat(v.filename)
if err == nil && fi.ModTime() == v.time && fi.Size() == v.size {
return true
}
return false
}
// CacheSet will set cache entry
func CacheSet(key string, cfg GitConfig, size int64, modTime time.Time) {
if cache == nil {
return
}
mu.Lock()
cache.Add(key, &cacheItem{
config: cfg,
filename: key,
time: modTime,
size: size,
})
mu.Unlock()
}
// CacheGet returns git config if config file is up-to-date
func CacheGet(key string) (GitConfig, bool) {
mu.RLock()
value, ok := cache.Get(key)
mu.RUnlock()
if !ok {
return nil, false
}
item, ok := value.(*cacheItem)
if !ok {
return nil, false
}
if !item.uptodate() {
mu.Lock()
cache.Remove(key)
mu.Unlock()
return nil, false
}
return item.config, true
}
func init() {
cache = lru.New(128)
}