Skip to content

Commit

Permalink
Fix save-loop and add clean-up
Browse files Browse the repository at this point in the history
Now the `save-loop` will clean up all sessions except the last.
It is also possible to call the clean up by `clean-up` command.
  • Loading branch information
Rafael Gumieri committed Nov 30, 2019
1 parent 75a1ec3 commit 89dd712
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
9 changes: 6 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -35,14 +32,20 @@ func main() {
}

for {
s, err := session.New()
t.Must(err)
time.Sleep(durationInterval * time.Second)
t.Must(s.Save())
session.CleanUp()
}

case "restore":
s, err := session.LoadNewest()
t.Must(err)

t.Must(s.Restore())

case "clean-up":
t.Must(session.CleanUp())
}
}
32 changes: 32 additions & 0 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"sort"
Expand Down Expand Up @@ -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
}

0 comments on commit 89dd712

Please sign in to comment.