Skip to content

Commit

Permalink
Add support for --purge to remove not-exist records
Browse files Browse the repository at this point in the history
  • Loading branch information
suzaku committed May 5, 2016
1 parent 6709d71 commit 1141fd8
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
12 changes: 12 additions & 0 deletions entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ import (
"path/filepath"
)

func clearNotExistDirs(entries []*Entry) []*Entry {
var cleared []*Entry
for _, e := range entries {
if isValidPath(e.Path) {
cleared = append(cleared, e)
} else {
log.Printf("Directory %s no longer exists", e.Path)
}
}
return cleared
}

func saveEntries(entries []*Entry, path string) {
tempfile, err := ioutil.TempFile("", "shonenjump")
if err != nil {
Expand Down
27 changes: 27 additions & 0 deletions entry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"testing"
"strings"
)

func TestClearNotExistDirs(t *testing.T) {
orig := isValidPath
defer func() { isValidPath = orig }()
isValidPath = func(p string) bool {
return !strings.HasSuffix(p, "not-exist")
}
entries := []*Entry{
&Entry{"/foo/bar", 10},
&Entry{"/foo/not-exist", 10},
&Entry{"/tmp", 10},
&Entry{"/not-exist", 10},
}
result := clearNotExistDirs(entries)
var output []string
for _, r := range result {
output = append(output, r.Path)
}
expected := []string{"/foo/bar", "/tmp"}
assertItemsEqual(t, output, expected)
}
2 changes: 1 addition & 1 deletion match.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"regexp"
)

func isValidPath(p string) bool {
var isValidPath = func(p string) bool {
if _, err := os.Stat(p); os.IsNotExist(err) {
return false
}
Expand Down
5 changes: 5 additions & 0 deletions shonenjump.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func main() {
dataPath := config.getDataPath()
pathToAdd := flag.String("add", "", "Add this path")
complete := flag.Bool("complete", false, "Used for tab completion")
purge := flag.Bool("purge", false, "Remove non-existent paths from database")
flag.Parse()
if *pathToAdd != "" {
entries := loadEntries(dataPath)
Expand Down Expand Up @@ -73,6 +74,10 @@ func main() {
fmt.Println(strings.Join(parts, separator))
}
}
} else if *purge {
entries := loadEntries(dataPath)
entries = clearNotExistDirs(entries)
saveEntries(entries, dataPath)
} else if flag.NArg() > 0 {
args := flag.Args()
entries := loadEntries(dataPath)
Expand Down

0 comments on commit 1141fd8

Please sign in to comment.