forked from anatol/pacoloco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
purge.go
61 lines (53 loc) · 1.57 KB
/
purge.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
package main
import (
"log"
"os"
"path/filepath"
"time"
"github.com/djherbis/times"
)
func setupPurgeStaleFilesRoutine() *time.Ticker {
ticker := time.NewTicker(time.Duration(24) * time.Hour) // purge files once a day
go func() {
purgeStaleFiles(config.CacheDir, config.PurgeFilesAfter)
for {
select {
case <-ticker.C:
purgeStaleFiles(config.CacheDir, config.PurgeFilesAfter)
}
}
}()
return ticker
}
// purgeStaleFiles purges files in the pacoloco cache
// it recursively scans `cacheDir`/pkgs and if the file access time is older than
// `now` - purgeFilesAfter(seconds) then the file gets removed
func purgeStaleFiles(cacheDir string, purgeFilesAfter int) {
// safety check, so we don't unintentionally wipe the whole cache
if purgeFilesAfter == 0 {
log.Fatalf("Stopping because purgeFilesAfter=%v and that would purge the whole cache", purgeFilesAfter)
}
removeIfOlder := time.Now().Add(time.Duration(-purgeFilesAfter) * time.Second)
pkgDir := filepath.Join(cacheDir, "pkgs")
// Go through all files in the repos, and check if access time is older than `removeIfOlder`
walkfn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
t := times.Get(info)
atime := t.AccessTime()
if atime.Before(removeIfOlder) {
log.Printf("Remove stale file %v as its access time (%v) is too old", path, atime)
if err := os.Remove(path); err != nil {
log.Print(err)
}
}
return nil
}
if err := filepath.Walk(pkgDir, walkfn); err != nil {
log.Println(err)
}
}