smart-tree 8.0.1

Smart Tree - An intelligent, AI-friendly directory visualization tool
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
// -----------------------------------------------------------------------------
// ๐Ÿ—‚๏ธ LS MODE - The Classic Unix Experience with Smart-Tree Magic!
// -----------------------------------------------------------------------------
// This formatter replicates the beloved `ls -Alh` command that every Unix user
// knows and loves. We take that familiar format and supercharge it with
// smart-tree's intelligence and beautiful formatting.
//
// Output format matches: drwxrwxr-x 1 hue hue 1.2K Jul  9 14:56 filename
// - Permissions (like drwxrwxr-x)
// - Link count
// - Owner and group
// - Human-readable file size (1.2K, 45M, 2.3G)
// - Last modified date and time
// - Filename with proper coloring and emojis (optional)
//
// Hue gets the comfort of familiar ls output, Trish gets beautiful formatting,
// and Aye gets to show off some Rust file system wizardry! ๐ŸŽญ
// -----------------------------------------------------------------------------

use super::Formatter;
use crate::emoji_mapper;
use crate::scanner::{FileNode, TreeStats};
use anyhow::Result;
use chrono::{DateTime, Local};
use std::fs;
use std::io::Write;
use std::path::Path;

#[cfg(unix)]
use std::os::unix::fs::{MetadataExt, PermissionsExt};

/// LS Formatter - Unix ls -Alh output with smart-tree enhancements
///
/// This formatter provides the classic Unix `ls -Alh` experience:
/// - Long format with detailed file information
/// - Human-readable file sizes  
/// - All files including hidden ones
/// - Familiar permissions display
/// - Proper date/time formatting
///
/// Perfect for users who want smart-tree's power with familiar ls output!
pub struct LsFormatter {
    /// Whether to show emojis alongside filenames (default: true)
    show_emojis: bool,
    /// Whether to use colors in output (default: true)  
    use_colors: bool,
}

impl Default for LsFormatter {
    fn default() -> Self {
        Self::new(true, true)
    }
}

impl LsFormatter {
    /// Create a new LS formatter
    ///
    /// # Arguments
    /// * `show_emojis` - Whether to include emojis in the output (Trish loves these!)
    /// * `use_colors` - Whether to colorize the output for better readability
    pub fn new(show_emojis: bool, use_colors: bool) -> Self {
        Self {
            show_emojis,
            use_colors,
        }
    }

    /// Format file permissions in the classic Unix style (e.g., drwxrwxr-x)
    ///
    /// This creates the familiar 10-character permission string that every
    /// Unix user recognizes. First character is file type, then 3 groups of
    /// 3 characters each for owner, group, and other permissions.
    /// On Windows, we show a simplified version.
    fn format_permissions(&self, node: &FileNode) -> String {
        let metadata = match fs::metadata(&node.path) {
            Ok(meta) => meta,
            Err(_) => return "?---------".to_string(), // Permission denied or file missing
        };

        let file_type = if metadata.is_dir() {
            'd'
        } else if metadata.is_symlink() {
            'l'
        } else {
            '-'
        };

        #[cfg(unix)]
        {
            let mode = metadata.permissions().mode();

            // Extract permission bits (owner, group, other)
            let owner_perms = format!(
                "{}{}{}",
                if mode & 0o400 != 0 { 'r' } else { '-' },
                if mode & 0o200 != 0 { 'w' } else { '-' },
                if mode & 0o100 != 0 { 'x' } else { '-' }
            );

            let group_perms = format!(
                "{}{}{}",
                if mode & 0o040 != 0 { 'r' } else { '-' },
                if mode & 0o020 != 0 { 'w' } else { '-' },
                if mode & 0o010 != 0 { 'x' } else { '-' }
            );

            let other_perms = format!(
                "{}{}{}",
                if mode & 0o004 != 0 { 'r' } else { '-' },
                if mode & 0o002 != 0 { 'w' } else { '-' },
                if mode & 0o001 != 0 { 'x' } else { '-' }
            );

            format!("{}{}{}{}", file_type, owner_perms, group_perms, other_perms)
        }

        #[cfg(windows)]
        {
            // On Windows, show simplified permissions
            let readonly = metadata.permissions().readonly();
            if readonly {
                format!("{}r--r--r--", file_type)
            } else {
                format!("{}rw-rw-rw-", file_type)
            }
        }

        #[cfg(not(any(unix, windows)))]
        {
            // For other platforms, show a generic format
            format!("{}rwxrwxrwx", file_type)
        }
    }

    /// Format file size in human-readable format (like ls -h)
    ///
    /// Converts bytes to human-readable units (B, K, M, G, T)
    /// Uses binary units (1024) like traditional ls command
    fn format_size(&self, size: u64) -> String {
        const UNITS: &[&str] = &["B", "K", "M", "G", "T"];

        if size == 0 {
            return "0".to_string();
        }

        let mut size_f = size as f64;
        let mut unit_index = 0;

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

        if unit_index == 0 {
            format!("{}", size)
        } else if size_f >= 10.0 {
            format!("{:.0}{}", size_f, UNITS[unit_index])
        } else {
            format!("{:.1}{}", size_f, UNITS[unit_index])
        }
    }

    /// Get the appropriate emoji for a file node
    ///
    /// This adds visual flair to the output, making it easier to quickly
    /// identify file types. Uses the centralized emoji mapper for rich file type representation!
    fn get_emoji(&self, node: &FileNode) -> &'static str {
        if !self.show_emojis {
            return "";
        }

        emoji_mapper::get_file_emoji(node, false)
    }

    /// Format the filename with optional emoji and coloring
    /// Ensures consistent spacing by padding emoji field to 2 characters
    fn format_filename(&self, node: &FileNode) -> String {
        let emoji = self.get_emoji(node);
        let filename = node
            .path
            .file_name()
            .unwrap_or_else(|| node.path.as_os_str())
            .to_string_lossy();

        // Format emoji with consistent spacing
        let emoji_field = if emoji.is_empty() {
            String::new()
        } else {
            // Always add a space after emoji for consistent alignment
            format!("{} ", emoji)
        };

        if self.use_colors {
            if node.is_dir {
                // Blue color for directories (ANSI color code 34)
                format!("{}\x1b[34m{}\x1b[0m", emoji_field, filename)
            } else if node.path.extension().and_then(|s| s.to_str()) == Some("rs") {
                // Orange color for Rust files (Hue's favorite!)
                format!("{}\x1b[38;5;208m{}\x1b[0m", emoji_field, filename)
            } else {
                // Default color for regular files
                format!("{}{}", emoji_field, filename)
            }
        } else if emoji_field.is_empty() {
            filename.to_string()
        } else {
            format!("{}{}", emoji_field, filename)
        }
    }

    /// Get owner and group information
    ///
    /// On Unix systems, this attempts to resolve uid/gid to actual names.
    /// Falls back to numeric IDs if resolution fails.
    fn get_owner_group(&self, node: &FileNode) -> (String, String) {
        #[cfg(unix)]
        {
            use std::ffi::CStr;

            // Get username from uid
            let owner = unsafe {
                let passwd = libc::getpwuid(node.uid);
                if passwd.is_null() {
                    // User not found, use numeric ID
                    node.uid.to_string()
                } else {
                    // Convert username to String
                    CStr::from_ptr((*passwd).pw_name)
                        .to_string_lossy()
                        .to_string()
                }
            };

            // Get group name from gid
            let group = unsafe {
                let grp = libc::getgrgid(node.gid);
                if grp.is_null() {
                    // Group not found, use numeric ID
                    node.gid.to_string()
                } else {
                    // Convert group name to String
                    CStr::from_ptr((*grp).gr_name).to_string_lossy().to_string()
                }
            };

            (owner, group)
        }

        #[cfg(not(unix))]
        {
            // On non-Unix systems, just show the numeric IDs
            (node.uid.to_string(), node.gid.to_string())
        }
    }

    /// Get hard link count (simplified)
    fn get_link_count(&self, node: &FileNode) -> u64 {
        #[cfg(unix)]
        {
            match fs::metadata(&node.path) {
                Ok(meta) => meta.nlink(),
                Err(_) => 1, // Default to 1 if we can't read metadata
            }
        }

        #[cfg(not(unix))]
        {
            // On non-Unix systems, always return 1 for files, 2 for directories
            // This is a reasonable approximation
            if node.is_dir {
                2
            } else {
                1
            }
        }
    }
}

impl Formatter for LsFormatter {
    fn format(
        &self,
        writer: &mut dyn Write,
        nodes: &[FileNode],
        _stats: &TreeStats,
        root_path: &Path,
    ) -> Result<()> {
        // Check if this appears to be a filtered result set (from --find or other filters)
        // Heuristic: if nodes don't include all direct children of root, it's likely filtered
        let direct_child_count = nodes
            .iter()
            .filter(|n| n.path != root_path && n.path.parent() == Some(root_path))
            .count();
        let total_non_root = nodes.iter().filter(|n| n.path != root_path).count();
        let is_filtered = total_non_root > 0
            && (direct_child_count == 0 || total_non_root > direct_child_count * 2);

        let display_nodes: Vec<&FileNode> = if is_filtered {
            // For filtered results, show all matching nodes with full paths
            nodes
                .iter()
                .filter(|node| node.path != root_path) // Still exclude the root
                .collect()
        } else {
            // Normal ls behavior: only show direct children of root_path
            nodes
                .iter()
                .filter(|node| {
                    if node.path == root_path {
                        return false; // Don't show the root directory itself
                    }
                    // Only show direct children (depth 1 from root)
                    node.path.parent() == Some(root_path)
                })
                .collect()
        };

        // If no files/directories to display, show a message
        if display_nodes.is_empty() {
            writeln!(writer, "No matching files or directories found")?;
            if is_filtered {
                writeln!(writer)?;
                writeln!(
                    writer,
                    "๐Ÿ’ก Tip: Try using --everything to search in ignored directories like .cache"
                )?;
                writeln!(
                    writer,
                    "๐Ÿ’ก Tip: Use -d 10 or higher to search deeper (default is 5 levels)"
                )?;
                writeln!(
                    writer,
                    "๐Ÿ’ก Tip: Hidden directories need -a flag, ignored ones need --everything"
                )?;
            }
            return Ok(());
        }

        // Note: Nodes are already sorted by the scanner based on user's --sort preference
        // We don't re-sort here to preserve the requested sort order

        // Format each file/directory in ls -Alh style
        for node in display_nodes {
            let permissions = self.format_permissions(node);
            let link_count = self.get_link_count(node);
            let (owner, group) = self.get_owner_group(node);
            let size = self.format_size(node.size);

            // Format the modification time
            let modified_time = match fs::metadata(&node.path) {
                Ok(meta) => match meta.modified() {
                    Ok(time) => {
                        let datetime: DateTime<Local> = time.into();
                        datetime.format("%b %d %H:%M").to_string()
                    }
                    Err(_) => "??? ?? ??:??".to_string(),
                },
                Err(_) => "??? ?? ??:??".to_string(),
            };

            // Determine filename display strategy:
            // - When filtering results (search/pattern match): Show relative path for context
            // - Otherwise: Show only the filename for cleaner output
            let filename = if is_filtered {
                // Format with relative path to help identify match locations
                let emoji = self.get_emoji(node);
                // Format emoji with consistent spacing
                let emoji_field = if emoji.is_empty() {
                    String::new()
                } else {
                    // Always add a space after emoji for consistent alignment
                    format!("{} ", emoji)
                };

                // Get relative path from root_path
                let relative_path = node
                    .path
                    .strip_prefix(root_path)
                    .unwrap_or(&node.path)
                    .display();

                // Apply directory coloring if colors are enabled
                if self.use_colors && node.is_dir {
                    // Blue color (ANSI 34) for directories
                    format!("{}\x1b[34m{}\x1b[0m", emoji_field, relative_path)
                } else {
                    // Default formatting for files or when colors are disabled
                    format!("{}{}", emoji_field, relative_path)
                }
            } else {
                self.format_filename(node)
            };

            // Write the ls -Alh formatted line
            writeln!(
                writer,
                "{:<10} {:>1} {:<4} {:<4} {:>6} {} {}",
                permissions, link_count, owner, group, size, modified_time, filename
            )?;
        }

        Ok(())
    }
}

// -----------------------------------------------------------------------------
// ๐ŸŽญ Tests - Because Trish insists on quality assurance!
// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scanner::{FileCategory, FileType, FilesystemType};
    use std::path::PathBuf;
    use std::time::SystemTime;

    #[test]
    fn test_format_size() {
        let formatter = LsFormatter::new(false, false);

        assert_eq!(formatter.format_size(0), "0");
        assert_eq!(formatter.format_size(500), "500");
        assert_eq!(formatter.format_size(1024), "1.0K");
        assert_eq!(formatter.format_size(1536), "1.5K");
        assert_eq!(formatter.format_size(1048576), "1.0M");
        assert_eq!(formatter.format_size(1073741824), "1.0G");
    }

    #[test]
    fn test_emoji_selection() {
        let formatter = LsFormatter::new(true, false);

        // Test directory emojis
        let empty_dir = FileNode {
            path: PathBuf::from("/test"),
            file_type: FileType::Directory,
            size: 0,
            is_dir: true,
            depth: 0,
            permissions: 0o755,
            modified: SystemTime::now(),
            uid: 1000,
            gid: 1000,
            is_symlink: false,
            is_hidden: false,
            permission_denied: false,
            is_ignored: false,
            category: FileCategory::Unknown,
            search_matches: None,
            filesystem_type: FilesystemType::Unknown,
            git_branch: None,
            traversal_context: None,
            interest: None,
            security_findings: Vec::new(),
            change_status: None,
            content_hash: None,
        };
        assert_eq!(formatter.get_emoji(&empty_dir), "๐Ÿ“‚");

        // Test file emojis
        let empty_file = FileNode {
            path: PathBuf::from("/test.txt"),
            file_type: FileType::RegularFile,
            size: 0,
            is_dir: false,
            depth: 0,
            permissions: 0o644,
            modified: SystemTime::now(),
            uid: 1000,
            gid: 1000,
            is_symlink: false,
            is_hidden: false,
            permission_denied: false,
            is_ignored: false,
            category: FileCategory::Unknown,
            search_matches: None,
            filesystem_type: FilesystemType::Unknown,
            git_branch: None,
            traversal_context: None,
            interest: None,
            security_findings: Vec::new(),
            change_status: None,
            content_hash: None,
        };
        assert_eq!(formatter.get_emoji(&empty_file), "๐Ÿชน");
    }

    #[test]
    fn test_permissions_format() {
        let formatter = LsFormatter::new(false, false);

        // This is a basic test - in real usage, format_permissions
        // reads actual file metadata
        let test_node = FileNode {
            path: PathBuf::from("/test"),
            file_type: FileType::Directory,
            size: 0,
            is_dir: true,
            depth: 0,
            permissions: 0o755,
            modified: SystemTime::now(),
            uid: 1000,
            gid: 1000,
            is_symlink: false,
            is_hidden: false,
            permission_denied: false,
            is_ignored: false,
            category: FileCategory::Unknown,
            search_matches: None,
            filesystem_type: FilesystemType::Unknown,
            git_branch: None,
            traversal_context: None,
            interest: None,
            security_findings: Vec::new(),
            change_status: None,
            content_hash: None,
        };

        let perms = formatter.format_permissions(&test_node);
        // Should start with 'd' for directory or '?' if we can't read it
        assert!(perms.starts_with('d') || perms.starts_with('?'));
        assert_eq!(perms.len(), 10); // Always 10 characters
    }
}