-
Notifications
You must be signed in to change notification settings - Fork 1
/
duplicate_files.go
90 lines (82 loc) · 1.93 KB
/
duplicate_files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"io"
"net/http"
"os"
"path"
"strings"
zglob "github.com/mattn/go-zglob"
"github.com/ubccsss/exams/config"
"github.com/ubccsss/exams/examdb"
)
// findDuplicates returns all duplicates/extra files on disk that don't have a
// corresponding DB entry.
func findDuplicates(w io.Writer, db *examdb.Database) ([]string, error) {
var duplicate []string
pattern := path.Join(config.StaticDir, "**/*.pdf*")
paths, err := zglob.Glob(pattern)
if err != nil {
return nil, err
}
for _, path := range paths {
// Strip off config.StaticDir
staticPath := strings.TrimPrefix(path, config.StaticDir+"/")
f := db.FindFileByPath(staticPath)
if f == nil {
f := examdb.File{
Path: staticPath,
}
if err := f.ComputeHash(); err != nil {
return nil, err
}
f2 := db.FindFile(f.Hash)
if f2 == nil {
fmt.Fprintf(w, "file not in DB: %q\n", staticPath)
} else {
fmt.Fprintf(w, "%q -> %q\n", staticPath, f2.Path)
duplicate = append(duplicate, staticPath)
}
}
}
return duplicate, nil
}
func handleListDuplicates(w http.ResponseWriter, r *http.Request) {
duplicates, err := findDuplicates(w, &db)
if err != nil {
handleErr(w, err)
return
}
for _, d := range duplicates {
fmt.Fprintf(w, "%s\n", d)
}
w.Write([]byte("Done."))
}
func handleRemoveDuplicates(w http.ResponseWriter, r *http.Request) {
duplicates, err := findDuplicates(w, &db)
if err != nil {
handleErr(w, err)
return
}
for _, d := range duplicates {
fmt.Fprintf(w, "Removing: %s\n", d)
p := path.Join(config.StaticDir, d)
if err := os.Remove(p); err != nil {
handleErr(w, err)
return
}
}
w.Write([]byte("Done."))
}
func handleListIncorrectLocations(w http.ResponseWriter, r *http.Request) {
for _, f := range db.Files {
if len(f.Path) == 0 {
continue
}
dir := f.IdealDir()
if !strings.HasPrefix(f.Path, dir) {
fmt.Fprintf(w, "%s: %s\n", dir, f.Path)
}
}
w.Write([]byte("Done."))
}