haste-expire/haste-expire.go
jolheiser 2ebc929c07
Add single-run mode
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-09-29 12:44:38 -05:00

75 lines
1.4 KiB
Go

package main
import (
"flag"
"os"
"path/filepath"
"time"
"go.jolheiser.com/beaver"
)
var (
Interval time.Duration
SingleRun bool
Expire time.Duration
DataPath string
Debug bool
)
func main() {
flag.DurationVar(&Interval, "interval", time.Hour*24, "Interval between checking files")
flag.BoolVar(&SingleRun, "single", false, "Single run mode")
flag.DurationVar(&Expire, "expire", time.Hour*24*7, "Expiration time")
flag.StringVar(&DataPath, "data-path", "./data", "Path to haste files")
flag.BoolVar(&Debug, "debug", false, "Debug mode")
flag.Parse()
beaver.Console.Format = beaver.FormatOptions{
TimePrefix: true,
StackLimit: 0,
LevelPrefix: true,
LevelColor: true,
}
if Debug {
beaver.Console.Level = beaver.DEBUG
}
scan()
if !SingleRun {
cron()
}
}
func cron() {
ticker := time.NewTicker(Interval)
for {
scan()
<-ticker.C
}
}
func scan() {
beaver.Debug("Running scan...")
if err := filepath.Walk(DataPath, func(walkPath string, walkInfo os.FileInfo, walkErr error) error {
if walkErr != nil {
return walkErr
}
if walkInfo.IsDir() {
return nil
}
if LastAccess(walkInfo).Add(Expire).Before(time.Now()) {
beaver.Infof("Deleting %s", walkPath)
if err := os.Remove(walkPath); err != nil {
beaver.Errorf("Error deleting `%s`!", walkPath)
}
}
return nil
}); err != nil {
beaver.Errorf("Error walking storage: %v", err)
}
}