Remove empty ancestor directories after file removal. Given an iterator of relative paths that were just deleted, this collects every parent directory, sorts them deepest-first, and attempts `std::fs::remove_dir` on each. Because `remove_dir` only succeeds on *empty* directories, this is always safe — a directory that still contains files (tracked, untracked, or otherwise) will simply fail silen
(root: &Path, removed_paths: impl Iterator<Item = &'a str>)
| 33 | /// orchestration level and makes the cleanup logic reusable for other |
| 34 | /// operations (e.g. `atomic clean`). |
| 35 | fn cleanup_empty_ancestors<'a>(root: &Path, removed_paths: impl Iterator<Item = &'a str>) { |
| 36 | let mut dirs: HashSet<PathBuf> = HashSet::new(); |
| 37 | for path in removed_paths { |
| 38 | let p = PathBuf::from(path); |
| 39 | let mut ancestor = p.parent(); |
| 40 | while let Some(dir) = ancestor { |
| 41 | if dir == Path::new("") || dir == Path::new(".") { |
| 42 | break; |
| 43 | } |
| 44 | dirs.insert(dir.to_path_buf()); |
| 45 | ancestor = dir.parent(); |
| 46 | } |
| 47 | } |
| 48 | // Sort deepest-first so children are removed before parents. |
| 49 | let mut sorted: Vec<PathBuf> = dirs.into_iter().collect(); |
| 50 | sorted.sort_by_key(|a| std::cmp::Reverse(a.components().count())); |
| 51 | for dir in sorted { |
| 52 | let abs = root.join(&dir); |
| 53 | if abs.is_dir() { |
| 54 | // Only succeeds if the directory is empty — safe by construction. |
| 55 | let _ = std::fs::remove_dir(&abs); |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl Repository { |
| 61 | /// Switch to a different view and update the working copy. |