-
Notifications
You must be signed in to change notification settings - Fork 1
/
cachedir.go
executable file
·83 lines (68 loc) · 1.96 KB
/
cachedir.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
package fscache
import (
"os"
"path/filepath"
"sync"
)
type CacheDir struct {
mutex sync.RWMutex
compressionLevel int
cacheDir string
}
// Creates (or opens) a CacheDir using the given path.
func NewCacheDir(path string) (cd *CacheDir, err error) {
cd = &CacheDir{
compressionLevel: DefaultCompressionLevel,
}
if err = cd.SetCacheDir(path); err != nil {
return nil, err
}
return
}
// Sets the directory that will back this cache.
//
// Will try to os.MkdirAll the given path; if that fails,
// then the CacheDir is not modified.
func (cd *CacheDir) SetCacheDir(path string) (err error) {
cd.mutex.Lock()
defer cd.mutex.Unlock()
path = filepath.Join(filterDotsAll(filepath.SplitList(path)...)...)
if err = os.MkdirAll(path, 0777); err != nil {
return
}
cd.cacheDir = path
return
}
// Gets the path to the cache directory.
func (cd *CacheDir) GetCacheDir() string {
cd.mutex.RLock()
defer cd.mutex.RUnlock()
return cd.cacheDir
}
// Opens the file that backs the specified key.
func (cd *CacheDir) Open(key ...CacheKey) (fh *os.File, err error) {
return os.Open(cd.cachePath(key...))
}
// Opens the file that backs the specified key using os.OpenFile.
//
// The permission bits are always 0666, which then get filtered by umask.
func (cd *CacheDir) OpenFlags(flags int, key ...CacheKey) (fh *os.File, err error) {
return os.OpenFile(cd.cachePath(key...), flags, 0666)
}
// Creates a new file to back the specified key.
func (cd *CacheDir) Create(key ...CacheKey) (fh *os.File, err error) {
subItem := cd.cachePath(key...)
subDir := filepath.Dir(subItem)
if err = os.MkdirAll(subDir, 0777); err != nil {
return nil, err
}
return os.Create(subItem)
}
// Deletes the file that backs the specified key.
func (cd *CacheDir) Delete(key ...CacheKey) (err error) {
return os.Remove(cd.cachePath(key...))
}
// Deletes the specified key and all subkeys.
func (cd *CacheDir) DeleteAll(key ...CacheKey) (err error) {
return os.RemoveAll(cd.cachePath(key...))
}