This repository has been archived by the owner on Nov 11, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfind-duplicate-files.go
214 lines (190 loc) · 4.42 KB
/
find-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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"errors"
"flag"
"fmt"
"hash/fnv"
"io"
"os"
"path/filepath"
"runtime"
"strings"
)
type HashToFiles map[uint64][]string
type MaybeHash struct {
path string
hash uint64
err error
}
// Hash the file at 'path'.
func hashFile(path string) (uint64, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
buffer := make([]byte, 4096, 4096)
hash := fnv.New64a()
for {
n, err := file.Read(buffer)
if n > 0 {
hash.Write(buffer[:n])
}
if err == io.EOF {
break
} else if err != nil {
return 0, err
}
}
return hash.Sum64(), nil
}
func hashFileAsync(path string, response chan MaybeHash) {
hash, err := hashFile(path)
if err != nil {
response <- MaybeHash{err: err}
} else {
response <- MaybeHash{path: path, hash: hash, err: nil}
}
}
func sortDirContents(dir string) ([]string, []string, error) {
dirFile, err := os.Open(dir)
if err != nil {
return nil, nil, err
}
// While guarantees closure, is not immediate and so need explicit call
// later on.
defer dirFile.Close()
contents, err := dirFile.Readdir(0)
if err != nil {
return nil, nil, err
}
dirs := make([]string, 0, len(contents))
files := make([]string, 0, len(contents))
for _, content := range contents {
path := filepath.Join(dir, content.Name())
if content.IsDir() {
dirs = append(dirs, path)
} else {
files = append(files, path)
}
}
return dirs, files, nil
}
// Find all the files contained within 'directories'.
func findFiles(dirs []string) ([]string, error) {
files := make([]string, 0, 100)
// Can't use ranged 'for' as the length of directories changes during iteration.
for x := 0; x < len(dirs); x++ {
directory := dirs[x]
dirsInDir, filesInDir, err := sortDirContents(directory)
if err != nil {
return nil, err
}
dirs = append(dirs, dirsInDir...)
files = append(files, filesInDir...)
}
return files, nil
}
func findDuplicates(files []string) (HashToFiles, error) {
hashToFiles := make(HashToFiles)
for _, path := range files {
hash, err := hashFile(path)
if err != nil {
return nil, err
}
files, ok := hashToFiles[hash]
if !ok {
files = make([]string, 0, 2)
}
hashToFiles[hash] = append(files, path)
}
return hashToFiles, nil
}
func findDuplicatesConcurrently(filePaths []string) (HashToFiles, error) {
response := make(chan MaybeHash, len(filePaths))
maxFds := runtime.NumCPU()
throttle := make(chan bool, maxFds)
for _, path := range filePaths {
// Buffering will block until a goroutine thread is available.
throttle <- true
go func(path string) {
hashFileAsync(path, response)
<- throttle
}(path)
}
for i:= 0; i < maxFds; i++ {
// Will block until goroutines have removed all entries they have put
// in.
throttle <- true
}
close(response)
hashToFiles := make(HashToFiles)
for hashResult := range response {
if hashResult.err != nil {
return nil, hashResult.err
}
files, ok := hashToFiles[hashResult.hash]
if !ok {
files = make([]string, 0, 2)
}
hashToFiles[hashResult.hash] = append(files, hashResult.path)
}
return hashToFiles, nil
}
func ValidateArgIsDir(arg string) error {
dir, err := os.Open(arg)
if err != nil {
return err
}
defer dir.Close()
info, err := dir.Stat()
if err != nil {
return err
} else if !info.IsDir() {
return errors.New(fmt.Sprintf("%v is not a directory", arg))
}
return nil
}
// Validate the passed-in arguments are directories.
func validateArgs(args []string) error {
if len(args) < 1 {
return errors.New("expected 1 or more arguments")
}
for _, directory := range args {
err := ValidateArgIsDir(directory)
if err != nil {
return err
}
}
return nil
}
func errorExit(err error) {
// Would be more correct if flags.out() were publicly available instead of hard coding os.Stderr.
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// find-duplicate-files takes 1 or more directories on the command-line,
// recurses into all of them, and prints out what files are duplicates of
// each other.
func main() {
flag.Parse()
directories := flag.Args()
err := validateArgs(directories)
if err != nil {
errorExit(err)
}
files, err := findFiles(directories)
if err != nil {
errorExit(err)
}
//duplicates, err := findDuplicates(files)
duplicates, err := findDuplicatesConcurrently(files)
if err != nil {
errorExit(err)
}
for _, duplicate := range duplicates {
if len(duplicate) > 1 {
fmt.Printf("%v\n\n", strings.Join(duplicate, "\n"))
}
}
}