bestls 1.5.0

A fast and colorful Rust-based ls replacement CLI tool with JSON output and sorting options.
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! # File System Operations Module
//!
//! This module handles all file system operations and data structures for **bestls**.
//! It provides comprehensive file metadata extraction with cross-platform support
//! and parallel processing capabilities using `rayon`.
//!
//! ## Key Components
//!
//! - [`FileEntry`]: Core data structure representing a file or directory with complete metadata
//! - [`FileType`]: Enumeration of supported file system entry types
//! - [`get_files`]: Main function for retrieving and processing directory contents
//!
//! ## Features
//!
//! * **Parallel Processing**: Uses `rayon` for concurrent metadata fetching
//! * **Cross-Platform Support**: Handles Unix permissions with graceful Windows/other platform fallbacks
//! * **Rich Metadata**: Extracts size, permissions, ownership, and modification times
//! * **Human-Readable Output**: Formats file sizes and dates for easy reading
//!
//! ## Platform-Specific Behavior
//!
//! ### Unix Systems (Linux, macOS, etc.)
//! - Full permission handling (rwxrwxrwx format)
//! - User and group name resolution via `nix` crate
//! - Complete file metadata extraction
//!
//! ### Windows Systems
//! - Basic readonly/readwrite permissions
//! - Placeholder "Owner"/"Group" values
//! - Standard file metadata
//!
//! ### Other Platforms
//! - "N/A" fallbacks for unsupported features
//! - Basic file information only
//!
//! ## Examples
//!
//! ### Basic Directory Listing
//!
//! ```rust
//! use std::path::Path;
//! use bestls::fsops::get_files;
//!
//! let path = Path::new(".");
//! let include_hidden = false;
//!
//! match get_files(&path, include_hidden) {
//!     Ok(files) => {
//!         for file in files {
//!             println!("{}: {} ({})", file.name, file.human_size, file.e_type);
//!         }
//!     }
//!     Err(e) => eprintln!("Error reading directory: {}", e),
//! }
//! ```
//!
//! ### Including Hidden Files
//!
//! ```rust
//! use std::path::Path;
//! use bestls::fsops::get_files;
//!
//! let path = Path::new("/home/user");
//! let include_hidden = true; // Include files starting with '.'
//!
//! let files = get_files(&path, include_hidden)?;
//! println!("Found {} files (including hidden)", files.len());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use bytesize::ByteSize;
use chrono::{DateTime, Utc};
use rayon::prelude::*;
use serde::Serialize;
use std::{fmt, fs, io, path::Path};
use strum::Display;

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

/// Enumeration of file system entry types supported by bestls.
///
/// This enum represents the different types of file system entries that can be encountered
/// during directory traversal. It derives several traits for display and serialization.
///
/// # Variants
///
/// * `File` - Regular file
/// * `Directory` - Directory/folder
/// * `Symlink` - Symbolic link
///
/// # Traits
///
/// - `Debug`: For debugging output
/// - `Display`: For human-readable string representation via `strum`
/// - `Serialize`: For JSON output via `serde`
/// - `Clone`: For efficient copying
///
/// # Examples
///
/// ```rust
/// use bestls::fsops::FileType;
///
/// let file_type = FileType::File;
/// println!("Entry type: {}", file_type); // Prints: "Entry type: File"
///
/// // Use in match expressions
/// match file_type {
///     FileType::File => println!("This is a regular file"),
///     FileType::Directory => println!("This is a directory"),
///     FileType::Symlink => println!("This is a symbolic link"),
/// }
/// ```
///
/// # JSON Serialization
///
/// When serialized to JSON, the variants become strings:
///
/// ```json
/// {
///   "e_type": "File"
/// }
/// ```
#[derive(Debug, Display, Serialize, Clone)]
pub enum FileType {
    /// Regular file
    File,
    /// Directory or folder
    Directory,
    /// Symbolic link
    Symlink,
}

/// Comprehensive file system entry representation with rich metadata.
///
/// This struct contains all the metadata for a file system entry that bestls can extract.
/// It's designed to be serializable to JSON and provides human-readable formatting for
/// sizes and dates.
///
/// # Fields
///
/// * `name` - The filename or directory name (without path)
/// * `e_type` - The type of entry (File, Directory, or Symlink)
/// * `len_bytes` - Raw file size in bytes (for sorting and calculations)
/// * `human_size` - Human-readable size string (e.g., "1.5 KB", "2.1 MB")
/// * `modified` - Formatted modification date and time
/// * `permissions` - File permissions string (Unix: "rwxrwxrwx", Windows: "rw-" or "r--")
/// * `owner` - File owner name (Unix: resolved username, Windows: "Owner", other: "N/A")
/// * `group` - File group name (Unix: resolved group name, Windows: "Group", other: "N/A")
///
/// # Platform Differences
///
/// ## Unix Systems (Linux, macOS, etc.)
/// ```text
/// FileEntry {
///     name: "document.txt",
///     e_type: File,
///     len_bytes: 1024,
///     human_size: "1.0 KB",
///     modified: "Mon 15 Jan 2024 14:30:25",
///     permissions: "rw-r--r--",
///     owner: "username",
///     group: "users"
/// }
/// ```
///
/// ## Windows Systems
/// ```text
/// FileEntry {
///     name: "document.txt",
///     e_type: File,
///     len_bytes: 1024,
///     human_size: "1.0 KB",
///     modified: "Mon 15 Jan 2024 14:30:25",
///     permissions: "rw-",
///     owner: "Owner",
///     group: "Group"
/// }
/// ```
///
/// # Examples
///
/// ## Creating and Using FileEntry
///
/// ```rust
/// use bestls::fsops::{FileEntry, FileType};
/// use serde_json;
///
/// let entry = FileEntry {
///     name: "example.txt".to_string(),
///     e_type: FileType::File,
///     len_bytes: 2048,
///     human_size: "2.0 KB".to_string(),
///     modified: "Mon 15 Jan 2024 14:30:25".to_string(),
///     permissions: "rw-r--r--".to_string(),
///     owner: "user".to_string(),
///     group: "staff".to_string(),
/// };
///
/// // Serialize to JSON
/// let json = serde_json::to_string_pretty(&entry)?;
/// println!("{}", json);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Sorting FileEntry Collections
///
/// ```rust
/// use bestls::fsops::FileEntry;
///
/// fn sort_by_size(mut files: Vec<FileEntry>) -> Vec<FileEntry> {
///     files.sort_by(|a, b| a.len_bytes.cmp(&b.len_bytes));
///     files
/// }
///
/// fn sort_by_name(mut files: Vec<FileEntry>) -> Vec<FileEntry> {
///     files.sort_by(|a, b| a.name.cmp(&b.name));
///     files
/// }
/// ```
///
/// # JSON Output Format
///
/// When serialized to JSON, FileEntry produces well-structured output:
///
/// ```json
/// {
///   "name": "example.txt",
///   "e_type": "File",
///   "len_bytes": 2048,
///   "human_size": "2.0 KB",
///   "modified": "Mon 15 Jan 2024 14:30:25",
///   "permissions": "rw-r--r--",
///   "owner": "user",
///   "group": "staff"
/// }
/// ```
#[derive(Debug, Serialize, Clone)]
pub struct FileEntry {
    /// The filename or directory name (without path components)
    pub name: String,
    /// The type of file system entry (File, Directory, or Symlink)
    pub e_type: FileType,
    /// Raw file size in bytes (used for sorting and calculations)
    pub len_bytes: u64,
    /// Human-readable file size (e.g., "1.5 KB", "2.1 MB", "1.2 GB")
    pub human_size: String,
    /// Formatted modification date and time string
    pub modified: String,
    /// File permissions string (format varies by platform)
    pub permissions: String,
    /// File owner name (platform-dependent format)
    pub owner: String,
    /// File group name (platform-dependent format)
    pub group: String,
}

/// Retrieve and process all files in a directory with optional hidden file inclusion.
///
/// This is the main entry point for file system operations in bestls. It reads a directory,
/// optionally filters out hidden files, and processes all entries in parallel using `rayon`
/// to extract comprehensive metadata.
///
/// # Arguments
///
/// * `path` - The directory path to read
/// * `include_hidden` - Whether to include files starting with '.' (Unix hidden files)
///
/// # Returns
///
/// * `Ok(Vec<FileEntry>)` - Vector of file entries with complete metadata
/// * `Err(io::Error)` - I/O error if directory cannot be read
///
/// # Performance
///
/// This function uses parallel processing via `rayon` to extract metadata from multiple files
/// concurrently. This provides significant performance benefits for directories with many files,
/// especially when accessing network filesystems or slow storage devices.
///
/// # Examples
///
/// ## Basic Directory Listing
///
/// ```rust
/// use std::path::Path;
/// use bestls::fsops::get_files;
///
/// let current_dir = Path::new(".");
/// let files = get_files(&current_dir, false)?;
///
/// for file in files {
///     println!("{}: {}", file.name, file.human_size);
/// }
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// ## Including Hidden Files
///
/// ```rust
/// use std::path::Path;
/// use bestls::fsops::get_files;
///
/// let home_dir = Path::new("/home/user");
/// let all_files = get_files(&home_dir, true)?; // Include .bashrc, .profile, etc.
///
/// let hidden_count = all_files.iter()
///     .filter(|f| f.name.starts_with('.'))
///     .count();
///
/// println!("Found {} hidden files", hidden_count);
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// ## Error Handling
///
/// ```rust
/// use std::path::Path;
/// use bestls::fsops::get_files;
///
/// let restricted_dir = Path::new("/root");
/// match get_files(&restricted_dir, false) {
///     Ok(files) => println!("Found {} files", files.len()),
///     Err(e) => eprintln!("Cannot access directory: {}", e),
/// }
/// ```
///
/// # Error Conditions
///
/// This function can return errors in several scenarios:
/// - Directory does not exist
/// - Permission denied to read directory
/// - Path points to a file rather than directory
/// - I/O errors during filesystem access
///
/// Individual file metadata extraction errors are silently ignored to allow partial
/// directory listings even when some files cannot be accessed.
pub fn get_files(path: &Path, include_hidden: bool) -> Result<Vec<FileEntry>, io::Error> {
    let entries: Vec<fs::DirEntry> = fs::read_dir(path)?
        .filter_map(Result::ok)
        .filter(|entry: &fs::DirEntry| {
            include_hidden || !entry.file_name().to_string_lossy().starts_with('.')
        })
        .collect();

    let files: Vec<FileEntry> = entries
        .par_iter()
        .map(map_data)
        .filter_map(Result::ok)
        .collect();

    Ok(files)
}

/// Internal function to extract comprehensive metadata from a file system entry.
///
/// This function takes a `DirEntry` and extracts all available metadata, including
/// file type, size, permissions, ownership, and modification time. It handles
/// platform-specific differences gracefully using conditional compilation.
///
/// # Arguments
///
/// * `entry` - A directory entry from `fs::read_dir()`
///
/// # Returns
///
/// * `Ok(FileEntry)` - Complete file entry with all metadata
/// * `Err(io::Error)` - I/O error during metadata extraction
///
/// # Platform-Specific Processing
///
/// ## Unix Systems
/// - Extracts full rwxrwxrwx permissions using bit manipulation
/// - Resolves user and group names via `nix` crate
/// - Provides complete file system metadata
///
/// ## Windows Systems
/// - Simplifies permissions to "rw-" or "r--" based on readonly flag
/// - Uses placeholder "Owner" and "Group" strings
/// - Extracts standard file metadata
///
/// ## Other Platforms
/// - Falls back to "N/A" for unsupported features
/// - Provides basic file information
///
/// # Examples
///
/// This function is called internally by [`get_files`] and typically not used directly:
///
/// ```rust
/// // Internal usage within get_files()
/// let files: Vec<FileEntry> = entries
///     .par_iter()
///     .map(map_data)  // <- This function
///     .filter_map(Result::ok)
///     .collect();
/// ```
///
/// # Error Handling
///
/// Errors can occur during:
/// - Metadata extraction (`entry.metadata()`)
/// - File system access issues
/// - Platform-specific permission/ownership resolution
///
/// These errors are typically handled by the calling [`get_files`] function,
/// which filters out failed entries to provide partial results.
fn map_data(entry: &fs::DirEntry) -> Result<FileEntry, io::Error> {
    let metadata: fs::Metadata = entry.metadata()?;
    let file_type: fs::FileType = metadata.file_type();

    let modified: String = metadata
        .modified()
        .map(|m: std::time::SystemTime| {
            let dt: DateTime<Utc> = m.into();
            dt.format("%a %d %b %Y %H:%M:%S").to_string()
        })
        .unwrap_or_default();

    // Permissions
    #[cfg(unix)]
    let permissions: String = {
        let mode: u32 = metadata.permissions().mode();
        format!(
            "{}{}{}{}{}{}{}{}{}",
            if mode & 0o400 != 0 { 'r' } else { '-' },
            if mode & 0o200 != 0 { 'w' } else { '-' },
            if mode & 0o100 != 0 { 'x' } else { '-' },
            if mode & 0o040 != 0 { 'r' } else { '-' },
            if mode & 0o020 != 0 { 'w' } else { '-' },
            if mode & 0o010 != 0 { 'x' } else { '-' },
            if mode & 0o004 != 0 { 'r' } else { '-' },
            if mode & 0o002 != 0 { 'w' } else { '-' },
            if mode & 0o001 != 0 { 'x' } else { '-' },
        )
    };

    #[cfg(windows)]
    let permissions = if metadata.permissions().readonly() {
        "r--".into()
    } else {
        "rw-".into()
    };

    #[cfg(not(any(unix, windows)))]
    let permissions = "N/A".to_string();

    // Owner / Group - Using nix crate instead of users
    #[cfg(unix)]
    let (owner_name, group_name) = get_owner_group(&metadata);

    #[cfg(windows)]
    let (owner_name, group_name) = ("Owner".into(), "Group".into());

    #[cfg(not(any(unix, windows)))]
    let (owner_name, group_name) = ("N/A".into(), "N/A".into());

    Ok(FileEntry {
        name: entry.file_name().to_string_lossy().to_string(),
        e_type: if file_type.is_file() {
            FileType::File
        } else if file_type.is_dir() {
            FileType::Directory
        } else if file_type.is_symlink() {
            FileType::Symlink
        } else {
            FileType::File
        },
        len_bytes: metadata.len(),
        human_size: ByteSize(metadata.len()).to_string(),
        modified,
        permissions,
        owner: owner_name,
        group: group_name,
    })
}

/// Extract user and group names from file metadata on Unix systems.
///
/// This function is only compiled on Unix-like systems (Linux, macOS, etc.) and uses
/// the `nix` crate to resolve numeric user and group IDs to their corresponding names.
/// If name resolution fails, it falls back to displaying the numeric IDs.
///
/// # Arguments
///
/// * `metadata` - File metadata from which to extract ownership information
///
/// # Returns
///
/// A tuple containing:
/// * `String` - Username (or UID if name resolution fails)
/// * `String` - Group name (or GID if name resolution fails)
///
/// # Platform Support
///
/// This function is only available on Unix-like systems. It's conditionally compiled
/// using `#[cfg(unix)]` and will not be included in builds for Windows or other platforms.
///
/// # Examples
///
/// This function is used internally by [`map_data`]:
///
/// ```rust
/// // Internal usage (Unix only)
/// #[cfg(unix)]
/// let (owner_name, group_name) = get_owner_group(&metadata);
/// // Result might be ("alice", "developers") or ("1001", "1002") if names can't be resolved
/// ```
///
/// # Error Handling
///
/// The function gracefully handles cases where:
/// - User ID cannot be resolved to a username (returns numeric UID)
/// - Group ID cannot be resolved to a group name (returns numeric GID)
/// - System calls fail during name resolution (returns numeric IDs)
///
/// This ensures the function always returns valid strings, even in edge cases
/// like deleted users or system inconsistencies.
///
/// # Dependencies
///
/// Requires the `nix` crate for Unix system calls and the following metadata traits:
/// - `std::os::unix::fs::MetadataExt` for accessing `uid()` and `gid()`
/// - `nix::unistd::{User, Group, Uid, Gid}` for name resolution
#[cfg(unix)]
fn get_owner_group(metadata: &fs::Metadata) -> (String, String) {
    use nix::unistd::{Gid, Uid};

    let uid: Uid = Uid::from(metadata.uid());
    let gid: Gid = Gid::from(metadata.gid());

    let user: String = User::from_uid(uid)
        .ok()
        .flatten()
        .map(|u: User| u.name)
        .unwrap_or_else(|| uid.to_string());

    let group: String = Group::from_gid(gid)
        .ok()
        .flatten()
        .map(|g: Group| g.name)
        .unwrap_or_else(|| gid.to_string());

    (user, group)
}

/// Error type for size parsing operations
#[derive(Debug, Clone)]
pub enum SizeParseError {
    Empty,
    InvalidNumber(String),
    InvalidUnit(String),
    Overflow,
    NegativeValue { value: String },
}

impl fmt::Display for SizeParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SizeParseError::Empty => write!(f, "empty size string provided"),
            SizeParseError::InvalidNumber(s) => {
                write!(f, "invalid size value '{}' (expected a number)", s)
            }
            SizeParseError::InvalidUnit(u) => {
                write!(
                    f,
                    "unknown size unit '{}' (valid units: B, KB, MB, GB, TB)",
                    u
                )
            }
            SizeParseError::Overflow => write!(f, "size value exceeds maximum ({})", u64::MAX),
            SizeParseError::NegativeValue { value } => {
                write!(
                    f,
                    "invalid size value '{}' (size must be non-negative)",
                    value
                )
            }
        }
    }
}

impl std::error::Error for SizeParseError {}

/// Parse human-readable size strings (e.g., "1KB", "1.5MB", "100B")
///
/// Supports integer and decimal inputs (e.g., "1024", "1.5MB").
/// Uses integer arithmetic where possible to avoid floating-point precision issues.
///
/// # Examples
/// - "1KB" → Ok(1024)
/// - "1.5MB" → Ok(1572864)
/// - "100" → Ok(100) (defaults to bytes)
/// - "invalid" → Err(SizeParseError::InvalidNumber(...))
pub fn parse_size(size_str: &str) -> Result<u64, SizeParseError> {
    let size_str = size_str.trim().to_uppercase();

    if size_str.is_empty() {
        return Err(SizeParseError::Empty);
    }

    let (num_part, unit) = if let Some(pos) = size_str.find(|c: char| c.is_alphabetic()) {
        (&size_str[..pos], &size_str[pos..])
    } else {
        (&size_str[..], "B")
    };

    let num_str = num_part.trim();

    let multiplier = match unit {
        "B" => 1u64,
        "KB" | "K" => 1024u64,
        "MB" | "M" => 1024u64 * 1024u64,
        "GB" | "G" => 1024u64 * 1024u64 * 1024u64,
        "TB" | "T" => 1024u64 * 1024u64 * 1024u64 * 1024u64,
        _ => return Err(SizeParseError::InvalidUnit(unit.to_string())),
    };

    // Try parsing as u64 first (integer case)
    if let Ok(num_u64) = num_str.parse::<u64>() {
        return num_u64
            .checked_mul(multiplier)
            .ok_or(SizeParseError::Overflow);
    }

    // Fall back to f64 for decimal values (e.g., "1.5MB")
    let num: f64 = num_str
        .parse()
        .map_err(|_| SizeParseError::InvalidNumber(num_str.to_string()))?;

    // Reject negative values (semantic error: input is numeric but disallowed)
    if num < 0.0 {
        return Err(SizeParseError::NegativeValue {
            value: num_str.to_string(),
        });
    }

    // Check for overflow: ensure num * multiplier <= u64::MAX
    let result = num * multiplier as f64;
    if result > u64::MAX as f64 || result.is_infinite() || result.is_nan() {
        return Err(SizeParseError::Overflow);
    }

    Ok(result as u64)
}

/// Check if filename matches extension filter (case-insensitive)
/// Extensions should be pre-normalized (lowercase, without leading '.')
pub fn matches_extension(filename: &str, extensions: &[String]) -> bool {
    if extensions.is_empty() {
        return true;
    }

    let filename_lower = filename.to_lowercase();
    let filename_bytes = filename_lower.as_bytes();

    extensions.iter().any(|ext| {
        // Extensions are pre-normalized; check if filename ends with ".ext"
        // Avoid format! allocation: check for dot followed by extension bytes
        if filename_bytes.len() <= ext.len() {
            return false;
        }
        let dot_pos = filename_bytes.len() - ext.len() - 1;
        filename_bytes[dot_pos] == b'.' && &filename_bytes[dot_pos + 1..] == ext.as_bytes()
    })
}

/// Glob-style pattern matching using standard glob semantics
///
/// Supports:
/// - `*` - matches any sequence of characters except path separators
/// - `?` - matches a single character
/// - `[abc]` - character classes
/// - `[!abc]` - negated character classes
///
/// # Examples
/// - `*.rs` - matches all .rs files
/// - `test_*` - matches files starting with test_
/// - `*_test.rs` - matches files ending with _test.rs
///
/// # Note
/// This function assumes the glob pattern has already been compiled and validated
/// (e.g., during filter configuration construction), so it performs only the match
/// operation without recompiling or validating the pattern.
pub fn matches_pattern(filename: &str, pattern: &glob::Pattern) -> bool {
    pattern.matches(filename)
}

/// Recursively get files with optional depth limit
///
/// # Depth semantics
/// - `depth = 0` (or None): Unlimited depth, traverse all subdirectories
/// - `depth = 1`: Only files in the specified directory (no recursion)
/// - `depth = 2`: Files in the directory plus one level of subdirectories
/// - `depth = n`: Files up to n levels deep
pub fn get_files_recursive(
    path: &Path,
    include_hidden: bool,
    max_depth: Option<usize>,
) -> Result<Vec<FileEntry>, io::Error> {
    let mut files = Vec::new();
    collect_files_recursive(path, include_hidden, max_depth, 0, &mut files)?;
    Ok(files)
}

fn collect_files_recursive(
    path: &Path,
    include_hidden: bool,
    max_depth: Option<usize>,
    current_depth: usize,
    files: &mut Vec<FileEntry>,
) -> Result<(), io::Error> {
    // Check depth limit: if current_depth >= max_depth and max_depth > 0, stop recursing
    // max_depth = None or Some(0) means no limit; max_depth = 1 means current level only
    if let Some(max) = max_depth {
        if max > 0 && current_depth >= max {
            return Ok(());
        }
    }

    let entries: Vec<fs::DirEntry> = fs::read_dir(path)?
        .filter_map(Result::ok)
        .filter(|entry: &fs::DirEntry| {
            include_hidden || !entry.file_name().to_string_lossy().starts_with('.')
        })
        .collect();

    let mut file_entries: Vec<FileEntry> = entries
        .par_iter()
        .map(map_data)
        .filter_map(Result::ok)
        .collect();

    files.append(&mut file_entries);

    // Recurse into directories if we haven't hit the depth limit
    for entry in entries {
        if let Ok(metadata) = entry.metadata() {
            if metadata.is_dir() {
                // Log subdirectory traversal errors but continue with other directories
                // This allows collecting as many files as possible even if some subdirs are inaccessible
                if let Err(e) = collect_files_recursive(
                    &entry.path(),
                    include_hidden,
                    max_depth,
                    current_depth + 1,
                    files,
                ) {
                    eprintln!(
                        "Warning: failed to read directory '{}': {}",
                        entry.path().display(),
                        e
                    );
                }
            }
        }
    }

    Ok(())
}