-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicates.go
More file actions
421 lines (351 loc) · 11.5 KB
/
duplicates.go
File metadata and controls
421 lines (351 loc) · 11.5 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
)
// DuplicateHandler handles the removal of duplicate files
type DuplicateHandler struct {
Scanner *Scanner
DryRun bool
}
// NewDuplicateHandler creates a new DuplicateHandler instance
func NewDuplicateHandler(scanner *Scanner, dryRun bool) *DuplicateHandler {
return &DuplicateHandler{
Scanner: scanner,
DryRun: dryRun,
}
}
// atomicMove performs an atomic file move operation
func (dh *DuplicateHandler) atomicMove(src, dst string) error {
// Try atomic rename first (works on same filesystem)
err := os.Rename(src, dst)
if err == nil {
return nil
}
// If rename fails (cross-device), use copy + delete
return dh.copyAndDelete(src, dst)
}
// RemoveDuplicates removes duplicate files, keeping the newest version of each
func (dh *DuplicateHandler) RemoveDuplicates() error {
if len(dh.Scanner.Duplicates) == 0 {
fmt.Println("✅ No duplicates found to remove!")
return nil
}
successColor := color.New(color.FgGreen, color.Bold)
warningColor := color.New(color.FgYellow)
infoColor := color.New(color.FgCyan)
fmt.Println("🔄 Processing duplicate files...")
totalRemoved := 0
totalSpaceSaved := int64(0)
for hash, files := range dh.Scanner.Duplicates {
if len(files) < 2 {
continue
}
// Find the newest file to keep
newestFile := files[0]
for _, file := range files {
if file.LastModified.After(newestFile.LastModified) {
newestFile = file
}
}
infoColor.Printf("📋 Processing duplicates for hash: %s...\n", hash[:8]+"...")
infoColor.Printf(" Keeping: %s (%.2f MB, modified: %s)\n",
newestFile.Name,
float64(newestFile.Size)/1024/1024,
newestFile.LastModified.Format("2006-01-02 15:04:05"))
// Remove all other duplicates
for _, file := range files {
if file.Path == newestFile.Path {
continue
}
if dh.DryRun {
warningColor.Printf(" 🗑️ Would remove: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
} else {
fmt.Printf(" 🗑️ Removing: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
err := os.Remove(file.Path)
if err != nil {
warningColor.Printf(" ⚠️ Failed to remove %s: %v\n", file.Name, err)
continue
}
}
totalRemoved++
totalSpaceSaved += file.Size
}
fmt.Println()
}
if totalRemoved > 0 {
successColor.Printf("✅ Removed %d duplicate files!\n", totalRemoved)
successColor.Printf("💾 Space saved: %.2f MB\n", float64(totalSpaceSaved)/1024/1024)
} else {
fmt.Println("✅ No files were removed.")
}
return nil
}
// RemoveDuplicatesInteractive removes duplicate files with interactive selection
func (dh *DuplicateHandler) RemoveDuplicatesInteractive() error {
if len(dh.Scanner.Duplicates) == 0 {
fmt.Println("✅ No duplicates found to remove!")
return nil
}
successColor := color.New(color.FgGreen, color.Bold)
warningColor := color.New(color.FgYellow)
infoColor := color.New(color.FgCyan)
errorColor := color.New(color.FgRed, color.Bold)
fmt.Println("🔄 Interactive duplicate removal...")
fmt.Println("For each set of duplicates, you'll be asked which file to keep.")
fmt.Println()
totalRemoved := 0
totalSpaceSaved := int64(0)
for hash, files := range dh.Scanner.Duplicates {
if len(files) < 2 {
continue
}
infoColor.Printf("📋 Found %d duplicates with hash: %s\n", len(files), hash[:8]+"...")
// Display files with numbers
for i, file := range files {
fmt.Printf(" %d. %s (%.2f MB, modified: %s)\n",
i+1,
file.Name,
float64(file.Size)/1024/1024,
file.LastModified.Format("2006-01-02 15:04:05"))
}
// Ask user which file to keep
var choice int
for {
fmt.Printf("\n🤔 Which file would you like to keep? (1-%d, or 0 to skip): ", len(files))
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println(" Please enter a valid number.")
// Clear the input buffer to prevent infinite loop
var discard string
fmt.Scanln(&discard)
continue
}
if choice == 0 {
fmt.Println(" Skipping this set of duplicates.")
break
}
if choice < 1 || choice > len(files) {
fmt.Printf(" Please enter a number between 1 and %d.\n", len(files))
continue
}
// Valid choice
keepFile := files[choice-1]
infoColor.Printf(" Keeping: %s\n", keepFile.Name)
// Remove other files
for i, file := range files {
if i == choice-1 {
continue
}
if dh.DryRun {
warningColor.Printf(" 🗑️ Would remove: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
} else {
fmt.Printf(" 🗑️ Removing: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
err := os.Remove(file.Path)
if err != nil {
errorColor.Printf(" ❌ Failed to remove %s: %v\n", file.Name, err)
continue
}
}
totalRemoved++
totalSpaceSaved += file.Size
}
break
}
fmt.Println()
}
if totalRemoved > 0 {
successColor.Printf("✅ Removed %d duplicate files!\n", totalRemoved)
successColor.Printf("💾 Space saved: %.2f MB\n", float64(totalSpaceSaved)/1024/1024)
} else {
fmt.Println("✅ No files were removed.")
}
return nil
}
// RemoveDuplicatesByPattern removes duplicates based on naming patterns
func (dh *DuplicateHandler) RemoveDuplicatesByPattern() error {
if len(dh.Scanner.Duplicates) == 0 {
fmt.Println("✅ No duplicates found to remove!")
return nil
}
successColor := color.New(color.FgGreen, color.Bold)
warningColor := color.New(color.FgYellow)
infoColor := color.New(color.FgCyan)
fmt.Println("🔄 Removing duplicates by pattern...")
fmt.Println("Keeping files without copy indicators like '(1)', 'copy', etc.")
fmt.Println()
totalRemoved := 0
totalSpaceSaved := int64(0)
for hash, files := range dh.Scanner.Duplicates {
if len(files) < 2 {
continue
}
// Find the file that looks like the original (no copy indicators)
var originalFile *FileInfo
var copyFiles []FileInfo
for _, file := range files {
if dh.isOriginalFile(file.Name) {
originalFile = &file
} else {
copyFiles = append(copyFiles, file)
}
}
// If we couldn't determine an original, keep the newest
if originalFile == nil {
originalFile = &files[0]
for _, file := range files {
if file.LastModified.After(originalFile.LastModified) {
originalFile = &file
}
}
// Add all other files to copies
for _, file := range files {
if file.Path != originalFile.Path {
copyFiles = append(copyFiles, file)
}
}
}
infoColor.Printf("📋 Processing duplicates for hash: %s...\n", hash[:8]+"...")
infoColor.Printf(" Keeping: %s (%.2f MB)\n", originalFile.Name, float64(originalFile.Size)/1024/1024)
// Remove copy files
for _, file := range copyFiles {
if dh.DryRun {
warningColor.Printf(" 🗑️ Would remove: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
} else {
fmt.Printf(" 🗑️ Removing: %s (%.2f MB)\n", file.Name, float64(file.Size)/1024/1024)
err := os.Remove(file.Path)
if err != nil {
warningColor.Printf(" ⚠️ Failed to remove %s: %v\n", file.Name, err)
continue
}
}
totalRemoved++
totalSpaceSaved += file.Size
}
fmt.Println()
}
if totalRemoved > 0 {
successColor.Printf("✅ Removed %d duplicate files!\n", totalRemoved)
successColor.Printf("💾 Space saved: %.2f MB\n", float64(totalSpaceSaved)/1024/1024)
} else {
fmt.Println("✅ No files were removed.")
}
return nil
}
// isOriginalFile determines if a filename looks like an original (not a copy)
func (dh *DuplicateHandler) isOriginalFile(filename string) bool {
lowerName := strings.ToLower(filename)
// Patterns that indicate a file is a copy
copyPatterns := []string{
" (1)", " (2)", " (3)", " (4)", " (5)", " (6)", " (7)", " (8)", " (9)", " (10)",
" copy", " copy (1)", " copy (2)", " copy (3)", " copy (4)", " copy (5)",
" - copy", " - copy (1)", " - copy (2)", " - copy (3)", " - copy (4)", " - copy (5)",
"_copy", "_copy(1)", "_copy(2)", "_copy(3)", "_copy(4)", "_copy(5)",
"-copy", "-copy(1)", "-copy(2)", "-copy(3)", "-copy(4)", "-copy(5)",
".copy", ".copy(1)", ".copy(2)", ".copy(3)", ".copy(4)", ".copy(5)",
" (copy)", " (copy 1)", " (copy 2)", " (copy 3)", " (copy 4)", " (copy 5)",
"- (copy)", "- (copy 1)", "- (copy 2)", "- (copy 3)", "- (copy 4)", "- (copy 5)",
"_ (copy)", "_ (copy 1)", "_ (copy 2)", "_ (copy 3)", "_ (copy 4)", "_ (copy 5)",
" duplicate", " duplicate (1)", " duplicate (2)", " duplicate (3)", " duplicate (4)", " duplicate (5)",
" - duplicate", " - duplicate (1)", " - duplicate (2)", " - duplicate (3)", " - duplicate (4)", " - duplicate (5)",
"_duplicate", "_duplicate(1)", "_duplicate(2)", "_duplicate(3)", "_duplicate(4)", "_duplicate(5)",
"-duplicate", "-duplicate(1)", "-duplicate(2)", "-duplicate(3)", "-duplicate(4)", "-duplicate(5)",
}
for _, pattern := range copyPatterns {
if strings.Contains(lowerName, pattern) {
return false
}
}
return true
}
// MoveDuplicatesToFolder moves duplicate files to a specified folder instead of deleting them
func (dh *DuplicateHandler) MoveDuplicatesToFolder(destFolder string) error {
if len(dh.Scanner.Duplicates) == 0 {
fmt.Println("✅ No duplicates found to move!")
return nil
}
successColor := color.New(color.FgGreen, color.Bold)
warningColor := color.New(color.FgYellow)
infoColor := color.New(color.FgCyan)
// Create destination folder if it doesn't exist
if !dh.DryRun {
err := os.MkdirAll(destFolder, 0755)
if err != nil {
return fmt.Errorf("failed to create destination folder: %v", err)
}
}
fmt.Printf("🔄 Moving duplicates to: %s\n", destFolder)
fmt.Println()
totalMoved := 0
totalSpaceSaved := int64(0)
for hash, files := range dh.Scanner.Duplicates {
if len(files) < 2 {
continue
}
// Find the newest file to keep
newestFile := files[0]
for _, file := range files {
if file.LastModified.After(newestFile.LastModified) {
newestFile = file
}
}
infoColor.Printf("📋 Processing duplicates for hash: %s...\n", hash[:8]+"...")
infoColor.Printf(" Keeping: %s (%.2f MB)\n", newestFile.Name, float64(newestFile.Size)/1024/1024)
// Move all other duplicates
for _, file := range files {
if file.Path == newestFile.Path {
continue
}
destPath := filepath.Join(destFolder, file.Name)
if dh.DryRun {
warningColor.Printf(" 📁 Would move: %s -> %s\n", file.Name, destFolder)
} else {
fmt.Printf(" 📁 Moving: %s\n", file.Name)
err := dh.atomicMove(file.Path, destPath)
if err != nil {
warningColor.Printf(" ⚠️ Failed to move %s: %v\n", file.Name, err)
continue
}
}
totalMoved++
totalSpaceSaved += file.Size
}
fmt.Println()
}
if totalMoved > 0 {
successColor.Printf("✅ Moved %d duplicate files!\n", totalMoved)
successColor.Printf("💾 Space saved in original folder: %.2f MB\n", float64(totalSpaceSaved)/1024/1024)
} else {
fmt.Println("✅ No files were moved.")
}
return nil
}
// copyAndDelete copies a file to destination and then deletes the original
func (dh *DuplicateHandler) copyAndDelete(src, dst string) error {
// Open source file
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
// Create destination file
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
// Copy file content
_, err = dstFile.ReadFrom(srcFile)
if err != nil {
return err
}
// Sync to ensure data is written
if err := dstFile.Sync(); err != nil {
return err
}
// Delete source file
return os.Remove(src)
}