@@ -19,20 +19,51 @@ import (
19
19
"time"
20
20
21
21
"github.com/arduino/go-paths-helper"
22
+ "github.com/pkg/errors"
23
+ "github.com/sirupsen/logrus"
22
24
)
23
25
24
- // GetOrCreate retrieves or creates the cache directory for the given key inside basePath.
26
+ const lastUsedFileName = ".last-used"
27
+
28
+ // GetOrCreate retrieves or creates the cache directory at the given path
25
29
// If the cache already exists the lifetime of the cache is extended.
26
- func GetOrCreate (dir * paths.Path , key string ) error {
27
- unusedTTL := time .Hour
28
- _ , err := newDirectoryCache (dir , unusedTTL ).
29
- GetOrCreate (key , time .Now ())
30
- return err
30
+ func GetOrCreate (dir * paths.Path ) error {
31
+ if ! dir .Exist () {
32
+ if err := dir .MkdirAll (); err != nil {
33
+ return err
34
+ }
35
+ }
36
+
37
+ return dir .Join (lastUsedFileName ).WriteFile ([]byte {})
31
38
}
32
39
33
40
// Purge removes all cache directories within baseDir that have expired
34
41
// To know how long ago a directory has been last used
35
42
// it checks into the .last-used file.
36
43
func Purge (baseDir * paths.Path , ttl time.Duration ) {
37
- newDirectoryCache (baseDir , ttl ).Purge ()
44
+ files , err := baseDir .ReadDir ()
45
+ if err != nil {
46
+ return
47
+ }
48
+ for _ , file := range files {
49
+ if file .IsDir () {
50
+ removeIfExpired (file , ttl )
51
+ }
52
+ }
53
+ }
54
+
55
+ func removeIfExpired (dir * paths.Path , ttl time.Duration ) {
56
+ fileInfo , err := dir .Join ().Stat ()
57
+ if err != nil {
58
+ return
59
+ }
60
+ lifeExpectancy := ttl - time .Since (fileInfo .ModTime ())
61
+ if lifeExpectancy > 0 {
62
+ return
63
+ }
64
+ logrus .Tracef (`Purging cache directory "%s". Expired by %s` , dir , lifeExpectancy .Abs ())
65
+ err = dir .RemoveAll ()
66
+ if err != nil {
67
+ logrus .Tracef (`Error while pruning cache directory "%s": %s` , dir , errors .WithStack (err ))
68
+ }
38
69
}
0 commit comments