Skip to main content

compare_dir/
file_hasher.rs

1use crate::ProgressReporter;
2use crate::file_hash_cache::FileHashCache;
3use std::collections::HashMap;
4use std::fs;
5use std::io::{self, Read};
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, mpsc};
8use walkdir::WalkDir;
9
10#[derive(Debug, Clone)]
11enum HashProgress {
12    StartDiscovering,
13    TotalFiles(usize),
14    Result(PathBuf, u64, blake3::Hash, bool),
15}
16
17enum EntryState {
18    Single(PathBuf, std::time::SystemTime),
19    Hashing,
20}
21
22/// A group of duplicated files and their size.
23#[derive(Debug, Clone)]
24pub struct DuplicatedFiles {
25    pub paths: Vec<PathBuf>,
26    pub size: u64,
27}
28
29/// A tool for finding duplicated files in a directory.
30pub struct FileHasher {
31    dir: PathBuf,
32    pub buffer_size: usize,
33    cache: Arc<FileHashCache>,
34}
35
36impl FileHasher {
37    /// Creates a new `FileHasher` for the given directory.
38    pub fn new(dir: PathBuf) -> Self {
39        let cache = FileHashCache::find_or_new(&dir);
40        Self {
41            dir,
42            buffer_size: crate::FileComparer::DEFAULT_BUFFER_SIZE,
43            cache,
44        }
45    }
46
47    /// Save the hash cache if it is dirty.
48    pub fn save_cache(&self) -> anyhow::Result<()> {
49        Ok(self.cache.save()?)
50    }
51
52    /// Clears the loaded hashes in the cache.
53    pub fn clear_cache(&self) -> anyhow::Result<()> {
54        let relative = self.dir.strip_prefix(self.cache.base_dir())?;
55        self.cache.clear(relative);
56        Ok(())
57    }
58
59    /// Executes the duplicate file finding process and prints results.
60    pub fn run(&self) -> anyhow::Result<()> {
61        let start_time = std::time::Instant::now();
62        let mut duplicates = self.find_duplicates()?;
63        if duplicates.is_empty() {
64            println!("No duplicates found.");
65        } else {
66            duplicates.sort_by(|a, b| a.size.cmp(&b.size));
67            let mut total_wasted_space = 0;
68            for dupes in &duplicates {
69                let paths = &dupes.paths;
70                let file_size = dupes.size;
71                println!(
72                    "Identical {} files of {}:",
73                    paths.len(),
74                    crate::human_readable_size(file_size)
75                );
76                for path in paths {
77                    println!("  {}", path.display());
78                }
79                total_wasted_space += file_size * (paths.len() as u64 - 1);
80            }
81            eprintln!(
82                "Total wasted space: {}",
83                crate::human_readable_size(total_wasted_space)
84            );
85        }
86        eprintln!("Finished in {:?}.", start_time.elapsed());
87        Ok(())
88    }
89
90    /// Finds duplicated files and returns a list of duplicate groups.
91    pub fn find_duplicates(&self) -> anyhow::Result<Vec<DuplicatedFiles>> {
92        let progress = ProgressReporter::new();
93        progress.set_message("Scanning directories...");
94
95        let (tx, rx) = mpsc::channel();
96        let mut by_hash: HashMap<blake3::Hash, DuplicatedFiles> = HashMap::new();
97        let mut num_cache_hits = 0;
98        std::thread::scope(|scope| {
99            scope.spawn(|| {
100                if let Err(e) = self.find_duplicates_internal(tx) {
101                    log::error!("Error during duplicate finding: {}", e);
102                }
103            });
104
105            while let Ok(event) = rx.recv() {
106                match event {
107                    HashProgress::StartDiscovering => {
108                        progress.set_message("Hashing files...");
109                    }
110                    HashProgress::TotalFiles(total) => {
111                        progress.set_length(total as u64);
112                        if num_cache_hits > 0 {
113                            progress.set_message(format!(" ({} cache hits)", num_cache_hits));
114                        }
115                    }
116                    HashProgress::Result(path, size, hash, is_cache_hit) => {
117                        if is_cache_hit {
118                            num_cache_hits += 1;
119                            if progress.length().is_none() {
120                                progress.set_message(format!(
121                                    "Hashing files... ({} cache hits)",
122                                    num_cache_hits
123                                ));
124                            } else {
125                                progress.set_message(format!(" ({} cache hits)", num_cache_hits));
126                            }
127                        }
128
129                        progress.inc(1);
130                        let entry = by_hash.entry(hash).or_insert_with(|| DuplicatedFiles {
131                            paths: Vec::new(),
132                            size,
133                        });
134                        // Hash collisions shouldn't happen, but if they do, sizes shouldn't mismatch.
135                        assert_eq!(entry.size, size, "Hash collision: sizes do not match");
136                        entry.paths.push(path);
137                    }
138                }
139            }
140        });
141        progress.finish();
142
143        let mut duplicates = Vec::new();
144        for (_, mut dupes) in by_hash {
145            if dupes.paths.len() > 1 {
146                dupes.paths.sort();
147                duplicates.push(dupes);
148            }
149        }
150        Ok(duplicates)
151    }
152
153    fn find_duplicates_internal(&self, tx: mpsc::Sender<HashProgress>) -> anyhow::Result<()> {
154        tx.send(HashProgress::StartDiscovering)?;
155        let mut by_size: HashMap<u64, EntryState> = HashMap::new();
156        let mut total_hashed = 0;
157
158        rayon::scope(|scope| -> anyhow::Result<()> {
159            for entry in WalkDir::new(&self.dir).into_iter().filter_map(|e| e.ok()) {
160                if !entry.file_type().is_file() {
161                    continue;
162                }
163                let meta = entry.metadata()?;
164                let size = meta.len();
165                let modified = meta.modified()?;
166                // Small optimization: If file size is 0, it's not really worth treating
167                // as wasted space duplicates in the same way, but keeping it unified for now.
168                let current_path = entry.path().to_path_buf();
169
170                match by_size.entry(size) {
171                    std::collections::hash_map::Entry::Occupied(mut occ) => match occ.get_mut() {
172                        EntryState::Single(first_path, first_modified) => {
173                            // We found a second file of identical size.
174                            // Time to start hashing both the *original* matching file and the *new* one!
175                            self.spawn_hash_task(scope, first_path, size, *first_modified, &tx);
176                            self.spawn_hash_task(scope, &current_path, size, modified, &tx);
177
178                            // Modify the state to indicate we are now fully hashing this size bucket.
179                            *occ.get_mut() = EntryState::Hashing;
180                            total_hashed += 2;
181                        }
182                        EntryState::Hashing => {
183                            // File size bucket already hashing; just dynamically spawn the new file immediately.
184                            self.spawn_hash_task(scope, &current_path, size, modified, &tx);
185                            total_hashed += 1;
186                        }
187                    },
188                    std::collections::hash_map::Entry::Vacant(vac) => {
189                        vac.insert(EntryState::Single(current_path, modified));
190                    }
191                }
192            }
193            tx.send(HashProgress::TotalFiles(total_hashed))?;
194            Ok(())
195        })?;
196
197        // The scope waits for all spawned tasks to complete.
198        // Channel `tx` gets naturally closed when it drops at the end of this function.
199        self.save_cache()
200    }
201
202    fn spawn_hash_task<'scope>(
203        &'scope self,
204        scope: &rayon::Scope<'scope>,
205        path: &Path,
206        size: u64,
207        modified: std::time::SystemTime,
208        tx: &mpsc::Sender<HashProgress>,
209    ) {
210        let relative = path
211            .strip_prefix(self.cache.base_dir())
212            .expect("path should be in cache base_dir");
213        if let Some(hash) = self.cache.get(relative, modified) {
214            let _ = tx.send(HashProgress::Result(path.to_path_buf(), size, hash, true));
215            return;
216        }
217
218        let path_owned = path.to_path_buf();
219        let relative_owned = relative.to_path_buf();
220        let tx_owned = tx.clone();
221        let cache_owned = self.cache.clone();
222        scope.spawn(move |_| {
223            if let Ok(hash) = Self::compute_hash(&path_owned, self.buffer_size) {
224                cache_owned.insert(&relative_owned, modified, hash);
225                let _ = tx_owned.send(HashProgress::Result(path_owned, size, hash, false));
226            } else {
227                log::warn!("Failed to hash file: {:?}", path_owned);
228            }
229        });
230    }
231
232    /// Gets the hash of a file, using the cache if available.
233    pub fn get_hash(&self, path: &Path) -> io::Result<blake3::Hash> {
234        let meta = fs::metadata(path)?;
235        let modified = meta.modified()?;
236        let relative = path
237            .strip_prefix(self.cache.base_dir())
238            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
239
240        if let Some(hash) = self.cache.get(relative, modified) {
241            return Ok(hash);
242        }
243
244        let hash = Self::compute_hash(path, self.buffer_size)?;
245        self.cache.insert(relative, modified, hash);
246        Ok(hash)
247    }
248
249    fn compute_hash(path: &Path, buffer_size: usize) -> io::Result<blake3::Hash> {
250        let start_time = std::time::Instant::now();
251        let mut f = fs::File::open(path)?;
252        let mut hasher = blake3::Hasher::new();
253        if buffer_size == 0 {
254            let len = f.metadata()?.len();
255            if len > 0 {
256                let mmap = unsafe { memmap2::MmapOptions::new().map(&f)? };
257                hasher.update(&mmap[..]);
258            }
259        } else {
260            let mut buf = vec![0u8; buffer_size];
261            loop {
262                let n = f.read(&mut buf)?;
263                if n == 0 {
264                    break;
265                }
266                hasher.update(&buf[..n]);
267            }
268        }
269        log::trace!("Hashed in {:?}: {:?}", start_time.elapsed(), path);
270        Ok(hasher.finalize())
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use std::io::Write;
278
279    fn create_file(path: &Path, content: &str) -> io::Result<()> {
280        let mut file = fs::File::create(path)?;
281        file.write_all(content.as_bytes())?;
282        Ok(())
283    }
284
285    #[test]
286    fn test_find_duplicates() -> anyhow::Result<()> {
287        let dir = tempfile::tempdir()?;
288
289        let file1_path = dir.path().join("same1.txt");
290        create_file(&file1_path, "same content")?;
291
292        let file2_path = dir.path().join("same2.txt");
293        create_file(&file2_path, "same content")?;
294
295        let diff_path = dir.path().join("diff.txt");
296        create_file(&diff_path, "different content")?;
297
298        let mut hasher = FileHasher::new(dir.path().to_path_buf());
299        hasher.buffer_size = 8192;
300        let duplicates = hasher.find_duplicates()?;
301
302        assert_eq!(duplicates.len(), 1);
303        let group = &duplicates[0];
304        assert_eq!(group.paths.len(), 2);
305        assert_eq!(group.size, 12); // "same content" is 12 bytes
306
307        assert!(group.paths.contains(&file1_path));
308        assert!(group.paths.contains(&file2_path));
309
310        Ok(())
311    }
312}