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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! File list walking implementation
use crate::{
config::Config,
error::{Error, Result},
fs_utils::{
self,
security::{FileIdentity, get_stdout_identity, output_protection_threshold},
},
walker::{WalkerEntry, WalkerItem},
};
use log::{debug, error, warn};
use std::path::{Path, PathBuf};
use super::builder::configured_walk_builder;
use super::output_guard;
/// Walker for a specific list of files and directories
///
/// This walker handles both individual files and directories. Files are
/// validated and yielded directly. Directories are recursively walked with
/// the same filters as `DirectoryWalker`, and all contents are collected
/// during construction.
///
/// # Fused Iterator
///
/// This iterator is fused: once `next()` returns `None`, all subsequent
/// calls will also return `None`. This is guaranteed by the
/// [`FusedIterator`] impl (delegated to the inner `Vec::IntoIter`).
pub struct FileListWalker {
/// Iterator over collected entries
///
/// These are either direct file entries or entries collected from
/// recursively walking directory arguments. All entries are collected
/// during construction to enable `ExactSizeIterator`.
entries: std::vec::IntoIter<WalkerItem>,
}
impl FileListWalker {
/// Create a new file list walker
///
/// # Arguments
///
/// * `paths` - List of file and/or directory paths to process
/// * `config` - Configuration containing root path for validation
///
/// # Errors
///
/// Returns error if:
/// - Root directory cannot be canonicalized
/// - All specified paths are invalid (returns `AllFilesInvalid` error)
/// - No valid entries remain after validation
///
/// # Performance
///
/// Directories are walked and their contents collected during construction.
/// This is acceptable for explicit path lists (typically small) and enables
/// `ExactSizeIterator` support. Directory expansion is capped by
/// `config.max_files()` to prevent unbounded memory growth.
pub fn new(paths: &[PathBuf], config: &Config) -> Result<Self> {
// Canonicalize root once at construction (not per-path)
// This is a critical performance optimization: eliminates N syscalls
let canonical_root = config.root().canonicalize().map_err(|e| Error::Config {
message: format!("Failed to canonicalize root path: {e}"),
})?;
debug_assert!(
canonical_root.is_absolute(),
"Canonical root must be absolute"
);
// Pre-compute stdout identity once for output file protection.
// Matches DirectoryWalker's security behaviour.
let stdout_identity = get_stdout_identity();
let max_files = config.max_files();
debug!("Processing {} path(s)", paths.len());
// Collect all entries (files and expanded directories)
let mut all_entries = Vec::new();
let mut errors = Vec::new();
let mut file_count: usize = 0;
for path in paths {
// Budget for directory expansion: remaining files before the
// global cap. Explicit file arguments are always included
// (the user asked for them), but directory expansion must be
// bounded to prevent unbounded memory growth.
let remaining_budget = max_files.saturating_sub(file_count);
match Self::process_path(
path,
&canonical_root,
config,
stdout_identity.as_ref(),
remaining_budget,
) {
Ok(mut entries) => {
let new_files = entries
.iter()
.filter(|item| matches!(item, WalkerItem::Entry(e) if !e.is_dir))
.count();
debug!("Processed {}: {} entries", path.display(), new_files);
file_count = file_count.saturating_add(new_files);
all_entries.append(&mut entries);
}
Err(e) => {
error!("Invalid path {}: {}", path.display(), e);
errors.push((path.clone(), e));
}
}
}
// Report validation results
if !errors.is_empty() {
// If ALL paths failed, that's a hard error
if all_entries.is_empty() {
return Err(Error::AllFilesInvalid {
count: errors.len(),
});
}
// Some paths succeeded - warn about failures but continue
warn!(
"Skipped {} invalid path(s) out of {} total",
errors.len(),
paths.len()
);
}
debug!("Successfully processed {} entries total", all_entries.len());
// Convert to IntoIter for zero-copy iteration
Ok(Self {
entries: all_entries.into_iter(),
})
}
/// Process a single path (file or directory)
///
/// # Arguments
///
/// * `path` - Path to process
/// * `canonical_root` - Pre-canonicalized root for validation
/// * `config` - Configuration for directory walking
/// * `stdout_identity` - Pre-computed stdout identity for output protection
/// * `remaining_budget` - Maximum files to collect from directory expansion
///
/// # Returns
///
/// - For files: Single-item vec with the file entry
/// - For directories: Vec of files found recursively (capped by `remaining_budget`)
///
/// # Errors
///
/// Returns error if path is invalid, outside root, or inaccessible
fn process_path(
path: &Path,
canonical_root: &Path,
config: &Config,
stdout_identity: Option<&FileIdentity>,
remaining_budget: usize,
) -> Result<Vec<WalkerItem>> {
debug_assert!(
canonical_root.is_absolute(),
"Canonical root must be absolute"
);
// Validate path exists and get canonical form
let canonical = Self::validate_path(path, canonical_root)?;
let metadata = canonical.metadata().map_err(|e| {
warn!("Failed to get metadata for {}: {}", canonical.display(), e);
Error::InvalidPath {
path: path.to_path_buf(),
}
})?;
if metadata.is_file() {
// Single file - create entry
let relative_path = canonical
.strip_prefix(canonical_root)
.unwrap_or(&canonical)
.to_path_buf();
Ok(vec![WalkerItem::Entry(WalkerEntry {
path: canonical,
relative_path,
is_dir: false,
})])
} else if metadata.is_dir() {
// Directory - recursively walk and collect all files
debug!("Walking directory: {}", canonical.display());
Ok(Self::process_directory(
&canonical,
canonical_root,
config,
stdout_identity,
remaining_budget,
))
} else {
// Neither file nor directory (e.g., symlink to nowhere, device file)
warn!("Path is neither file nor directory: {}", path.display());
Err(Error::InvalidPath {
path: path.to_path_buf(),
})
}
}
/// Validate and canonicalize a path
///
/// # Security
///
/// - Ensures path exists
/// - Canonicalizes to prevent path traversal issues
/// - Validates against symlink attacks
/// - Ensures path is within project root
///
/// # Arguments
///
/// * `path` - Path to validate
/// * `canonical_root` - Pre-canonicalized root directory
fn validate_path(path: &Path, canonical_root: &Path) -> Result<PathBuf> {
debug_assert!(
canonical_root.is_absolute(),
"Canonical root must be absolute"
);
if !path.exists() {
return Err(Error::FileNotFound {
path: path.to_path_buf(),
});
}
// Canonicalize to resolve symlinks and get absolute path
let canonical = path.canonicalize().map_err(|e| {
debug!("Failed to canonicalize {}: {}", path.display(), e);
Error::InvalidPath {
path: path.to_path_buf(),
}
})?;
debug_assert!(
canonical.is_absolute(),
"Canonicalized path must be absolute"
);
// Security: Prevent path traversal attacks
// Ensures canonical path is within the project root
if !fs_utils::is_canonical_within_root(&canonical, canonical_root) {
warn!(
"Rejecting path outside project root: {} (root: {})",
canonical.display(),
canonical_root.display()
);
return Err(Error::InvalidPath {
path: path.to_path_buf(),
});
}
Ok(canonical)
}
/// Recursively walk a directory and collect file entries
///
/// Applies the same filters as `DirectoryWalker` via
/// [`configured_walk_builder`]:
/// - Dotfile filtering (based on config)
/// - Gitignore rules
/// - Custom ignore patterns
/// - Directory/file patterns
/// - Output file protection (inode match + recently-created heuristic)
///
/// Collection is capped at `max_files` to prevent unbounded memory
/// growth when a directory argument contains a very large tree.
///
/// # Arguments
///
/// * `dir_path` - Canonical path to directory
/// * `canonical_root` - Original root for relative path calculation
/// * `config` - Configuration with filter settings
/// * `stdout_identity` - Pre-computed stdout identity for output protection
/// * `max_files` - Maximum file entries to collect from this directory
///
/// # Returns
///
/// Vector of `WalkerItem` entries (files and any errors encountered)
fn process_directory(
dir_path: &Path,
canonical_root: &Path,
config: &Config,
stdout_identity: Option<&FileIdentity>,
max_files: usize,
) -> Vec<WalkerItem> {
debug_assert!(dir_path.is_absolute(), "Directory path must be absolute");
debug_assert!(
canonical_root.is_absolute(),
"Canonical root must be absolute"
);
let builder = configured_walk_builder(dir_path, config);
// Get output protection threshold once
let output_threshold = output_protection_threshold();
// Walk directory and collect entries, bounded by max_files
let mut entries = Vec::new();
let mut file_count: usize = 0;
for entry_result in builder.build() {
let entry = match entry_result {
Ok(e) => e,
Err(e) => {
// Non-fatal: log and continue
warn!("Directory walk error in {}: {}", dir_path.display(), e);
entries.push(WalkerItem::Error(Error::Walker {
message: format!("Directory walk error: {e}"),
}));
continue;
}
};
let file_type = entry.file_type();
let is_file = file_type.is_some_and(|ft| ft.is_file());
// Only process files (skip directories)
if !is_file {
continue;
}
// Enforce file cap to prevent unbounded collection
if file_count >= max_files {
debug!(
"Reached file budget ({max_files}) during directory \
expansion of {}",
dir_path.display()
);
break;
}
// Output file protection: skip files that match stdout
// identity (inode-based). Mirrors DirectoryWalker's check.
if let Some(stdout_id) = stdout_identity {
match entry.metadata() {
Ok(metadata) => {
if output_guard::matches_stdout(entry.path(), &metadata, stdout_id) {
continue;
}
}
Err(e) => {
debug!(
"Failed to get metadata for {}: {}",
entry.path().display(),
e
);
}
}
}
// Output file protection: skip empty files created recently
// (heuristic for shell redirection protection)
if let Ok(metadata) = entry.metadata() {
if output_guard::is_recently_created_empty(
entry.path(),
&metadata,
output_threshold,
) {
continue;
}
}
let path = entry.path().to_path_buf();
// Calculate relative path from ORIGINAL root, not directory root
// This ensures paths are displayed relative to CWD, not the subdirectory
let relative_path = path
.strip_prefix(canonical_root)
.unwrap_or(&path)
.to_path_buf();
entries.push(WalkerItem::Entry(WalkerEntry {
path,
relative_path,
is_dir: false,
}));
file_count += 1;
}
debug!(
"Collected {} entries from directory {}",
entries.len(),
dir_path.display()
);
entries
}
}
impl Iterator for FileListWalker {
type Item = WalkerItem;
fn next(&mut self) -> Option<Self::Item> {
self.entries.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.entries.size_hint()
}
}
impl ExactSizeIterator for FileListWalker {
fn len(&self) -> usize {
self.entries.len()
}
}
impl std::iter::FusedIterator for FileListWalker {}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use serial_test::serial;
use std::fs;
use tempfile::TempDir;
fn create_test_file(dir: &TempDir, name: &str) -> PathBuf {
let path = dir.path().join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(&path, "test content").unwrap();
// Canonicalize to ensure path consistency across symlinks (e.g. macOS /tmp)
path.canonicalize().unwrap()
}
fn create_test_dir(dir: &TempDir, name: &str) -> PathBuf {
let path = dir.path().join(name);
fs::create_dir_all(&path).unwrap();
path.canonicalize().unwrap()
}
#[test]
#[serial]
fn test_file_list_walker_empty() {
let temp = TempDir::new().unwrap();
let config = Config::new_for_test(temp.path().to_path_buf());
let walker = FileListWalker::new(&[], &config).unwrap();
assert_eq!(walker.len(), 0);
assert_eq!(walker.count(), 0);
}
#[test]
#[serial]
fn test_file_list_walker_single_file() {
let temp = TempDir::new().unwrap();
// Robustness: Canonicalize root first to avoid symlink inconsistencies (macOS /var -> /private/var)
let root_path = temp.path().canonicalize().unwrap();
let file_path = root_path.join("test.txt");
fs::write(&file_path, "test content").unwrap();
// Create config with canonical root
let config = Config::new_for_test(root_path);
let walker = FileListWalker::new(std::slice::from_ref(&file_path), &config).unwrap();
assert_eq!(walker.len(), 1);
// Verify the entry has is_dir = false
let entries: Vec<_> = walker.collect();
assert_eq!(entries.len(), 1);
match &entries[0] {
WalkerItem::Entry(entry) => assert!(!entry.is_dir),
WalkerItem::Error(_) => panic!("Expected Entry, got Error"),
}
}
#[test]
#[serial]
fn test_file_list_walker_single_directory() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create directory with some files
let dir_path = create_test_dir(&temp, "subdir");
let _ = create_test_file(&temp, "subdir/file1.txt");
let _ = create_test_file(&temp, "subdir/file2.txt");
let config = Config::new_for_test(root_path);
let walker = FileListWalker::new(std::slice::from_ref(&dir_path), &config).unwrap();
// Should collect all files from directory
let entries: Vec<_> = walker.collect();
assert_eq!(
entries.len(),
2,
"Directory should expand to its file contents"
);
// Verify all entries are files (not directories)
for entry in &entries {
match entry {
WalkerItem::Entry(e) => {
assert!(!e.is_dir, "Directory walker should only yield files");
assert!(
e.relative_path.starts_with("subdir"),
"Relative path should be from original root: {:?}",
e.relative_path
);
}
WalkerItem::Error(_) => panic!("Unexpected error entry"),
}
}
}
#[test]
#[serial]
fn test_file_list_walker_mixed_files_and_directories() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create mixed structure
let file1 = create_test_file(&temp, "file1.txt");
let dir1 = create_test_dir(&temp, "dir1");
let _ = create_test_file(&temp, "dir1/file2.txt");
let _ = create_test_file(&temp, "dir1/file3.txt");
let file4 = create_test_file(&temp, "file4.txt");
let config = Config::new_for_test(root_path);
let paths = vec![file1, dir1, file4];
let walker = FileListWalker::new(&paths, &config).unwrap();
// Should have: file1 + (file2, file3 from dir1) + file4 = 4 files
let entries: Vec<_> = walker.collect();
assert_eq!(
entries.len(),
4,
"Should process files and directory contents"
);
// Verify all are files
for entry in &entries {
match entry {
WalkerItem::Entry(e) => assert!(!e.is_dir),
WalkerItem::Error(_) => panic!("Unexpected error entry"),
}
}
}
#[test]
#[serial]
fn test_file_list_walker_nested_directories() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create nested structure
let _ = create_test_file(&temp, "a/b/c/file.txt");
let _ = create_test_file(&temp, "a/b/file2.txt");
let _ = create_test_file(&temp, "a/file3.txt");
let dir_a = root_path.join("a");
let config = Config::new_for_test(root_path);
let walker = FileListWalker::new(std::slice::from_ref(&dir_a), &config).unwrap();
let entries: Vec<_> = walker.collect();
assert_eq!(
entries.len(),
3,
"Should recursively walk nested directories"
);
// Verify relative paths are correct
let paths: Vec<_> = entries
.iter()
.filter_map(|item| match item {
WalkerItem::Entry(e) => Some(e.relative_path.to_str().unwrap()),
WalkerItem::Error(_) => None,
})
.collect();
assert!(
paths.iter().any(|p| p.contains("a/b/c/file.txt")),
"Should find deeply nested file"
);
}
#[test]
fn test_validate_nonexistent_file() {
let temp = TempDir::new().unwrap();
let path = PathBuf::from("/nonexistent/file.txt");
let canonical_root = temp.path().canonicalize().unwrap();
assert!(FileListWalker::validate_path(&path, &canonical_root).is_err());
}
#[test]
fn test_path_traversal_prevention() {
let temp = TempDir::new().unwrap();
// Create a file outside the temp directory
let outside_dir = TempDir::new().unwrap();
let outside_file = create_test_file(&outside_dir, "outside.txt");
let canonical_root = temp.path().canonicalize().unwrap();
// Try to validate a file outside the root - should fail
let result = FileListWalker::validate_path(&outside_file, &canonical_root);
assert!(result.is_err());
}
#[test]
fn test_file_within_root_succeeds() {
let temp = TempDir::new().unwrap();
let inside_file = create_test_file(&temp, "inside.txt");
let canonical_root = temp.path().canonicalize().unwrap();
// File within root should succeed
let result = FileListWalker::validate_path(&inside_file, &canonical_root);
assert!(result.is_ok());
}
#[test]
fn test_directory_within_root_succeeds() {
let temp = TempDir::new().unwrap();
let inside_dir = create_test_dir(&temp, "inside_dir");
let canonical_root = temp.path().canonicalize().unwrap();
// Directory within root should succeed
let result = FileListWalker::validate_path(&inside_dir, &canonical_root);
assert!(result.is_ok());
}
#[cfg(unix)]
#[test]
fn test_symlink_escape_prevented() {
// Test that symlinks pointing outside the root are rejected
let temp = TempDir::new().unwrap();
let outside = TempDir::new().unwrap();
let outside_file = create_test_file(&outside, "secret.txt");
// Create symlink inside temp pointing to outside file
let symlink = temp.path().join("link.txt");
std::os::unix::fs::symlink(&outside_file, &symlink).unwrap();
let canonical_root = temp.path().canonicalize().unwrap();
// Try to validate the symlink - should fail because it resolves outside root
let result = FileListWalker::validate_path(&symlink, &canonical_root);
assert!(
result.is_err(),
"Symlink to file outside root should be rejected"
);
}
#[test]
#[serial]
fn test_canonical_root_cached() {
// Verify that canonical_root is computed once during construction
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
let file_path = root_path.join("test.txt");
fs::write(&file_path, "test content").unwrap();
let config = Config::new_for_test(root_path);
// Construction should succeed without re-canonicalizing root for each file
let walker = FileListWalker::new(std::slice::from_ref(&file_path), &config);
assert!(walker.is_ok());
}
#[test]
#[serial]
fn test_all_files_invalid_returns_error() {
// When all paths are invalid, should return AllFilesInvalid error
let temp = TempDir::new().unwrap();
let config = Config::new_for_test(temp.path().to_path_buf());
let invalid_files = vec![
PathBuf::from("/nonexistent1.txt"),
PathBuf::from("/nonexistent2.txt"),
];
let result = FileListWalker::new(&invalid_files, &config);
assert!(result.is_err());
if let Err(Error::AllFilesInvalid { count }) = result {
assert_eq!(count, 2);
} else {
panic!("Expected AllFilesInvalid error");
}
}
#[test]
#[serial]
fn test_partial_validation_success() {
// When some paths are valid and some invalid, should succeed with valid ones
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
let valid_file = root_path.join("valid.txt");
fs::write(&valid_file, "test content").unwrap();
let config = Config::new_for_test(root_path);
let mixed_files = vec![valid_file, PathBuf::from("/nonexistent.txt")];
let walker = FileListWalker::new(&mixed_files, &config).unwrap();
assert_eq!(walker.len(), 1); // Only valid file remains
}
#[test]
#[serial]
fn test_zero_copy_iteration() {
// Verify that iteration doesn't clone PathBufs
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
let file_path = root_path.join("test.txt");
fs::write(&file_path, "test content").unwrap();
let config = Config::new_for_test(root_path);
let walker = FileListWalker::new(std::slice::from_ref(&file_path), &config).unwrap();
// Consuming the walker should move values, not clone
let entries: Vec<_> = walker.collect();
assert_eq!(entries.len(), 1);
}
#[test]
#[serial]
fn test_directory_respects_gitignore() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create .gitignore
fs::write(root_path.join(".gitignore"), "ignored.txt\n").unwrap();
// Create files
let _ = create_test_file(&temp, "included.txt");
let _ = create_test_file(&temp, "ignored.txt");
let config = Config::new_for_test(root_path.clone());
let walker = FileListWalker::new(std::slice::from_ref(&root_path), &config).unwrap();
let entries: Vec<_> = walker.collect();
// Should only find non-ignored files
let file_names: Vec<_> = entries
.iter()
.filter_map(|item| match item {
WalkerItem::Entry(e) => e.path.file_name().and_then(|n| n.to_str()),
WalkerItem::Error(_) => None,
})
.collect();
assert!(
file_names.contains(&"included.txt"),
"Should include non-ignored files"
);
assert!(
!file_names.contains(&"ignored.txt"),
"Should respect gitignore"
);
}
#[test]
#[serial]
fn test_relative_paths_from_original_root() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create nested structure
let _ = create_test_file(&temp, "a/b/file.txt");
let dir_b = root_path.join("a/b");
let config = Config::new_for_test(root_path);
// Walk subdirectory
let walker = FileListWalker::new(std::slice::from_ref(&dir_b), &config).unwrap();
let entries: Vec<_> = walker.collect();
assert_eq!(entries.len(), 1);
match &entries[0] {
WalkerItem::Entry(e) => {
// Relative path should be from ORIGINAL root, not subdirectory
assert!(
e.relative_path.starts_with("a/b"),
"Relative path should be from original root, got: {:?}",
e.relative_path
);
}
WalkerItem::Error(_) => panic!("Unexpected error"),
}
}
#[test]
#[serial]
fn test_process_directory_never_returns_error() {
// Verify that process_directory collects errors into the result vector
// instead of returning Err. This is a regression test for the fix.
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
// Create a valid directory
let dir_path = create_test_dir(&temp, "test_dir");
let _ = create_test_file(&temp, "test_dir/file.txt");
let config = Config::new_for_test(root_path.clone());
// Call process_directory directly - should return Vec, not Result
let entries = FileListWalker::process_directory(&dir_path, &root_path, &config, None, 1);
// Should be a Vec with entries
assert!(!entries.is_empty(), "Should return entries");
// Verify at least one entry is a file
let has_file_entry = entries
.iter()
.any(|item| matches!(item, WalkerItem::Entry(e) if !e.is_dir));
assert!(has_file_entry, "Should contain at least one file entry");
}
#[test]
#[serial]
fn test_fused_iterator_returns_none_after_exhaustion() {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
let file_path = root_path.join("test.txt");
fs::write(&file_path, "test content").unwrap();
let config = Config::new_for_test(root_path);
let mut walker = FileListWalker::new(std::slice::from_ref(&file_path), &config).unwrap();
// Exhaust the iterator
while walker.next().is_some() {}
// FusedIterator contract: subsequent calls must return None
assert!(walker.next().is_none());
assert!(walker.next().is_none());
}
proptest! {
#[test]
#[serial]
fn test_walker_size_hint_consistent(count in 0usize..50) {
let temp = TempDir::new().unwrap();
let root_path = temp.path().canonicalize().unwrap();
let files: Vec<PathBuf> = (0..count)
.map(|i| {
let p = root_path.join(format!("file_{i}.txt"));
fs::write(&p, "content").unwrap();
p
})
.collect();
let config = Config::new_for_test(root_path);
let walker = FileListWalker::new(&files, &config).unwrap();
let (lower, upper) = walker.size_hint();
assert_eq!(lower, count);
assert_eq!(upper, Some(count));
}
}
}