]> git.lizzy.rs Git - go-fscache.git/blob - cachedir.go
Replace obsolete lock package
[go-fscache.git] / cachedir.go
1 package fscache
2
3 import (
4         "os"
5         "path/filepath"
6         "sync"
7 )
8
9 type CacheDir struct {
10         mutex sync.RWMutex
11
12         compressionLevel int
13         cacheDir         string
14 }
15
16 // Creates (or opens) a CacheDir using the given path.
17 func NewCacheDir(path string) (cd *CacheDir, err error) {
18         cd = &CacheDir{
19                 compressionLevel: DefaultCompressionLevel,
20         }
21         if err = cd.SetCacheDir(path); err != nil {
22                 return nil, err
23         }
24         return
25 }
26
27 // Sets the directory that will back this cache.
28 //
29 // Will try to os.MkdirAll the given path; if that fails,
30 // then the CacheDir is not modified.
31 func (cd *CacheDir) SetCacheDir(path string) (err error) {
32         cd.mutex.Lock()
33         defer cd.mutex.Unlock()
34
35         path = filepath.Join(filterDotsAll(filepath.SplitList(path)...)...)
36
37         if err = os.MkdirAll(path, 0777); err != nil {
38                 return
39         }
40         cd.cacheDir = path
41         return
42 }
43
44 // Gets the path to the cache directory.
45 func (cd *CacheDir) GetCacheDir() string {
46         cd.mutex.RLock()
47         defer cd.mutex.RUnlock()
48
49         return cd.cacheDir
50 }
51
52 // Opens the file that backs the specified key.
53 func (cd *CacheDir) Open(key ...CacheKey) (fh *os.File, err error) {
54         return os.Open(cd.cachePath(key...))
55 }
56
57 // Opens the file that backs the specified key using os.OpenFile.
58 //
59 // The permission bits are always 0666, which then get filtered by umask.
60 func (cd *CacheDir) OpenFlags(flags int, key ...CacheKey) (fh *os.File, err error) {
61         return os.OpenFile(cd.cachePath(key...), flags, 0666)
62 }
63
64 // Creates a new file to back the specified key.
65 func (cd *CacheDir) Create(key ...CacheKey) (fh *os.File, err error) {
66         subItem := cd.cachePath(key...)
67         subDir := filepath.Dir(subItem)
68
69         if err = os.MkdirAll(subDir, 0777); err != nil {
70                 return nil, err
71         }
72         return os.Create(subItem)
73 }
74
75 // Deletes the file that backs the specified key.
76 func (cd *CacheDir) Delete(key ...CacheKey) (err error) {
77         return os.Remove(cd.cachePath(key...))
78 }
79
80 // Deletes the specified key and all subkeys.
81 func (cd *CacheDir) DeleteAll(key ...CacheKey) (err error) {
82         return os.RemoveAll(cd.cachePath(key...))
83 }