]> git.lizzy.rs Git - go-fscache.git/blob - cachestat.go
Replace obsolete lock package
[go-fscache.git] / cachestat.go
1 package fscache
2
3 import (
4         "os"
5         "time"
6 )
7
8 // Calls os.Stat() on the file or folder that backs the given key.
9 func (cd *CacheDir) Stat(key ...CacheKey) (stat os.FileInfo, err error) {
10         lock, err := cd.Lock(key...)
11         if err != nil {
12                 return
13         }
14         defer lock.Unlock()
15
16         fh, err := cd.Open(key...)
17         if err != nil {
18                 return
19         }
20         defer fh.Close()
21
22         return fh.Stat()
23 }
24
25 // Updates the mtime of the file backing the given key.
26 //
27 // Creates an empty file if it doesn't exist.
28 func (cd *CacheDir) Touch(key ...CacheKey) (err error) {
29         lock, err := cd.Lock(key...)
30         switch {
31         case err == nil:
32                 // AOK
33                 defer lock.Unlock()
34         case os.IsNotExist(err):
35                 // new file
36         default:
37                 return
38         }
39
40         if err = cd.ChtimeNoLock(time.Now(), key...); err == nil {
41                 return
42         }
43
44         fh, err := cd.OpenFlags(os.O_APPEND|os.O_CREATE, key...)
45         switch {
46         case err == nil:
47                 // AOK
48         case os.IsNotExist(err): // directory path not created yet
49                 fh, err = cd.Create(key...)
50                 if err != nil {
51                         return
52                 }
53         default:
54                 return
55         }
56         return fh.Close()
57 }
58
59 // Same as Chtime, but does not try to acquire a file lock on the file
60 // before. Only call this if you already hold a lock to the file.
61 func (cd *CacheDir) ChtimeNoLock(t time.Time, key ...CacheKey) (err error) {
62         return os.Chtimes(cd.cachePath(key...), time.Now(), t)
63 }
64
65 // Sets the mtime of the file backing the given key to the specified time.
66 func (cd *CacheDir) Chtime(t time.Time, key ...CacheKey) (err error) {
67         lock, err := cd.Lock(key...)
68         if err != nil {
69                 return
70         }
71         defer lock.Unlock()
72
73         return cd.ChtimeNoLock(t, key...)
74 }