use anyhow::Result;
use blake3::Hasher;
use indicatif::{ProgressBar, ProgressStyle};
use rayon::prelude::*;
use std::{
collections::HashMap,
fs::File,
io::{Read, Seek, SeekFrom},
path::{Path, PathBuf},
};
const QUICK_HASH_CHUNK: usize = 4096;
fn blake3_file(path: &Path) -> Result<[u8; 32]> {
let mut f = File::open(path)?;
let mut hasher = Hasher::new();
let mut buf = [0u8; 1024 * 1024];
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(*hasher.finalize().as_bytes())
}
fn quick_hash_file(path: &Path, size: u64) -> Result<[u8; 32]> {
if size <= (QUICK_HASH_CHUNK * 2) as u64 {
return blake3_file(path);
}
let mut f = File::open(path)?;
let mut hasher = Hasher::new();
let mut buf = [0u8; QUICK_HASH_CHUNK];
let n = f.read(&mut buf).unwrap_or(0);
hasher.update(&buf[..n]);
let end = size.saturating_sub(QUICK_HASH_CHUNK as u64);
let _ = f.seek(SeekFrom::Start(end));
let n = f.read(&mut buf).unwrap_or(0);
hasher.update(&buf[..n]);
Ok(*hasher.finalize().as_bytes())
}
pub fn run_dups(
root: &Path,
move_to_trash: bool,
min_bytes: Option<u64>,
max_bytes: Option<u64>,
) -> Result<()> {
if std::env::var("CLEANUX_TEST_DUPS_ERROR").is_ok() {
return Err(anyhow::anyhow!("forced dups error"));
}
let pb = ProgressBar::new_spinner();
if let Ok(style) = ProgressStyle::with_template("{spinner} {msg}") {
pb.set_style(style);
}
pb.set_message("Scanning files...");
let mut by_size: HashMap<u64, Vec<PathBuf>> = HashMap::new();
for dent in crate::fsutil::walk_builder(root).build().flatten() {
let md = if std::env::var("CLEANUX_TEST_BAD_METADATA").is_ok() {
Err(std::io::Error::new(std::io::ErrorKind::Other, "forced"))
} else {
std::fs::symlink_metadata(dent.path())
};
if let Ok(md) = md {
let file_type = md.file_type();
if !file_type.is_file() || file_type.is_symlink() {
continue;
}
let size = md.len();
if let Some(min) = min_bytes {
if size < min {
continue;
}
}
if let Some(max) = max_bytes {
if size > max {
continue;
}
}
by_size.entry(size).or_default().push(dent.into_path());
}
}
let candidates: Vec<(u64, Vec<PathBuf>)> =
by_size.into_iter().filter(|(_, v)| v.len() > 1).collect();
if candidates.is_empty() {
pb.finish_and_clear();
println!("No duplicates found.");
return Ok(());
}
pb.set_message("Quick hashing candidates...");
let quick_hashed: Vec<(u64, [u8; 32], PathBuf)> = candidates
.par_iter()
.flat_map(|(size, paths)| {
paths
.par_iter()
.filter_map(|p| {
quick_hash_file(p, *size)
.ok()
.map(|h| (*size, h, p.clone()))
})
.collect::<Vec<_>>()
})
.collect();
let mut quick_groups: HashMap<(u64, [u8; 32]), Vec<PathBuf>> = HashMap::new();
for (size, hash, p) in quick_hashed {
quick_groups.entry((size, hash)).or_default().push(p);
}
pb.set_message("Hashing candidates...");
let full_hashed: Vec<(u64, [u8; 32], PathBuf)> = quick_groups
.into_iter()
.filter(|(_, v)| v.len() > 1)
.collect::<Vec<_>>()
.par_iter()
.flat_map(|((size, _), paths)| {
paths
.par_iter()
.filter_map(|p| blake3_file(p).ok().map(|h| (*size, h, p.clone())))
.collect::<Vec<_>>()
})
.collect();
let mut by_hash: HashMap<(u64, [u8; 32]), Vec<PathBuf>> = HashMap::new();
for (size, hash, p) in full_hashed {
by_hash.entry((size, hash)).or_default().push(p);
}
pb.finish_and_clear();
let mut groups: Vec<Vec<PathBuf>> = by_hash.into_values().filter(|v| v.len() > 1).collect();
if groups.is_empty() {
println!("No duplicates found.");
return Ok(());
}
groups.sort_by_key(|g| std::cmp::Reverse(g.len()));
println!("Found {} duplicate groups.", groups.len());
for (i, g) in groups.iter().enumerate() {
println!("\n[Group {}] {} files", i + 1, g.len());
for p in g {
println!(" {}", p.display());
}
}
if move_to_trash {
let mut to_trash: Vec<PathBuf> = Vec::new();
for g in &groups {
to_trash.extend(g.iter().skip(1).cloned());
}
if !to_trash.is_empty() {
trash_delete_all(&to_trash)?;
println!("\nMoved {} files to Trash.", to_trash.len());
}
}
Ok(())
}
fn trash_delete_all(paths: &[PathBuf]) -> Result<()> {
if std::env::var("CLEANUX_TEST_DUPS_TRASH_ERROR").is_ok() {
return Err(anyhow::anyhow!("forced dups trash error"));
}
trash::delete_all(paths)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let mut path = std::env::temp_dir();
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
path.push(format!("cleanux_dups_test_{}_{}", prefix, nanos));
fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn blake3_file_errors_on_missing_path() {
let td = TempDir::new("missing");
let missing = td.path.join("nope");
assert!(blake3_file(&missing).is_err());
}
#[test]
fn blake3_file_errors_on_directory_read() {
let td = TempDir::new("dir");
assert!(blake3_file(&td.path).is_err());
}
#[test]
fn quick_hash_file_accepts_directory_read() {
let td = TempDir::new("quick_dir");
quick_hash_file(&td.path, (QUICK_HASH_CHUNK * 3) as u64).unwrap();
}
#[test]
fn quick_hash_file_errors_on_missing_path() {
let td = TempDir::new("quick_missing");
let missing = td.path.join("nope");
assert!(quick_hash_file(&missing, (QUICK_HASH_CHUNK * 3) as u64).is_err());
}
#[test]
fn quick_hash_file_accepts_empty_file() {
let td = TempDir::new("quick_empty");
let empty = td.path.join("empty.bin");
fs::write(&empty, &[]).unwrap();
quick_hash_file(&empty, (QUICK_HASH_CHUNK * 3) as u64).unwrap();
}
}