github.com/drone/drone-cache-lib@v0.0.0-20200806063744-981868645a25/cache/flusher.go (about) 1 package cache 2 3 import ( 4 "time" 5 6 log "github.com/sirupsen/logrus" 7 "github.com/drone/drone-cache-lib/storage" 8 ) 9 10 // DirtyFunc defines when an cache item is outdated. 11 type DirtyFunc func(storage.FileEntry) bool 12 13 // Flusher defines an object to clear the cache. 14 type Flusher struct { 15 store storage.Storage 16 dirty func(storage.FileEntry) bool 17 } 18 19 // NewFlusher creates a new cache flusher. 20 func NewFlusher(s storage.Storage, fn DirtyFunc) Flusher { 21 return Flusher{store: s, dirty: fn} 22 } 23 24 // NewDefaultFlusher creates a new cache flusher with default expire. 25 func NewDefaultFlusher(s storage.Storage) Flusher { 26 return Flusher{store: s, dirty: IsExpired} 27 } 28 29 // Flush cleans the cache if it's expired. 30 func (f *Flusher) Flush(src string) error { 31 log.Infof("Cleaning files from %s", src) 32 33 files, err := f.store.List(src) 34 if err != nil { 35 return err 36 } 37 38 for _, file := range files { 39 if f.dirty(file) { 40 err := f.store.Delete(file.Path) 41 if err != nil { 42 return err 43 } 44 } 45 } 46 47 return nil 48 } 49 50 // IsExpired checks if the cache is expired. 51 func IsExpired(file storage.FileEntry) bool { 52 // Check if older then 30 days 53 return file.LastModified.Before(time.Now().AddDate(0, 0, -30)) 54 }