diff --git a/main.go b/main.go index 8569db1..2f6c23e 100644 --- a/main.go +++ b/main.go @@ -24,9 +24,6 @@ func main() { t.Must(s.Save()) case "save-loop": - s, err := session.New() - t.Must(err) - durationInterval := time.Duration(60) if len(os.Args) >= 3 { interval, err := strconv.Atoi(os.Args[2]) @@ -35,8 +32,11 @@ func main() { } for { + s, err := session.New() + t.Must(err) time.Sleep(durationInterval * time.Second) t.Must(s.Save()) + session.CleanUp() } case "restore": @@ -44,5 +44,8 @@ func main() { t.Must(err) t.Must(s.Restore()) + + case "clean-up": + t.Must(session.CleanUp()) } } diff --git a/session/session.go b/session/session.go index 91fa716..75a1b99 100644 --- a/session/session.go +++ b/session/session.go @@ -5,6 +5,7 @@ import ( "errors" "io/ioutil" "log" + "os" "path" "path/filepath" "sort" @@ -107,3 +108,34 @@ func (s *Session) Restore() (err error) { return } + +// CleanUp delete all session files except the last +func CleanUp() (err error) { + files, err := ioutil.ReadDir(sessionsPath) + if err != nil { + log.Fatal(err) + } + + if len(files) == 0 { + return + } + + sort.Slice(files, func(i, j int) bool { + iUnix := timestampFromFilename(files[i].Name()) + jUnix := timestampFromFilename(files[j].Name()) + return iUnix > jUnix + }) + + for i, file := range files { + if i == 0 { + continue + } + + err = os.Remove(path.Join(sessionsPath, file.Name())) + if err != nil { + return + } + } + + return +}