Skip to main content

rusty_sweeper/scanner/
entry.rs

1use serde::Serialize;
2use std::path::PathBuf;
3use std::time::SystemTime;
4
5/// Represents a file or directory with its metadata and size information.
6/// This is the core data structure for the disk scanner.
7#[derive(Debug, Clone, Serialize)]
8pub struct DirEntry {
9    /// Full path to the file or directory
10    pub path: PathBuf,
11
12    /// Entry name (last component of path)
13    pub name: String,
14
15    /// True if this is a directory
16    pub is_dir: bool,
17
18    /// Apparent size in bytes (sum of file sizes)
19    pub size: u64,
20
21    /// Actual disk usage in bytes (accounting for block size)
22    pub disk_usage: u64,
23
24    /// Number of files (1 for files, recursive count for dirs)
25    pub file_count: u64,
26
27    /// Number of subdirectories (recursive)
28    pub dir_count: u64,
29
30    /// Last modification time
31    pub mtime: Option<SystemTime>,
32
33    /// Child entries (empty for files)
34    pub children: Vec<DirEntry>,
35
36    /// Error message if we couldn't read this entry (permission denied, etc.)
37    pub error: Option<String>,
38}
39
40impl DirEntry {
41    /// Clone this entry's display metadata without recursively cloning children.
42    pub fn shallow_clone(&self) -> Self {
43        Self {
44            path: self.path.clone(),
45            name: self.name.clone(),
46            is_dir: self.is_dir,
47            size: self.size,
48            disk_usage: self.disk_usage,
49            file_count: self.file_count,
50            dir_count: self.dir_count,
51            mtime: self.mtime,
52            children: Vec::new(),
53            error: self.error.clone(),
54        }
55    }
56
57    /// Create a new file entry from metadata
58    pub fn new_file(path: PathBuf, size: u64, disk_usage: u64, mtime: Option<SystemTime>) -> Self {
59        let name = path
60            .file_name()
61            .map(|n| n.to_string_lossy().to_string())
62            .unwrap_or_default();
63
64        Self {
65            path,
66            name,
67            is_dir: false,
68            size,
69            disk_usage,
70            file_count: 1,
71            dir_count: 0,
72            mtime,
73            children: vec![],
74            error: None,
75        }
76    }
77
78    /// Create a new directory entry (children added later)
79    pub fn new_dir(path: PathBuf, mtime: Option<SystemTime>) -> Self {
80        let name = path
81            .file_name()
82            .map(|n| n.to_string_lossy().to_string())
83            .unwrap_or_else(|| path.to_string_lossy().to_string());
84
85        Self {
86            path,
87            name,
88            is_dir: true,
89            size: 0,
90            disk_usage: 0,
91            file_count: 0,
92            dir_count: 0,
93            mtime,
94            children: vec![],
95            error: None,
96        }
97    }
98
99    /// Create an error entry for inaccessible paths
100    pub fn new_error(path: PathBuf, error: String) -> Self {
101        let name = path
102            .file_name()
103            .map(|n| n.to_string_lossy().to_string())
104            .unwrap_or_default();
105
106        Self {
107            path,
108            name,
109            is_dir: false,
110            size: 0,
111            disk_usage: 0,
112            file_count: 0,
113            dir_count: 0,
114            mtime: None,
115            children: vec![],
116            error: Some(error),
117        }
118    }
119
120    /// Recalculate size totals from children
121    pub fn recalculate_totals(&mut self) {
122        if !self.is_dir {
123            return;
124        }
125
126        self.size = 0;
127        self.disk_usage = 0;
128        self.file_count = 0;
129        self.dir_count = 0;
130
131        for child in &self.children {
132            self.size += child.size;
133            self.disk_usage += child.disk_usage;
134            self.file_count += child.file_count;
135            if child.is_dir {
136                self.dir_count += 1 + child.dir_count;
137            }
138        }
139    }
140
141    /// Sort children by size (largest first)
142    pub fn sort_by_size(&mut self) {
143        self.children.sort_by(|a, b| b.size.cmp(&a.size));
144        for child in &mut self.children {
145            child.sort_by_size();
146        }
147    }
148
149    /// Sort children by name (alphabetical)
150    pub fn sort_by_name(&mut self) {
151        self.children.sort_by(|a, b| a.name.cmp(&b.name));
152        for child in &mut self.children {
153            child.sort_by_name();
154        }
155    }
156
157    /// Get total entry count (self + all descendants)
158    pub fn total_entries(&self) -> u64 {
159        self.file_count + self.dir_count + if self.is_dir { 1 } else { 0 }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn test_dir_entry_creation() {
169        let entry = DirEntry {
170            path: PathBuf::from("/test"),
171            name: "test".to_string(),
172            is_dir: true,
173            size: 1024,
174            disk_usage: 4096,
175            file_count: 5,
176            dir_count: 2,
177            mtime: None,
178            children: vec![],
179            error: None,
180        };
181        assert!(entry.is_dir);
182        assert_eq!(entry.size, 1024);
183        assert_eq!(entry.name, "test");
184        assert_eq!(entry.file_count, 5);
185        assert_eq!(entry.dir_count, 2);
186    }
187
188    #[test]
189    fn test_dir_entry_with_error() {
190        let entry = DirEntry {
191            path: PathBuf::from("/forbidden"),
192            name: "forbidden".to_string(),
193            is_dir: true,
194            size: 0,
195            disk_usage: 0,
196            file_count: 0,
197            dir_count: 0,
198            mtime: None,
199            children: vec![],
200            error: Some("Permission denied".to_string()),
201        };
202        assert!(entry.error.is_some());
203        assert_eq!(entry.error.as_ref().unwrap(), "Permission denied");
204    }
205
206    #[test]
207    fn test_new_file() {
208        let entry = DirEntry::new_file(PathBuf::from("/parent/file.txt"), 1024, 4096, None);
209        assert!(!entry.is_dir);
210        assert_eq!(entry.name, "file.txt");
211        assert_eq!(entry.size, 1024);
212        assert_eq!(entry.disk_usage, 4096);
213        assert_eq!(entry.file_count, 1);
214        assert_eq!(entry.dir_count, 0);
215    }
216
217    #[test]
218    fn test_new_dir() {
219        let entry = DirEntry::new_dir(PathBuf::from("/parent/subdir"), None);
220        assert!(entry.is_dir);
221        assert_eq!(entry.name, "subdir");
222        assert_eq!(entry.size, 0);
223        assert_eq!(entry.file_count, 0);
224    }
225
226    #[test]
227    fn test_new_dir_root_path() {
228        let entry = DirEntry::new_dir(PathBuf::from("/"), None);
229        assert!(entry.is_dir);
230        assert_eq!(entry.name, "/");
231    }
232
233    #[test]
234    fn test_new_error() {
235        let entry = DirEntry::new_error(
236            PathBuf::from("/forbidden/file"),
237            "Permission denied".to_string(),
238        );
239        assert!(entry.error.is_some());
240        assert_eq!(entry.name, "file");
241        assert_eq!(entry.size, 0);
242    }
243
244    #[test]
245    fn test_recalculate_totals() {
246        let mut parent = DirEntry::new_dir(PathBuf::from("/parent"), None);
247        parent.children.push(DirEntry::new_file(
248            PathBuf::from("/parent/file1.txt"),
249            100,
250            4096,
251            None,
252        ));
253        parent.children.push(DirEntry::new_file(
254            PathBuf::from("/parent/file2.txt"),
255            200,
256            4096,
257            None,
258        ));
259
260        parent.recalculate_totals();
261
262        assert_eq!(parent.size, 300);
263        assert_eq!(parent.disk_usage, 8192);
264        assert_eq!(parent.file_count, 2);
265    }
266
267    #[test]
268    fn test_recalculate_totals_with_subdirs() {
269        let mut parent = DirEntry::new_dir(PathBuf::from("/parent"), None);
270
271        let mut subdir = DirEntry::new_dir(PathBuf::from("/parent/subdir"), None);
272        subdir.children.push(DirEntry::new_file(
273            PathBuf::from("/parent/subdir/nested.txt"),
274            500,
275            4096,
276            None,
277        ));
278        subdir.recalculate_totals();
279
280        parent.children.push(subdir);
281        parent.children.push(DirEntry::new_file(
282            PathBuf::from("/parent/file.txt"),
283            100,
284            4096,
285            None,
286        ));
287        parent.recalculate_totals();
288
289        assert_eq!(parent.size, 600);
290        assert_eq!(parent.file_count, 2);
291        assert_eq!(parent.dir_count, 1);
292    }
293
294    #[test]
295    fn test_sort_by_size() {
296        let mut parent = DirEntry::new_dir(PathBuf::from("/parent"), None);
297        parent.children.push(DirEntry::new_file(
298            PathBuf::from("/parent/small.txt"),
299            100,
300            4096,
301            None,
302        ));
303        parent.children.push(DirEntry::new_file(
304            PathBuf::from("/parent/large.txt"),
305            1000,
306            4096,
307            None,
308        ));
309        parent.children.push(DirEntry::new_file(
310            PathBuf::from("/parent/medium.txt"),
311            500,
312            4096,
313            None,
314        ));
315
316        parent.sort_by_size();
317
318        assert_eq!(parent.children[0].name, "large.txt");
319        assert_eq!(parent.children[1].name, "medium.txt");
320        assert_eq!(parent.children[2].name, "small.txt");
321    }
322
323    #[test]
324    fn test_sort_by_name() {
325        let mut parent = DirEntry::new_dir(PathBuf::from("/parent"), None);
326        parent.children.push(DirEntry::new_file(
327            PathBuf::from("/parent/charlie.txt"),
328            100,
329            4096,
330            None,
331        ));
332        parent.children.push(DirEntry::new_file(
333            PathBuf::from("/parent/alpha.txt"),
334            100,
335            4096,
336            None,
337        ));
338        parent.children.push(DirEntry::new_file(
339            PathBuf::from("/parent/bravo.txt"),
340            100,
341            4096,
342            None,
343        ));
344
345        parent.sort_by_name();
346
347        assert_eq!(parent.children[0].name, "alpha.txt");
348        assert_eq!(parent.children[1].name, "bravo.txt");
349        assert_eq!(parent.children[2].name, "charlie.txt");
350    }
351
352    #[test]
353    fn test_total_entries() {
354        let mut parent = DirEntry::new_dir(PathBuf::from("/parent"), None);
355        parent.file_count = 5;
356        parent.dir_count = 2;
357
358        assert_eq!(parent.total_entries(), 8); // 5 files + 2 dirs + 1 (self)
359    }
360
361    #[test]
362    fn test_total_entries_file() {
363        let file = DirEntry::new_file(PathBuf::from("/file.txt"), 100, 4096, None);
364        assert_eq!(file.total_entries(), 1); // Just the file itself
365    }
366}