Skip to main content

rusty_sweeper/scanner/
formatter.rs

1use super::entry::DirEntry;
2use super::size::format_size;
3
4/// Format options for tree output
5#[derive(Debug, Clone)]
6pub struct FormatOptions {
7    /// Maximum depth to display
8    pub max_depth: Option<usize>,
9    /// Show only top N entries per directory
10    pub top_n: Option<usize>,
11    /// Use colors in output
12    pub colors: bool,
13    /// Show file counts
14    pub show_counts: bool,
15}
16
17impl Default for FormatOptions {
18    fn default() -> Self {
19        Self {
20            max_depth: Some(3),
21            top_n: Some(20),
22            colors: true,
23            show_counts: false,
24        }
25    }
26}
27
28impl FormatOptions {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn with_max_depth(mut self, depth: usize) -> Self {
34        self.max_depth = Some(depth);
35        self
36    }
37
38    pub fn with_top_n(mut self, n: usize) -> Self {
39        self.top_n = Some(n);
40        self
41    }
42
43    pub fn with_colors(mut self, enabled: bool) -> Self {
44        self.colors = enabled;
45        self
46    }
47
48    pub fn with_counts(mut self, show: bool) -> Self {
49        self.show_counts = show;
50        self
51    }
52
53    pub fn unlimited() -> Self {
54        Self {
55            max_depth: None,
56            top_n: None,
57            colors: false,
58            show_counts: false,
59        }
60    }
61}
62
63/// Format entry as a tree string
64pub fn format_tree(entry: &DirEntry, options: &FormatOptions) -> String {
65    let mut output = String::new();
66    format_tree_recursive(entry, &mut output, "", true, 0, options);
67    output
68}
69
70fn format_tree_recursive(
71    entry: &DirEntry,
72    output: &mut String,
73    prefix: &str,
74    is_last: bool,
75    depth: usize,
76    options: &FormatOptions,
77) {
78    // Check depth limit
79    if let Some(max_depth) = options.max_depth {
80        if depth > max_depth {
81            return;
82        }
83    }
84
85    // Build the current line
86    let connector = if depth == 0 {
87        ""
88    } else if is_last {
89        "└── "
90    } else {
91        "├── "
92    };
93
94    let size_str = format_size(entry.size);
95    let name = if entry.is_dir {
96        format!("{}/", entry.name)
97    } else {
98        entry.name.clone()
99    };
100
101    // Error indicator
102    let error_indicator = if entry.error.is_some() { " [!]" } else { "" };
103
104    // Count indicator
105    let count_str = if options.show_counts && entry.is_dir {
106        format!(" ({} files)", entry.file_count)
107    } else {
108        String::new()
109    };
110
111    output.push_str(&format!(
112        "{}{}{:>10}  {}{}{}\n",
113        prefix, connector, size_str, name, count_str, error_indicator
114    ));
115
116    // Process children
117    if entry.is_dir && !entry.children.is_empty() {
118        let new_prefix = if depth == 0 {
119            String::new()
120        } else if is_last {
121            format!("{}    ", prefix)
122        } else {
123            format!("{}│   ", prefix)
124        };
125
126        let children_to_show: Vec<_> = if let Some(top_n) = options.top_n {
127            entry.children.iter().take(top_n).collect()
128        } else {
129            entry.children.iter().collect()
130        };
131
132        let total = children_to_show.len();
133        let has_more = options.top_n.is_some_and(|n| entry.children.len() > n);
134
135        for (i, child) in children_to_show.iter().enumerate() {
136            let is_last_child = i == total - 1 && !has_more;
137            format_tree_recursive(
138                child,
139                output,
140                &new_prefix,
141                is_last_child,
142                depth + 1,
143                options,
144            );
145        }
146
147        // Show truncation indicator if needed
148        if has_more {
149            let remaining = entry.children.len() - options.top_n.unwrap();
150            output.push_str(&format!(
151                "{}└── ... and {} more entries\n",
152                new_prefix, remaining
153            ));
154        }
155    }
156}
157
158/// Format entry as a simple table
159pub fn format_table(entry: &DirEntry, options: &FormatOptions) -> String {
160    let mut output = String::new();
161
162    output.push_str(&format!("{:>12}  {}\n", "SIZE", "PATH"));
163    output.push_str(&format!("{:->12}  {:-<50}\n", "", ""));
164
165    format_table_recursive(entry, &mut output, 0, options);
166
167    output
168}
169
170fn format_table_recursive(
171    entry: &DirEntry,
172    output: &mut String,
173    depth: usize,
174    options: &FormatOptions,
175) {
176    if let Some(max_depth) = options.max_depth {
177        if depth > max_depth {
178            return;
179        }
180    }
181
182    let size_str = format_size(entry.size);
183    let indent = "  ".repeat(depth);
184
185    output.push_str(&format!("{:>12}  {}{}\n", size_str, indent, entry.name));
186
187    let children_to_show: Vec<_> = if let Some(top_n) = options.top_n {
188        entry.children.iter().take(top_n).collect()
189    } else {
190        entry.children.iter().collect()
191    };
192
193    for child in children_to_show {
194        format_table_recursive(child, output, depth + 1, options);
195    }
196
197    // Show truncation indicator if needed
198    if let Some(top_n) = options.top_n {
199        if entry.children.len() > top_n {
200            let remaining = entry.children.len() - top_n;
201            let indent = "  ".repeat(depth + 1);
202            output.push_str(&format!("{:>12}  {}... {} more\n", "", indent, remaining));
203        }
204    }
205}
206
207/// Format entry as JSON
208pub fn format_json(entry: &DirEntry, pretty: bool) -> Result<String, serde_json::Error> {
209    if pretty {
210        serde_json::to_string_pretty(entry)
211    } else {
212        serde_json::to_string(entry)
213    }
214}
215
216/// Simplified JSON structure for large outputs
217#[derive(serde::Serialize)]
218pub struct SummarizedEntry {
219    pub path: String,
220    pub size: u64,
221    pub size_human: String,
222    pub file_count: u64,
223    pub dir_count: u64,
224    pub children: Vec<SummarizedEntry>,
225}
226
227impl From<&DirEntry> for SummarizedEntry {
228    fn from(entry: &DirEntry) -> Self {
229        Self {
230            path: entry.path.to_string_lossy().to_string(),
231            size: entry.size,
232            size_human: format_size(entry.size),
233            file_count: entry.file_count,
234            dir_count: entry.dir_count,
235            children: entry.children.iter().map(SummarizedEntry::from).collect(),
236        }
237    }
238}
239
240/// Format as summarized JSON (smaller output)
241pub fn format_json_summary(entry: &DirEntry, pretty: bool) -> Result<String, serde_json::Error> {
242    let summary = SummarizedEntry::from(entry);
243    if pretty {
244        serde_json::to_string_pretty(&summary)
245    } else {
246        serde_json::to_string(&summary)
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use std::path::PathBuf;
254
255    fn create_test_entry() -> DirEntry {
256        let mut root = DirEntry::new_dir(PathBuf::from("/test"), None);
257
258        let mut subdir = DirEntry::new_dir(PathBuf::from("/test/subdir"), None);
259        subdir.children.push(DirEntry::new_file(
260            PathBuf::from("/test/subdir/file.txt"),
261            1024,
262            4096,
263            None,
264        ));
265        subdir.recalculate_totals();
266
267        root.children.push(DirEntry::new_file(
268            PathBuf::from("/test/large.bin"),
269            1048576,
270            1048576,
271            None,
272        ));
273        root.children.push(subdir);
274        root.recalculate_totals();
275        root.sort_by_size();
276
277        root
278    }
279
280    #[test]
281    fn test_format_tree_basic() {
282        let entry = create_test_entry();
283        let options = FormatOptions::default();
284        let output = format_tree(&entry, &options);
285
286        assert!(output.contains("test/"));
287        assert!(output.contains("large.bin"));
288        assert!(output.contains("subdir/"));
289        assert!(output.contains("1.00 MB")); // large.bin
290    }
291
292    #[test]
293    fn test_format_tree_contains_structure() {
294        let entry = create_test_entry();
295        let options = FormatOptions::unlimited();
296        let output = format_tree(&entry, &options);
297
298        // Should have tree characters
299        assert!(output.contains("├──") || output.contains("└──"));
300    }
301
302    #[test]
303    fn test_format_tree_depth_limit() {
304        let entry = create_test_entry();
305        let options = FormatOptions {
306            max_depth: Some(1),
307            ..Default::default()
308        };
309        let output = format_tree(&entry, &options);
310
311        // Should show root and immediate children, but not nested file
312        assert!(output.contains("subdir/"));
313        assert!(!output.contains("file.txt"));
314    }
315
316    #[test]
317    fn test_format_tree_with_counts() {
318        let entry = create_test_entry();
319        let options = FormatOptions::new().with_counts(true);
320        let output = format_tree(&entry, &options);
321
322        assert!(output.contains("files)"));
323    }
324
325    #[test]
326    fn test_format_tree_top_n() {
327        let mut root = DirEntry::new_dir(PathBuf::from("/test"), None);
328        for i in 0..10 {
329            root.children.push(DirEntry::new_file(
330                PathBuf::from(format!("/test/file{}.txt", i)),
331                1000 * (10 - i as u64),
332                4096,
333                None,
334            ));
335        }
336        root.recalculate_totals();
337        root.sort_by_size();
338
339        let options = FormatOptions::new().with_top_n(3);
340        let output = format_tree(&root, &options);
341
342        assert!(output.contains("file0.txt")); // largest
343        assert!(output.contains("file1.txt"));
344        assert!(output.contains("file2.txt"));
345        assert!(!output.contains("file9.txt")); // smallest, truncated
346        assert!(output.contains("7 more entries"));
347    }
348
349    #[test]
350    fn test_format_tree_error_entry() {
351        let mut root = DirEntry::new_dir(PathBuf::from("/test"), None);
352        root.children.push(DirEntry::new_error(
353            PathBuf::from("/test/forbidden"),
354            "Permission denied".to_string(),
355        ));
356        root.recalculate_totals();
357
358        let options = FormatOptions::default();
359        let output = format_tree(&root, &options);
360
361        assert!(output.contains("[!]"));
362    }
363
364    #[test]
365    fn test_format_table_basic() {
366        let entry = create_test_entry();
367        let options = FormatOptions::default();
368        let output = format_table(&entry, &options);
369
370        assert!(output.contains("SIZE"));
371        assert!(output.contains("PATH"));
372        assert!(output.contains("1.00 MB"));
373        assert!(output.contains("test"));
374    }
375
376    #[test]
377    fn test_format_table_indentation() {
378        let entry = create_test_entry();
379        let options = FormatOptions::unlimited();
380        let output = format_table(&entry, &options);
381
382        // Check that nested entries are indented
383        let lines: Vec<&str> = output.lines().collect();
384        // subdir should have more indentation than root
385        let subdir_line = lines.iter().find(|l| l.contains("subdir")).unwrap();
386        let root_line = lines
387            .iter()
388            .find(|l| l.contains("test") && !l.contains("subdir"))
389            .unwrap();
390
391        // subdir should appear after more spaces than root name
392        assert!(subdir_line.find("subdir").unwrap() > root_line.find("test").unwrap());
393    }
394
395    #[test]
396    fn test_format_json() {
397        let entry = create_test_entry();
398        let json = format_json(&entry, false).unwrap();
399
400        assert!(json.contains("\"path\""));
401        assert!(json.contains("\"size\""));
402        assert!(json.contains("\"children\""));
403    }
404
405    #[test]
406    fn test_format_json_pretty() {
407        let entry = create_test_entry();
408        let json = format_json(&entry, true).unwrap();
409
410        // Pretty JSON should have newlines
411        assert!(json.contains('\n'));
412    }
413
414    #[test]
415    fn test_format_json_summary() {
416        let entry = create_test_entry();
417        let json = format_json_summary(&entry, false).unwrap();
418
419        assert!(json.contains("size_human"));
420        assert!(json.contains("1.00 MB") || json.contains("1 MB"));
421    }
422
423    #[test]
424    fn test_format_json_summary_structure() {
425        let entry = create_test_entry();
426        let json = format_json_summary(&entry, true).unwrap();
427
428        // Should have the expected fields
429        assert!(json.contains("\"path\""));
430        assert!(json.contains("\"size\""));
431        assert!(json.contains("\"size_human\""));
432        assert!(json.contains("\"file_count\""));
433        assert!(json.contains("\"dir_count\""));
434        assert!(json.contains("\"children\""));
435    }
436
437    #[test]
438    fn test_format_json_parseable() {
439        let entry = create_test_entry();
440        let json = format_json(&entry, false).unwrap();
441
442        // Verify it's valid JSON by parsing it
443        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
444        assert!(parsed.is_object());
445        assert!(parsed["path"].is_string());
446        assert!(parsed["size"].is_number());
447    }
448}