-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfdup.v
323 lines (312 loc) · 7.36 KB
/
fdup.v
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// fdup - file duplicates finder
// Copyright (C) 2025 Ge <[email protected]>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <https://www.gnu.org/licenses/>.
module main
import os
import cli
import arrays
import maps
import hash.crc32
import hash.fnv1a
import crypto.blake3
import crypto.sha1
import crypto.sha256
import crypto.md5
import runtime
import term
import time
import x.json2 as json
fn main() {
mut app := cli.Command{
name: 'fdup'
description: 'File duplicates finder'
version: '0.2.0'
usage: '[DIR...]'
execute: find
defaults: struct {
man: false
}
flags: [
cli.Flag{
flag: .string
name: 'hash'
description: 'Hashing algorythm: blake3, crc32, fnv1a, sha1, sha256, md5 [default: fnv1a]'
default_value: ['fnv1a']
},
cli.Flag{
flag: .int
name: 'threads'
description: 'Number of threads used for calculating hash sums [default: number of CPU cores]'
default_value: [runtime.nr_cpus().str()]
},
cli.Flag{
flag: .bool
name: 'brief'
description: 'Brief output, print plain easy to parse hashes and filenames only.'
},
cli.Flag{
flag: .bool
name: 'json'
description: 'Print output in JSON format.'
},
cli.Flag{
flag: .string_array
name: 'exclude'
description: 'Glob pattern to exclude files and directories [can be passed multiple times]'
},
cli.Flag{
flag: .bool
name: 'skip-empty'
description: 'Skip empty files.'
},
cli.Flag{
flag: .string
name: 'max-size'
description: 'Maximum file size in bytes. Files larger than this will be skipped.'
},
cli.Flag{
flag: .bool
name: 'remove'
description: 'Remove duplicates.'
},
cli.Flag{
flag: .bool
name: 'prompt'
description: 'Prompt before every removal.'
},
]
}
app.setup()
app.parse(os.args)
}
fn find(cmd cli.Command) ! {
hash_fn := HashFn.from_string(cmd.flags.get_string('hash')!) or { HashFn.fnv1a }
nr_threads := cmd.flags.get_int('threads')!
brief_output := cmd.flags.get_bool('brief')!
json_output := cmd.flags.get_bool('json')!
exclude_globs := cmd.flags.get_strings('exclude')!
skip_empty := cmd.flags.get_bool('skip-empty')!
max_size := cmd.flags.get_string('max-size')!.u64()
remove := cmd.flags.get_bool('remove')!
prompt := cmd.flags.get_bool('prompt')!
if nr_threads <= 0 {
eprintln('threads number cannot be zero or negative')
exit(1)
}
mut search_paths := ['.']
if cmd.args.len > 0 {
search_paths = cmd.args.clone()
}
// collect full list of files absolute paths
mut file_paths := &[]string{}
outer: for search_path in search_paths {
if search_path != '.' {
for glob in exclude_globs {
if search_path.match_glob(glob) {
continue outer
}
}
}
if !os.is_dir(search_path) {
eprintln('${search_path} is not a directory, skip')
continue
}
norm_path := os.norm_path(os.abs_path(os.expand_tilde_to_home(search_path)))
os.walk(norm_path, fn [mut file_paths, exclude_globs, skip_empty, max_size] (file string) {
for glob in exclude_globs {
if file.match_glob(glob) || os.file_name(file).match_glob(glob) {
return
}
}
mut file_size := u64(0)
if skip_empty || max_size > 0 {
file_size = os.file_size(file)
}
if skip_empty && file_size == 0 {
return
}
if max_size > 0 && file_size > max_size {
return
}
file_paths << file
})
}
if file_paths.len == 0 {
eprintln('nothing to do, exiting')
exit(1)
}
eprintln('found ${file_paths.len} files, processing...')
// split the files list into approximately equal parts by the number of threads
mut parts := [][]string{}
if nr_threads == 1 {
parts = [*file_paths]
} else if nr_threads >= file_paths.len {
for path in file_paths {
parts << [path]
}
} else {
parts = arrays.chunk(*file_paths, file_paths.len / nr_threads)
mut idx := 0
for parts.len != nr_threads {
parts[idx] = arrays.append(parts[0], parts.last())
parts.delete_last()
idx++
if idx >= parts.len {
idx = 0
}
}
}
// calculate hashsums in parallel
mut threads := []thread map[string]string{}
for i := 0; i < parts.len; i++ {
threads << spawn calculate_hashsums(i, parts[i], hash_fn)
}
calculated := threads.wait()
mut sums := map[string]string{}
for s in calculated {
maps.merge_in_place(mut sums, s)
}
// find and pretty-print duplicates
dups := find_duplicates(sums)
if dups.len == 0 {
eprintln(term.bold('no duplicates found'))
exit(0)
}
if brief_output {
for hash, files in dups {
for file in files {
println(hash + ':' + file)
}
}
} else if json_output {
mut output := OutputSchema{
hash_fn: hash_fn.str()
}
for hash, files in dups {
mut entries := []FileEntry{}
for file in files {
stat := os.stat(file)!
entries << FileEntry{
path: file
size: stat.size
mtime: time.unix(stat.mtime)
}
}
output.data << Duplicate{
hash: hash
total: entries.len
files: entries
}
}
println(json.encode[OutputSchema](output))
} else {
for hash, files in dups {
println(term.bold(hash))
for file in files {
stat := os.stat(file)!
println('\t${time.unix(stat.mtime)} ${stat.size:-10} ${file}')
}
}
}
if remove {
for _, files in dups {
for file in files[1..] {
if prompt {
answer := os.input("delete file '${file}'? (y/n): ")
if answer != 'y' {
eprintln('skipped ${file}')
continue
}
}
os.rm(file)!
}
}
}
}
struct OutputSchema {
hash_fn string
mut:
data []Duplicate
}
struct Duplicate {
hash string
total int
files []FileEntry
}
struct FileEntry {
path string
size u64
mtime time.Time
}
fn find_duplicates(files map[string]string) map[string][]string {
mut dups := map[string][]string{}
for _, hash in files {
if hash !in dups {
for f, h in files {
if h == hash {
dups[hash] << f
}
}
}
}
for h, f in dups {
if f.len == 1 {
dups.delete(h)
}
}
return dups
}
enum HashFn {
blake3
crc32
fnv1a
sha1
sha256
md5
}
fn hashsum(file string, hash_fn HashFn) string {
file_bytes := os.read_bytes(file) or { []u8{len: 1} }
defer {
unsafe { file_bytes.free() }
}
match hash_fn {
.blake3 {
return blake3.sum256(file_bytes).hex()
}
.crc32 {
return crc32.sum(file_bytes).hex()
}
.fnv1a {
return fnv1a.sum64(file_bytes).hex()
}
.sha1 {
return sha1.sum(file_bytes).hex()
}
.sha256 {
return sha256.sum(file_bytes).hex()
}
.md5 {
return md5.sum(file_bytes).hex()
}
}
}
fn calculate_hashsums(tid int, files []string, hash_fn HashFn) map[string]string {
eprintln('thread ${tid} started with queue of ${files.len} files')
mut sums := map[string]string{}
for file in files {
sums[file] = hashsum(file, hash_fn)
}
return sums
}