Skip to main content

cleaner_core/tree/
mod.rs

1//! Directory tree with MAXIMUM PERFORMANCE single-pass scan
2//! Single WalkDir, no duplicate syscalls, O(n) everywhere
3
4mod builder;
5mod entry;
6mod progress;
7mod sizing;
8mod sort;
9
10#[cfg(test)]
11mod tests;
12
13pub use entry::DirEntry;
14pub use progress::ScanProgress;
15pub use sort::{sort_by_name, sort_by_size};
16
17use foldhash::{HashMap, HashMapExt};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21#[derive(Clone)]
22pub struct DirTree {
23    pub children: HashMap<PathBuf, Arc<Vec<DirEntry>>>,
24    sort_modes: HashMap<PathBuf, bool>,
25}
26
27impl DirTree {
28    pub fn from_children(children: HashMap<PathBuf, Vec<DirEntry>>) -> Self {
29        let children = children
30            .into_iter()
31            .map(|(path, entries)| (path, Arc::new(entries)))
32            .collect();
33        Self {
34            children,
35            sort_modes: HashMap::new(),
36        }
37    }
38
39    pub fn from_shared_children(children: HashMap<PathBuf, Arc<Vec<DirEntry>>>) -> Self {
40        Self {
41            children,
42            sort_modes: HashMap::new(),
43        }
44    }
45
46    pub fn get_children(&mut self, path: &Path, by_name: bool) -> Arc<Vec<DirEntry>> {
47        if self.sort_modes.get(path).copied() != Some(by_name) {
48            if let Some(entries) = self.children.get_mut(path) {
49                let entries = Arc::make_mut(entries);
50                if by_name {
51                    sort_by_name(entries);
52                } else {
53                    sort_by_size(entries);
54                }
55                self.sort_modes.insert(path.to_path_buf(), by_name);
56            }
57        }
58        self.children
59            .get(path)
60            .cloned()
61            .unwrap_or_else(|| Arc::new(Vec::new()))
62    }
63
64    /// Remove entry from the tree and update all parent sizes (O(depth))
65    pub fn delete_entry(&mut self, path: &PathBuf, is_dir: bool) {
66        if let Some(parent) = path.parent() {
67            let parent_buf = parent.to_path_buf();
68
69            // 1. Remove from parent's children list
70            if let Some(entries) = self.children.get_mut(&parent_buf) {
71                let entries = Arc::make_mut(entries);
72                if let Some(idx) = entries
73                    .iter()
74                    .position(|entry| Some(entry.name.as_os_str()) == path.file_name())
75                {
76                    let removed = entries.remove(idx);
77                    let size_removed = removed.size;
78
79                    // Manual deletion is rare relative to tree construction, so
80                    // avoid an eager full-path index on every scan.
81                    let mut current_parent = parent_buf;
82                    while let Some(grandparent) = current_parent.parent() {
83                        let grandparent = grandparent.to_path_buf();
84                        if let Some(entries) = self.children.get_mut(&grandparent) {
85                            if let Some(parent_entry) =
86                                Arc::make_mut(entries).iter_mut().find(|entry| {
87                                    Some(entry.name.as_os_str()) == current_parent.file_name()
88                                })
89                            {
90                                parent_entry.size = parent_entry.size.saturating_sub(size_removed);
91                            }
92                        }
93                        current_parent = grandparent;
94                    }
95                }
96            }
97        }
98
99        // 3. If directory, remove its children entry mapping (optional cleanup)
100        if is_dir {
101            self.children
102                .retain(|candidate, _| !candidate.starts_with(path));
103            self.sort_modes
104                .retain(|candidate, _| !candidate.starts_with(path));
105        }
106    }
107
108    pub fn get_temp_stats(&self, dir: &Path) -> (usize, usize, u64) {
109        let mut totals = (0usize, 0usize, 0u64);
110        let mut stack = vec![dir.to_path_buf()];
111        while let Some(path) = stack.pop() {
112            if let Some(entries) = self.children.get(&path) {
113                for entry in entries.iter().filter(|entry| entry.name != "..") {
114                    if entry.is_temp {
115                        if entry.is_dir {
116                            totals.0 = totals.0.saturating_add(1);
117                        } else {
118                            totals.1 = totals.1.saturating_add(1);
119                        }
120                        totals.2 = totals.2.saturating_add(entry.size);
121                    } else if entry.is_dir {
122                        stack.push(path.join(&entry.name));
123                    }
124                }
125            }
126        }
127        totals
128    }
129}