maram 0.2.0

A modern, high-performance alternative to the Unix tree command
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Output formatting and visualization
//!
//! This module handles all output formatting including tree visualization,
//! JSON/CSV export, and beautiful size distribution charts.

use crate::{Args, Config, Result, TreeEntry, TreeStats};
use clap::ValueEnum;
use colored::*;
use serde_json;
use std::collections::HashMap;
use std::io::{self, Write};
use std::path::Path;

/// Output format options
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    /// Tree visualization (default)
    Tree,
    /// JSON output
    Json,
    /// CSV output
    Csv,
    /// Plain text list
    Plain,
}

/// Size distribution types
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum DistributionType {
    /// Distribution by file type
    Type,
    /// Distribution by size buckets
    Size,
    /// Distribution by file extension
    Ext,
}

/// Distribution output format
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum DistributionFormat {
    /// Table format
    Table,
    /// Bar chart format
    Chart,
}

/// Options for formatting output
#[derive(Debug, Clone)]
pub struct FormatOptions {
    /// Use Unicode characters for tree
    pub unicode: bool,
    /// Use colored output
    pub color: bool,
    /// Show full paths
    pub full_path: bool,
    /// Show file sizes
    pub show_size: bool,
    /// Show line counts
    pub show_lines: bool,
    /// Show directory sizes
    pub dir_sizes: bool,
}

impl FormatOptions {
    /// Create format options from args and config
    pub fn from_args_and_config(args: &Args, config: &Config) -> Self {
        let color = if args.no_color {
            false
        } else if args.color {
            true
        } else {
            // Auto-detect based on terminal
            atty::is(atty::Stream::Stdout) && std::env::var("NO_COLOR").is_err()
        };

        Self {
            unicode: args.unicode || config.display.unicode,
            color,
            full_path: args.full_path,
            show_size: args.show_size,
            show_lines: args.show_lines,
            dir_sizes: args.dir_sizes,
        }
    }
}

/// Tree drawing characters
struct TreeChars {
    down: &'static str,
    down_right: &'static str,
    last: &'static str,
}

impl TreeChars {
    fn new(unicode: bool) -> Self {
        // Currently the same characters are used for both modes.
        // Keep a single branch to satisfy clippy::if_same_then_else.
        let _ = unicode; // placeholder for potential ASCII alternative in the future
        Self { down: "", down_right: "├── ", last: "└── " }
    }
}

/// Print tree visualization
pub fn print_tree(entries: &[TreeEntry], opts: &FormatOptions) -> Result<()> {
    let mut stdout = io::stdout();
    write_tree(&mut stdout, entries, opts)
}

/// Write tree visualization to a writer
pub fn write_tree(out: &mut dyn Write, entries: &[TreeEntry], opts: &FormatOptions) -> Result<()> {
    let chars = TreeChars::new(opts.unicode);
    for (i, entry) in entries.iter().enumerate() {
        print_tree_entry(out, entry, &chars, opts, Vec::new(), i == entries.len() - 1)?;
    }
    // Summary
    let stats = TreeStats::from_entries(entries);
    writeln!(out)?;
    writeln!(
        out,
        "{} {}, {} {}",
        stats.dir_count,
        if stats.dir_count == 1 {
            "directory"
        } else {
            "directories"
        },
        stats.file_count,
        if stats.file_count == 1 {
            "file"
        } else {
            "files"
        }
    )?;
    Ok(())
}

/// Print a single tree entry recursively
fn print_tree_entry(
    out: &mut dyn Write,
    entry: &TreeEntry,
    chars: &TreeChars,
    opts: &FormatOptions,
    prefix: Vec<bool>,
    is_last: bool,
) -> Result<()> {
    // Print prefix
    for &cont in &prefix {
        write!(out, "{}", if cont { chars.down } else { "    " })?;
    }

    // Print connector
    write!(
        out,
        "{}",
        if is_last {
            chars.last
        } else {
            chars.down_right
        }
    )?;

    // Format name with color
    let name = if opts.color {
        if entry.is_dir {
            entry.name.blue().bold().to_string()
        } else if entry.is_symlink {
            entry.name.cyan().to_string()
        } else if entry.is_executable {
            entry.name.green().to_string()
        } else {
            entry.name.clone()
        }
    } else {
        entry.name.clone()
    };

    // Add details
    let mut details = Vec::new();

    if opts.show_size && (!entry.is_dir || opts.dir_sizes) {
        details.push(format_size(entry.size));
    }

    if opts.show_lines && entry.line_count > 0 {
        details.push(format!("{} lines", entry.line_count));
    }

    // Print entry
    if details.is_empty() {
        writeln!(out, "{}", name)?;
    } else {
        let detail_str = if opts.color {
            format!(" ({})", details.join(", ")).dimmed().to_string()
        } else {
            format!(" ({})", details.join(", "))
        };
        writeln!(out, "{}{}", name, detail_str)?;
    }

    // Print children
    if !entry.children.is_empty() {
        let mut new_prefix = prefix;
        new_prefix.push(!is_last);

        for (i, child) in entry.children.iter().enumerate() {
            print_tree_entry(
                out,
                child,
                chars,
                opts,
                new_prefix.clone(),
                i == entry.children.len() - 1,
            )?;
        }
    }

    Ok(())
}

/// Print JSON output
pub fn print_json(entries: &[TreeEntry]) -> Result<()> {
    let mut stdout = io::stdout();
    write_json(&mut stdout, entries)
}

/// Write JSON output to a writer
pub fn write_json(out: &mut dyn Write, entries: &[TreeEntry]) -> Result<()> {
    let json = serde_json::to_string_pretty(entries)?;
    writeln!(out, "{}", json)?;
    Ok(())
}

/// Print CSV output
pub fn print_csv(entries: &[TreeEntry]) -> Result<()> {
    let mut stdout = io::stdout();
    write_csv(&mut stdout, entries)
}

/// Write CSV output to a writer
pub fn write_csv(out: &mut dyn Write, entries: &[TreeEntry]) -> Result<()> {
    writeln!(out, "path,type,size,lines,modified")?;

    fn write_csv_entry(out: &mut dyn Write, entry: &TreeEntry, parent_path: &str) -> Result<()> {
        let path = if parent_path.is_empty() {
            entry.name.clone()
        } else {
            format!("{}/{}", parent_path, entry.name)
        };

        let entry_type = if entry.is_dir { "directory" } else { "file" };
        let modified = entry
            .modified
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        writeln!(
            out,
            "{},{},{},{},{}",
            path, entry_type, entry.size, entry.line_count, modified
        )?;

        for child in &entry.children {
            write_csv_entry(out, child, &path)?;
        }

        Ok(())
    }

    for entry in entries {
        write_csv_entry(out, entry, "")?;
    }

    Ok(())
}

/// Print plain text output
pub fn print_plain(entries: &[TreeEntry]) -> Result<()> {
    let mut stdout = io::stdout();
    write_plain(&mut stdout, entries)
}

/// Write plain text output to a writer
pub fn write_plain(out: &mut dyn Write, entries: &[TreeEntry]) -> Result<()> {
    fn write_plain_entry(out: &mut dyn Write, entry: &TreeEntry, depth: usize) -> Result<()> {
        writeln!(out, "{}{}", "  ".repeat(depth), entry.name)?;
        for child in &entry.children {
            write_plain_entry(out, child, depth + 1)?;
        }
        Ok(())
    }
    for entry in entries {
        write_plain_entry(out, entry, 0)?;
    }
    Ok(())
}

/// Print total size summary
pub fn print_total_size(stats: &TreeStats, opts: &FormatOptions) -> Result<()> {
    let mut stdout = io::stdout();
    write_total_size(&mut stdout, stats, opts)
}

/// Write total size summary to a writer
pub fn write_total_size(
    out: &mut dyn Write,
    stats: &TreeStats,
    opts: &FormatOptions,
) -> Result<()> {
    let total_str = format!(
        "\nTotal: {} ({} files: {}, {} directories: {})",
        format_size(stats.total_size),
        stats.file_count,
        format_size(stats.file_size),
        stats.dir_count,
        format_size(stats.dir_size),
    );
    if opts.color {
        writeln!(out, "{}", total_str.bright_yellow().bold())?;
    } else {
        writeln!(out, "{}", total_str)?;
    }
    Ok(())
}

/// Print size distribution
pub fn print_distribution(
    entries: &[TreeEntry],
    dist_type: &DistributionType,
    top: usize,
    format: &DistributionFormat,
    opts: &FormatOptions,
) -> Result<()> {
    let mut stdout = io::stdout();
    write_distribution(&mut stdout, entries, dist_type, top, format, opts)
}

/// Write size distribution to a writer
pub fn write_distribution(
    out: &mut dyn Write,
    entries: &[TreeEntry],
    dist_type: &DistributionType,
    top: usize,
    format: &DistributionFormat,
    opts: &FormatOptions,
) -> Result<()> {
    let distribution = calculate_distribution(entries, dist_type);
    let mut sorted: Vec<_> = distribution.into_iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1));
    sorted.truncate(top);
    let total: u64 = sorted.iter().map(|(_, size)| size).sum();
    match format {
        DistributionFormat::Table => write_distribution_table(out, &sorted, total, opts),
        DistributionFormat::Chart => write_distribution_chart(out, &sorted, total, opts),
    }
}

/// Calculate size distribution
fn calculate_distribution(
    entries: &[TreeEntry],
    dist_type: &DistributionType,
) -> HashMap<String, u64> {
    let mut dist = HashMap::new();

    fn process_entry(
        entry: &TreeEntry,
        dist: &mut HashMap<String, u64>,
        dist_type: &DistributionType,
    ) {
        if !entry.is_dir {
            let key = match dist_type {
                DistributionType::Type => {
                    // Determine file type by extension
                    let ext = Path::new(&entry.name)
                        .extension()
                        .and_then(|s| s.to_str())
                        .unwrap_or("no extension");

                    match ext.to_lowercase().as_str() {
                        "jpg" | "jpeg" | "png" | "gif" | "bmp" | "svg" => "Images",
                        "mp4" | "avi" | "mkv" | "mov" | "wmv" => "Videos",
                        "mp3" | "wav" | "flac" | "aac" | "ogg" => "Audio",
                        "zip" | "tar" | "gz" | "7z" | "rar" => "Archives",
                        "pdf" | "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx" => "Documents",
                        "rs" | "js" | "ts" | "py" | "go" | "c" | "cpp" | "java" => "Code",
                        "txt" | "md" | "log" => "Text",
                        _ => "Other",
                    }
                    .to_string()
                }
                DistributionType::Size => {
                    // Size buckets
                    match entry.size {
                        0..=1024 => "< 1KB",
                        1025..=1_048_576 => "1KB - 1MB",
                        1_048_577..=10_485_760 => "1MB - 10MB",
                        10_485_761..=104_857_600 => "10MB - 100MB",
                        104_857_601..=1_073_741_824 => "100MB - 1GB",
                        _ => "> 1GB",
                    }
                    .to_string()
                }
                DistributionType::Ext => {
                    // By extension
                    Path::new(&entry.name)
                        .extension()
                        .and_then(|s| s.to_str())
                        .unwrap_or("no extension")
                        .to_string()
                }
            };

            *dist.entry(key).or_insert(0) += entry.size;
        }

        for child in &entry.children {
            process_entry(child, dist, dist_type);
        }
    }

    for entry in entries {
        process_entry(entry, &mut dist, dist_type);
    }

    dist
}

/// Print distribution as a table
fn write_distribution_table(
    out: &mut dyn Write,
    data: &[(String, u64)],
    total: u64,
    opts: &FormatOptions,
) -> Result<()> {
    writeln!(out, "\n{:>15} {:>12} {:>8}", "Category", "Size", "Percent")?;
    writeln!(out, "{}", "-".repeat(40))?;
    for (category, size) in data {
        let percent = (*size as f64 / total as f64) * 100.0;
        let line = format!(
            "{:>15} {:>12} {:>7.1}%",
            category,
            format_size(*size),
            percent
        );
        if opts.color {
            writeln!(out, "{}", line.bright_white())?;
        } else {
            writeln!(out, "{}", line)?;
        }
    }
    writeln!(out, "{}", "-".repeat(40))?;
    writeln!(
        out,
        "{:>15} {:>12} {:>7.1}%",
        "Total",
        format_size(total),
        100.0
    )?;
    Ok(())
}

/// Print distribution as a beautiful bar chart
fn write_distribution_chart(
    out: &mut dyn Write,
    data: &[(String, u64)],
    total: u64,
    opts: &FormatOptions,
) -> Result<()> {
    writeln!(out, "\n{}", "Size Distribution".bold())?;
    writeln!(out)?;
    let term_width = terminal_width().saturating_sub(35);
    let bar_char = if opts.unicode { "█" } else { "#" };
    let empty_char = if opts.unicode { "░" } else { "-" };
    for (category, size) in data {
        let percent = (*size as f64 / total as f64) * 100.0;
        let bar_width = ((percent / 100.0) * term_width as f64) as usize;
        let empty_width = term_width.saturating_sub(bar_width);
        let label = format!("{:>12}", category);
        let percent_str = format!("{:>5.1}%", percent);
        let size_str = format_size(*size);
        let bar = bar_char.repeat(bar_width);
        let empty = empty_char.repeat(empty_width);
        let (label_color, bar_color) = if opts.color {
            match percent as u32 {
                0..=10 => (label.green(), bar.green()),
                11..=25 => (label.yellow(), bar.yellow()),
                26..=50 => (label.bright_yellow(), bar.bright_yellow()),
                _ => (label.red(), bar.red()),
            }
        } else {
            (label.normal(), bar.normal())
        };
        writeln!(
            out,
            "{} {} [{}{}] {}",
            label_color,
            percent_str.dimmed(),
            bar_color,
            empty.dimmed(),
            size_str.bright_white()
        )?;
    }
    writeln!(
        out,
        "\n{:>12} {:>6} {} {}",
        "Total".bold(),
        "100.0%".dimmed(),
        " ".repeat(term_width + 2),
        format_size(total).bright_white().bold()
    )?;
    Ok(())
}

/// Format size in human-readable format
pub fn format_size(size: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = size as f64;
    let mut unit_idx = 0;

    while size >= 1024.0 && unit_idx < UNITS.len() - 1 {
        size /= 1024.0;
        unit_idx += 1;
    }

    if unit_idx == 0 {
        format!("{} {}", size as u64, UNITS[unit_idx])
    } else {
        format!("{:.1} {}", size, UNITS[unit_idx])
    }
}

/// Get terminal width
fn terminal_width() -> usize {
    // Try to get terminal width, default to 80 if unavailable
    term_size::dimensions().map(|(w, _)| w).unwrap_or(80)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(0), "0 B");
        assert_eq!(format_size(1023), "1023 B");
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
        assert_eq!(format_size(1_048_576), "1.0 MB");
        assert_eq!(format_size(1_073_741_824), "1.0 GB");
    }
}