dedcore 0.1.0

A high-performance deduplication tool
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use crate::safety::QuarantineManager;
use crate::cli;
use inquire::{Confirm, Select, Text};
use std::{thread, time::Duration};

pub fn show_loading_screen() {
    // ANSI color codes
    let cyan = "\x1b[36m";
    let yellow = "\x1b[33m";
    let green = "\x1b[32m";
    let reset = "\x1b[0m";
    println!(
        r#"{cyan}

      ██████╗ ███████╗██████╗  ██████╗ ██████╗ ██████╗ ███████╗
      ██╔══██╗██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝
      ██║  ██║█████╗  ██║  ██║██║     ██║   ██║██████╔╝█████╗  
      ██║  ██║██╔══╝  ██║  ██║██║     ██║   ██║██╔══██╗██╔══╝  
      ██████╔╝███████╗██████╔╝╚██████╗╚██████╔╝██║  ██║███████╗ v 0.1.0
              DEDCORE
{reset}"#,
        cyan = cyan,
        reset = reset
    );
    println!(
        "{yellow}dedcore: Oops, no more duplicates!{reset}\n",
        yellow = yellow,
        reset = reset
    );
    print!("{green}Loading: [", green = green);
    use std::io::{Write, stdout};
    let mut out = stdout();
    for _ in 0..20 {
        print!("#");
        out.flush().unwrap();
        thread::sleep(Duration::from_millis(30));
    }
    println!("]{reset}\n", reset = reset);
    thread::sleep(Duration::from_millis(200));
}

pub fn show_quarantine_menu() {
    loop {
        let options = vec![
            "Quarantine a File",
            "List Quarantined Files",
            "Commit Deletions",
            "Rollback All Quarantined Files",
            "Back",
        ];
        let choice = Select::new("Quarantine Operations:", options.clone())
            .prompt()
            .unwrap_or_else(|_| "Back");
        if choice == "Quarantine a File" {
            let file = Text::new("Enter the path to the file you want to quarantine:")
                .prompt()
                .unwrap_or_default();
            if file.is_empty() {
                println!("No file path entered.");
                continue;
            }
            let mut qm = QuarantineManager::new().expect("Failed to create QuarantineManager");
            match qm.quarantine_file(&file) {
                Ok(_) => println!("File quarantined: {}", file),
                Err(e) => println!("Failed to quarantine file: {}: {}", file, e),
            }
        } else if choice == "List Quarantined Files" {
            let qm = QuarantineManager::new().expect("Failed to create QuarantineManager");
            let files_ref = qm.list_quarantined_files();
            if files_ref.is_empty() {
                println!("No files are currently quarantined.");
                continue;
            }
            // Collect owned records to avoid borrow checker issues
            let files: Vec<_> = files_ref.iter().map(|rec| (*rec).clone()).collect();
            let file_options: Vec<String> = files
                .iter()
                .map(|rec| {
                    let quarantine_exists = std::path::Path::new(&rec.quarantine_path).exists();
                    if quarantine_exists {
                        format!("{} ({} bytes)", rec.original_path, rec.file_size)
                    } else {
                        format!("{} (MISSING)", rec.original_path)
                    }
                })
                .collect();
            let file_choice = Select::new(
                "Select a file to manage:",
                [&file_options[..], &["Back".to_string()]].concat(),
            )
            .prompt()
            .unwrap_or_else(|_| "Back".to_string());
            if file_choice == "Back" {
                continue;
            }
            let idx = file_options.iter().position(|s| s == &file_choice);
            if let Some(i) = idx {
                let rec = &files[i];
                let quarantine_exists = std::path::Path::new(&rec.quarantine_path).exists();
                let action = Select::new(
                    &format!("What would you like to do with {}?", rec.original_path),
                    vec!["Restore (Rollback)", "Delete Permanently (Commit)", "Back"],
                )
                .prompt()
                .unwrap_or_else(|_| "Back");
                if action == "Restore (Rollback)" {
                    if quarantine_exists {
                        let quarantine_path = &rec.quarantine_path;
                        let original_path = &rec.original_path;
                        if let Some(parent) = std::path::Path::new(original_path).parent() {
                            let _ = std::fs::create_dir_all(parent);
                        }
                        match std::fs::rename(quarantine_path, original_path) {
                            Ok(_) => println!("Restored {}", original_path),
                            Err(e) => println!("Failed to restore {}: {}", original_path, e),
                        }
                        // Remove from quarantine state
                        let mut qm2 =
                            QuarantineManager::new().expect("Failed to create QuarantineManager");
                        let _ = qm2.remove_quarantined_file(original_path);
                    } else {
                        println!(
                            "Quarantined file not found: {} (already missing)",
                            rec.quarantine_path
                        );
                        let mut qm2 =
                            QuarantineManager::new().expect("Failed to create QuarantineManager");
                        let _ = qm2.remove_quarantined_file(&rec.original_path);
                    }
                } else if action == "Delete Permanently (Commit)" {
                    if quarantine_exists {
                        let quarantine_path = &rec.quarantine_path;
                        match std::fs::remove_file(quarantine_path) {
                            Ok(_) => println!("Deleted {}", quarantine_path),
                            Err(e) => println!("Failed to delete {}: {}", quarantine_path, e),
                        }
                        // Remove from quarantine state
                        let mut qm2 =
                            QuarantineManager::new().expect("Failed to create QuarantineManager");
                        let _ = qm2.remove_quarantined_file(&rec.original_path);
                    } else {
                        println!(
                            "Quarantined file not found: {} (already missing)",
                            rec.quarantine_path
                        );
                        let mut qm2 =
                            QuarantineManager::new().expect("Failed to create QuarantineManager");
                        let _ = qm2.remove_quarantined_file(&rec.original_path);
                    }
                } else {
                    continue;
                }
            }
        } else if choice == "Commit Deletions" {
            let mut qm = QuarantineManager::new().expect("Failed to create QuarantineManager");
            match qm.commit_deletions() {
                Ok(count) => println!("{} quarantined files permanently deleted.", count),
                Err(e) => println!("Failed to commit deletions: {}", e),
            }
        } else if choice == "Rollback All Quarantined Files" {
            let mut qm = QuarantineManager::new().expect("Failed to create QuarantineManager");
            let mut missing = Vec::new();
            let mut restored = 0;
            for rec in qm
                .list_quarantined_files()
                .into_iter()
                .cloned()
                .collect::<Vec<_>>()
            {
                let quarantine_exists = std::path::Path::new(&rec.quarantine_path).exists();
                if quarantine_exists {
                    let quarantine_path = &rec.quarantine_path;
                    let original_path = &rec.original_path;
                    if let Some(parent) = std::path::Path::new(original_path).parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    match std::fs::rename(quarantine_path, original_path) {
                        Ok(_) => {
                            let _ = qm.remove_quarantined_file(original_path);
                            restored += 1;
                        }
                        Err(e) => println!("Failed to restore {}: {}", original_path, e),
                    }
                } else {
                    missing.push(rec.original_path.clone());
                    let _ = qm.remove_quarantined_file(&rec.original_path);
                }
            }
            println!(
                "{} quarantined files restored to their original locations.",
                restored
            );
            if !missing.is_empty() {
                println!(
                    "{} quarantined files were missing and could not be restored:",
                    missing.len()
                );
                for m in missing {
                    println!("  {}", m);
                }
            }
        } else if choice == "Back" {
            break;
        }
    }
}

pub fn show_help_menu() {
    println!("\n=== DedCore Help ===");
    println!("- Use the arrow keys to navigate menus and Enter to select.");
    println!("- Main features:");
    println!("  * Scan for Duplicates: Find duplicate files in a directory.");
    println!("  * Quarantine Operations: Safely move, delete, or restore files.");
    println!("  * Commit Deletions: Permanently delete quarantined files.");
    println!("  * Rollback: Restore quarantined files to their original locations.");
    println!("- For more info, see the README or project documentation.\n");
    let _ = Text::new("Press Enter to return to the main menu...").prompt();
}

pub fn scan_menu() {
    // Path
    let path = select_path();
    if path.trim().is_empty() {
        println!("No path provided. Aborting scan.");
        return;
    }
    // Security
    let security = select_security();
    // Speed
    let speed = select_speed();
    // Filetypes
    let filetypes =
        Text::new("File types to include (comma-separated, e.g. txt,jpg; leave blank for all):")
            .with_placeholder("txt,jpg")
            .prompt()
            .unwrap_or_default();
    // Min size
    let min_size = Text::new("Minimum file size in bytes (leave blank for none):")
        .with_placeholder("0")
        .prompt()
        .unwrap_or_default();
    // Max size
    let max_size = Text::new("Maximum file size in bytes (leave blank for none):")
        .with_placeholder("1000000")
        .prompt()
        .unwrap_or_default();
    // Min age
    let min_age = Text::new("Minimum file age in days (leave blank for none):")
        .with_placeholder("0")
        .prompt()
        .unwrap_or_default();
    // Max age
    let max_age = Text::new("Maximum file age in days (leave blank for none):")
        .with_placeholder("365")
        .prompt()
        .unwrap_or_default();
    // Regex
    let regex = Text::new("Regex filter for file paths (leave blank for none):")
        .with_placeholder(".*backup.*")
        .prompt()
        .unwrap_or_default();
    // Dry run
    let dry_run = Confirm::new("Dry run? (Show what would happen, but make no changes)")
        .with_default(false)
        .prompt()
        .unwrap_or(false);
    // Quarantine all duplicates
    let quarantine_all =
        Confirm::new("Quarantine all duplicates (all but one per group) after scan?")
            .with_default(false)
            .prompt()
            .unwrap_or(false);
    // Similarity threshold for text file grouping
    let similarity_threshold = Text::new(
        "Minimum similarity threshold for grouping similar text files (0.0-1.0, default: 0.8):",
    )
    .with_placeholder("0.8")
    .prompt()
    .unwrap_or_default();
    // Similarity threshold for image file grouping
    let image_similarity_threshold = Text::new(
        "Minimum similarity threshold for grouping similar image files (0.0-1.0, default: 0.9):",
    )
    .with_placeholder("0.9")
    .prompt()
    .unwrap_or_default();

    // --- Pre-scan summary ---
    // This summary helps users catch mistakes before running a potentially expensive scan.
    // Confirmation step is a good UX touch for safety.
    println!("\n=== Scan Summary ===");
    println!("Path: {}", path);
    println!("Security: {}", security);
    println!("Speed: {}", speed);
    if !filetypes.is_empty() {
        println!("File types: {}", filetypes);
    }
    if !min_size.is_empty() {
        println!("Min size: {} bytes", min_size);
    }
    if !max_size.is_empty() {
        println!("Max size: {} bytes", max_size);
    }
    if !min_age.is_empty() {
        println!("Min age: {} days", min_age);
    }
    if !max_age.is_empty() {
        println!("Max age: {} days", max_age);
    }
    if !regex.is_empty() {
        println!("Regex: {}", regex);
    }
    println!("Dry run: {}", if dry_run { "yes" } else { "no" });
    println!(
        "Quarantine all duplicates: {}",
        if quarantine_all { "yes" } else { "no" }
    );
    if !similarity_threshold.is_empty() {
        println!("Text similarity threshold: {}", similarity_threshold);
    }
    if !image_similarity_threshold.is_empty() {
        println!("Image similarity threshold: {}", image_similarity_threshold);
    }
    println!("====================\n");
    // Confirm before running
    if !Confirm::new("Proceed with scan?")
        .with_default(true)
        .prompt()
        .unwrap_or(false)
    {
        println!("Scan cancelled.");
        return;
    }
    // Build CLI args
    let mut args = vec!["dedcore".to_string()];
    args.push(path.clone());
    args.push(format!("--security={}", security));
    args.push(format!("--speed={}", speed));
    if !filetypes.is_empty() {
        args.push(format!("--filetypes={}", filetypes));
    }
    if !min_size.is_empty() {
        args.push(format!("--min-size={}", min_size));
    }
    if !max_size.is_empty() {
        args.push(format!("--max-size={}", max_size));
    }
    if !min_age.is_empty() {
        args.push(format!("--min-age={}", min_age));
    }
    if !max_age.is_empty() {
        args.push(format!("--max-age={}", max_age));
    }
    if !regex.is_empty() {
        args.push(format!("--regex={}", regex));
    }
    if dry_run {
        args.push("--dry".to_string());
    }
    if quarantine_all {
        args.push("--quarantine-all-dupes".to_string());
    }
    if !similarity_threshold.trim().is_empty() {
        if let Ok(val) = similarity_threshold.trim().parse::<f64>() {
            if val >= 0.0 && val <= 1.0 {
                args.push(format!("--similarity-threshold={}", val));
            } else {
                println!(
                    "Invalid similarity threshold, must be between 0.0 and 1.0. Using default (0.8)."
                );
            }
        } else {
            println!("Invalid similarity threshold input. Using default (0.8).");
        }
    }
    if !image_similarity_threshold.trim().is_empty() {
        if let Ok(val) = image_similarity_threshold.trim().parse::<f64>() {
            if val >= 0.0 && val <= 1.0 {
                args.push(format!("--image-similarity-threshold={}", val));
            } else {
                println!(
                    "Invalid image similarity threshold, must be between 0.0 and 1.0. Using default (0.9)."
                );
            }
        } else {
            println!("Invalid image similarity threshold input. Using default (0.9).");
        }
    }
    // Call CLI logic with constructed args
    cli::run_with_args(args);
}

pub fn main_menu() -> String {
    let options = vec![
        "Scan for Duplicates",
        "Quarantine Operations",
        "Help",
        "Sponsor Us",
        "Exit",
    ];
    loop {
        let choice = Select::new("What would you like to do?", options.clone())
            .prompt()
            .map(|s| s.to_string())
            .unwrap_or_else(|_| "Exit".to_string());
        if choice == "Sponsor Us" {
            show_sponsor_message();
            continue;
        }
        return choice;
    }
}

pub fn select_path() -> String {
    Text::new("Paste the path to a file or directory:")
        .prompt()
        .unwrap_or_else(|_| String::new())
}

pub fn select_security() -> String {
    let options = vec!["high", "maximum", "medium", "low"];
    Select::new("Select security level:", options)
        .prompt()
        .map(|s| s.to_string())
        .unwrap_or_else(|_| "high".to_string())
}

pub fn select_speed() -> String {
    let options = vec!["balanced", "fastest", "mostsecure"];
    Select::new("Select speed preference:", options)
        .prompt()
        .map(|s| s.to_string())
        .unwrap_or_else(|_| "balanced".to_string())
}

fn show_sponsor_message() {
    println!("\n=== Sponsor DedCore ===");
    println!("If you like this project, consider sponsoring us!");
    println!("GitHub Sponsors: https://github.com/sponsors/yourusername");
    println!("Or buy us a coffee: https://buymeacoffee.com/yourusername\n");
    let _ = Text::new("Press Enter to return to the main menu...").prompt();
}