luff 0.2.1

Print files with formatting
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
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! Directory walking implementation with streaming semantics

use crate::walker::WalkerItem;
use crate::{
    config::Config,
    error::{Error, Result},
    fs_utils::security::{FileIdentity, get_stdout_identity, output_protection_threshold},
    walker::WalkerEntry,
};
use log::debug;
use std::path::PathBuf;

use super::builder::configured_walk_builder;
use super::output_guard;

/// Minimum total entries safety cap.
///
/// Even with a very small `max_files` (e.g., 1), we allow at least this many
/// total entries (files + directories) before hard-stopping. This ensures
/// directory-heavy trees can still yield meaningful structure for tree output.
const TOTAL_ENTRIES_MINIMUM: usize = 10_000;

/// Safety multiplier for total entries cap.
///
/// The total entries cap is `max(max_files * SAFETY_FACTOR, MINIMUM)`.
/// A factor of 2 means we allow roughly as many directory entries as file
/// entries, which is generous for all practical directory structures.
const TOTAL_ENTRIES_SAFETY_FACTOR: usize = 2;

/// Directory tree walker with lazy streaming semantics
///
/// This walker processes files on-demand during iteration, maintaining
/// O(1) memory footprint regardless of directory size. It preserves
/// all security guarantees through per-entry validation.
///
/// # Limiting Behavior
///
/// Two limits control iteration:
///
/// - **`max_files`** (user-configurable): Caps the number of *file* entries
///   yielded. Directory entries are not subject to this limit, because they
///   provide structural context needed for tree output.
///
/// - **`max_total_entries`** (internal safety): Caps the total number of
///   entries (files + directories) to prevent pathological directory
///   structures from causing unbounded memory growth in downstream
///   consumers that buffer entries. Set generously to be invisible in
///   normal use.
///
/// # Fused Iterator
///
/// This iterator is fused: once `next()` returns `None`, all subsequent
/// calls will also return `None`. This is guaranteed by the
/// [`FusedIterator`] impl.
pub struct DirectoryWalker {
    /// Underlying ignore crate walker (lazy by nature)
    inner: ignore::Walk,

    /// Root directory for relative path calculation
    root: PathBuf,

    /// Pre-computed stdout identity for output file detection
    stdout_identity: Option<FileIdentity>,

    /// Maximum files to process for sanity checking
    max_files: usize,

    /// Current count of processed files (files only, not directories)
    processed_count: usize,

    /// Total entries yielded (files + directories) for safety cap
    total_yielded: usize,

    /// Internal safety cap on total entries (files + directories)
    ///
    /// Prevents pathological directory structures from causing OOM in
    /// downstream consumers that buffer entries. Computed as
    /// `max(max_files * 2, 10_000)`.
    max_total_entries: usize,

    /// Track if we've warned about `max_files` limit
    max_files_warned: bool,

    /// Track if we've warned about `max_total_entries` limit
    max_total_warned: bool,

    /// Output protection threshold (cached to avoid repeated env var reads)
    output_threshold: std::time::Duration,
}

impl DirectoryWalker {
    /// Create a new directory walker with streaming semantics
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration specifying root path, filters, and options
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration cannot be used to initialize
    /// the walker (e.g., invalid root path).
    ///
    /// # Performance
    ///
    /// Construction is O(1) - no directory traversal occurs until iteration begins.
    /// This enables processing of arbitrarily large directories without memory overhead.
    ///
    /// # Security
    ///
    /// All security checks (output file detection, path validation) occur per-entry
    /// during iteration, providing the same guarantees as upfront collection.
    pub fn new(config: &Config) -> Result<Self> {
        debug_assert!(
            config.root().is_absolute(),
            "Config root must be absolute path"
        );

        let builder = configured_walk_builder(config.root(), config);

        // Get stdout identity once for all checks
        let stdout_identity = get_stdout_identity();

        let max_files = config.max_files();

        // Compute internal safety cap: generous enough for normal use,
        // bounded enough to prevent pathological OOM.
        let max_total_entries = max_files
            .saturating_mul(TOTAL_ENTRIES_SAFETY_FACTOR)
            .max(TOTAL_ENTRIES_MINIMUM);

        Ok(Self {
            inner: builder.build(),
            root: config.root().to_path_buf(),
            stdout_identity,
            max_files,
            processed_count: 0,
            total_yielded: 0,
            max_total_entries,
            max_files_warned: false,
            max_total_warned: false,
            output_threshold: output_protection_threshold(),
        })
    }

    /// Get the current count of processed files
    ///
    /// This is useful for testing and debugging to verify the walker
    /// is correctly tracking file counts.
    #[cfg(test)]
    #[must_use]
    pub const fn processed_count(&self) -> usize {
        self.processed_count
    }

    /// Get the total count of yielded entries (files + directories)
    #[cfg(test)]
    #[must_use]
    pub const fn total_yielded(&self) -> usize {
        self.total_yielded
    }

    /// Emit a one-time warning when the `max_files` limit is reached.
    fn warn_max_files_once(&mut self) {
        if !self.max_files_warned {
            self.max_files_warned = true;
            eprintln!(
                "\nâš  Warning: Reached maximum file limit ({} files)",
                self.max_files
            );
            eprintln!("  Remaining files will be skipped.");
            eprintln!(
                "  Consider using --max-files, --max-depth, \
                 or more specific patterns.\n"
            );
        }
    }

    /// Emit a one-time warning when the total entries safety cap is reached.
    fn warn_max_total_once(&mut self) {
        if !self.max_total_warned {
            self.max_total_warned = true;
            eprintln!(
                "\nâš  Warning: Reached total entry safety limit ({} entries)",
                self.max_total_entries
            );
            eprintln!(
                "  This typically indicates an unusually large \
                 directory structure."
            );
            eprintln!(
                "  Consider using --max-depth or more specific \
                 patterns to narrow the scope.\n"
            );
        }
    }
}

impl Iterator for DirectoryWalker {
    type Item = crate::walker::WalkerItem;

    fn next(&mut self) -> Option<Self::Item> {
        // Hard stop: total entries safety cap (files + directories).
        // This prevents pathological directory structures from causing
        // unbounded memory growth in downstream consumers that buffer
        // entries.
        //
        // This is the sole enforcement point: `total_yielded` is only
        // incremented immediately before `return Some(…)` below, so on
        // re-entry this check sees the updated value. No inner-loop
        // guard is needed because the field is not modified elsewhere
        // within `next()`.
        if self.total_yielded >= self.max_total_entries {
            self.warn_max_total_once();
            return None;
        }

        // Use `while let` instead of `for … in &mut self.inner` so the
        // mutable borrow on `self.inner` is limited to the `.next()` call.
        // This allows `&mut self` method calls (warnings, counters) in the
        // loop body without conflicting borrows.
        while let Some(entry_result) = self.inner.next() {
            let entry = match entry_result {
                Ok(e) => e,
                Err(e) => {
                    return Some(WalkerItem::Error(Error::Walker {
                        message: format!("Directory walk error: {e}"),
                    }));
                }
            };

            let file_type = entry.file_type();
            let is_file = file_type.is_some_and(|ft| ft.is_file());
            let is_dir = file_type.is_some_and(|ft| ft.is_dir());

            // Skip non-file/non-directory entries
            if !is_file && !is_dir {
                continue;
            }

            // Skip the root directory itself — it is the traversal starting
            // point, not a discovered entry.  The `ignore` crate always
            // yields the root as its first item; emitting it would produce a
            // `WalkerEntry` with an empty relative path, which is
            // meaningless to every downstream consumer (tree output,
            // markdown, clipboard).
            if entry.path() == self.root {
                debug!("Skipping root directory entry: {}", entry.path().display());
                continue;
            }

            // For files: enforce max_files limit and output protection.
            // Directories are never subject to the file limit — they are
            // structural entries needed for tree output and don't represent
            // file content to process.
            if is_file {
                // Soft stop: skip this file but keep iterating so that
                // directory entries can still be yielded for tree
                // structure.
                if self.processed_count >= self.max_files {
                    self.warn_max_files_once();
                    continue;
                }

                // Output file protection: skip files that match stdout
                // identity
                if let Some(ref stdout_id) = self.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
                            );
                        }
                    }
                }

                // Heuristic: skip recently-created empty files that may
                // be the output destination (not yet written to).
                if let Ok(metadata) = entry.metadata() {
                    if output_guard::is_recently_created_empty(
                        entry.path(),
                        &metadata,
                        self.output_threshold,
                    ) {
                        continue;
                    }
                }

                self.processed_count += 1;
            }

            let path = entry.path().to_path_buf();
            let relative_path = path.strip_prefix(&self.root).unwrap_or(&path).to_path_buf();

            self.total_yielded += 1;

            return Some(WalkerItem::Entry(WalkerEntry {
                path,
                relative_path,
                is_dir,
            }));
        }

        None
    }

    /// Note: This walker does NOT implement `ExactSizeIterator` because the
    /// total number of entries is unknown until traversal completes.
    /// The `size_hint` returns conservative bounds. The upper bound
    /// reflects the internal total entries safety cap minus entries
    /// already yielded.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (
            0,
            Some(self.max_total_entries.saturating_sub(self.total_yielded)),
        )
    }
}

// SAFETY (logical): Once the inner `ignore::Walk` iterator is exhausted it
// permanently returns `None`.  The `total_yielded >= max_total_entries`
// guard is also monotonic.  Therefore this iterator is fused.
impl std::iter::FusedIterator for DirectoryWalker {}

// All tests in this module require CLI infrastructure (Args, clap,
// Config::from_args) for constructing realistic Config values. Gate the
// entire block behind the `cli` feature so that `cargo test --no-default-features --features wasm`
// compiles cleanly.
#[cfg(test)]
#[cfg(feature = "cli")]
mod tests {
    use super::*;
    use crate::{cli::Args, config::Config};
    use clap::Parser;
    use proptest::prelude::*;
    use serial_test::serial;
    use std::fs;
    use tempfile::TempDir;

    proptest! {
        /// Property: Walker should never yield more file entries than
        /// max_files
        #[test]
        #[serial]
        fn prop_never_exceeds_max_files(
            max_files in 1usize..20,
            num_files in 10usize..30
        ) {
            let temp = TempDir::new().unwrap();
            std::env::set_current_dir(temp.path()).unwrap();

            for i in 0..num_files {
                fs::write(
                    temp.path().join(format!("file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from([
                "test", "--max-files", &max_files.to_string(),
            ]);
            let config = Config::from_args(&args).unwrap();

            let walker = DirectoryWalker::new(&config).unwrap();

            let file_count = walker
                .filter_map(WalkerItem::into_entry)
                .filter(|entry| !entry.is_dir)
                .count();

            assert!(
                file_count <= max_files,
                "Walker yielded {file_count} files but max_files \
                 is {max_files}"
            );
        }

        /// Property: Size hint upper bound should always be >= actual
        /// remaining count
        #[test]
        #[serial]
        fn prop_size_hint_upper_bound_valid(num_files in 1usize..20) {
            let temp = TempDir::new().unwrap();
            std::env::set_current_dir(temp.path()).unwrap();

            for i in 0..num_files {
                fs::write(
                    temp.path().join(format!("file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from(["test"]);
            let config = Config::from_args(&args).unwrap();

            let mut walker = DirectoryWalker::new(&config).unwrap();

            let (lower, upper) = walker.size_hint();
            assert_eq!(lower, 0, "Lower bound should be 0 (unknown)");
            assert!(upper.is_some(), "Upper bound should be Some");

            let initial_upper = upper.unwrap();
            let _ = walker.next();
            let (_, upper_after) = walker.size_hint();

            if let Some(upper_val) = upper_after {
                assert!(
                    upper_val <= initial_upper,
                    "Upper bound should not increase after consuming \
                     items"
                );
            }
        }

        /// Property: All relative paths should be relative to root
        #[test]
        #[serial]
        fn prop_relative_paths_start_from_root(
            num_files in 1usize..10
        ) {
            let temp = TempDir::new().unwrap();
            let root = temp.path().canonicalize().unwrap();
            std::env::set_current_dir(&root).unwrap();

            fs::create_dir_all(root.join("a/b/c")).unwrap();
            for i in 0..num_files {
                fs::write(
                    root.join(format!("a/b/c/file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from(["test"]);
            let config = Config::from_args(&args).unwrap();

            let walker = DirectoryWalker::new(&config).unwrap();

            for item in walker {
                if let Some(entry) = item.into_entry() {
                    assert!(
                        entry.relative_path.is_relative(),
                        "Relative path should be relative, got: {:?}",
                        entry.relative_path
                    );

                    assert!(
                        !entry.relative_path.as_os_str().is_empty(),
                        "Relative path should not be empty (root entry \
                         should be skipped), got entry: {:?}",
                        entry.path
                    );

                    assert!(
                        entry.path.is_absolute(),
                        "Absolute path should be absolute, got: {:?}",
                        entry.path
                    );
                }
            }
        }

        /// Property: Directories should NOT count toward max_files limit
        #[test]
        #[serial]
        fn prop_directories_dont_count_toward_limit(
            max_files in 1usize..5,
            num_dirs in 5usize..10
        ) {
            let temp = TempDir::new().unwrap();
            std::env::set_current_dir(temp.path()).unwrap();

            for i in 0..num_dirs {
                fs::create_dir_all(
                    temp.path().join(format!("dir_{i}")),
                ).unwrap();
            }

            for i in 0..max_files {
                fs::write(
                    temp.path().join(format!("file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from([
                "test", "--max-files", &max_files.to_string(),
            ]);
            let config = Config::from_args(&args).unwrap();

            let mut walker = DirectoryWalker::new(&config).unwrap();

            let mut file_count = 0;
            let mut dir_count = 0;

            for item in &mut walker {
                if let Some(entry) = item.into_entry() {
                    if entry.is_dir {
                        dir_count += 1;
                    } else {
                        file_count += 1;
                    }
                }
            }

            assert_eq!(
                file_count, max_files,
                "Should process exactly max_files files"
            );
            assert!(
                dir_count > 0,
                "Should process directories without counting them"
            );
        }

        /// Property: Walker should never yield the root directory itself
        #[test]
        #[serial]
        fn prop_never_yields_root_entry(
            num_files in 0usize..10,
            num_dirs in 0usize..5
        ) {
            let temp = TempDir::new().unwrap();
            let root = temp.path().canonicalize().unwrap();
            std::env::set_current_dir(&root).unwrap();

            for i in 0..num_dirs {
                fs::create_dir_all(
                    root.join(format!("dir_{i}")),
                ).unwrap();
            }
            for i in 0..num_files {
                fs::write(
                    root.join(format!("file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from(["test"]);
            let config = Config::from_args(&args).unwrap();

            let walker = DirectoryWalker::new(&config).unwrap();

            for item in walker {
                if let Some(entry) = item.into_entry() {
                    assert_ne!(
                        entry.path, root,
                        "Walker should never yield the root directory \
                         itself"
                    );
                    assert!(
                        !entry.relative_path.as_os_str().is_empty(),
                        "Walker should never yield an entry with an \
                         empty relative path"
                    );
                }
            }
        }

        #[test]
        #[serial]
        fn prop_total_entries_bounded(
            max_files in 1usize..10,
            num_files in 5usize..20,
            num_dirs in 5usize..20
        ) {
            let temp = TempDir::new().unwrap();
            std::env::set_current_dir(temp.path()).unwrap();

            for i in 0..num_dirs {
                fs::create_dir_all(
                    temp.path().join(format!("dir_{i}")),
                ).unwrap();
            }
            for i in 0..num_files {
                fs::write(
                    temp.path().join(format!("file_{i}.txt")),
                    "content",
                ).unwrap();
            }

            let args = Args::parse_from([
                "test", "--max-files", &max_files.to_string(),
            ]);
            let config = Config::from_args(&args).unwrap();

            let mut walker = DirectoryWalker::new(&config).unwrap();
            let max_total = walker.max_total_entries;

            let mut total_count = 0;
            for item in &mut walker {
                if item.into_entry().is_some() {
                    total_count += 1;
                }
            }

            assert!(
                total_count <= max_total,
                "Total entries ({total_count}) should not exceed \
                 safety cap ({max_total})"
            );
            assert_eq!(
                walker.total_yielded(),
                total_count,
                "Internal counter should match actual yielded count"
            );
        }
    }

    #[test]
    #[serial]
    fn test_directory_walker_creation() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();
        assert_eq!(walker.max_files, 1_000_000);
        assert!(!walker.max_files_warned);
        assert!(!walker.max_total_warned);
        assert_eq!(walker.processed_count(), 0);
        assert_eq!(walker.total_yielded(), 0);
    }

    #[test]
    #[serial]
    fn test_max_files_one_sets_warned_flag() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        // Create two files so the walker hits the limit after processing
        // the first and encounters the second.
        fs::write(temp.path().join("first.txt"), "content").unwrap();
        fs::write(temp.path().join("second.txt"), "content").unwrap();

        let args = Args::parse_from(["test", "--max-files", "1"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&config).unwrap();
        assert!(!walker.max_files_warned);

        // Exhaust the walker — the second file should be skipped and the
        // warning flag set.
        let entries: Vec<_> = walker.by_ref().filter_map(WalkerItem::into_entry).collect();

        let file_count = entries.iter().filter(|e| !e.is_dir).count();
        assert_eq!(file_count, 1, "max_files=1 should yield exactly one file");

        assert!(
            walker.max_files_warned,
            "max_files_warned should be true when max_files is 1 and \
             a second file was encountered"
        );
    }

    #[test]
    #[serial]
    fn test_max_files_optimization_skips_iterator() {
        let temp = TempDir::new().unwrap();

        fs::create_dir_all(temp.path().join("a/b/c")).unwrap();
        fs::write(temp.path().join("a/file1.txt"), "1").unwrap();
        fs::write(temp.path().join("a/b/file2.txt"), "2").unwrap();
        fs::write(temp.path().join("a/b/c/file3.txt"), "3").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["bench", "--max-files", "1"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&config).unwrap();

        // Consume entries until we've processed the file limit
        let mut file_count = 0;
        while let Some(item) = walker.next() {
            if let Some(entry) = item.into_entry() {
                if !entry.is_dir {
                    file_count += 1;
                }
            }
            if walker.processed_count() >= walker.max_files {
                break;
            }
        }

        assert_eq!(walker.processed_count(), 1);
        assert_eq!(file_count, 1);

        // Remaining items should only be directories (files are skipped)
        let remaining: Vec<_> = walker.by_ref().filter_map(WalkerItem::into_entry).collect();
        let remaining_files = remaining.iter().filter(|e| !e.is_dir).count();
        assert_eq!(
            remaining_files, 0,
            "No more files should be yielded after the limit"
        );
    }

    #[test]
    #[serial]
    fn test_processed_count_increases_only_for_files() {
        let temp = TempDir::new().unwrap();

        fs::create_dir_all(temp.path().join("dir1/dir2")).unwrap();
        fs::write(temp.path().join("dir1/file1.txt"), "content").unwrap();
        fs::write(temp.path().join("dir1/dir2/file2.txt"), "content").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&config).unwrap();

        let mut file_entries = 0;
        let mut dir_entries = 0;

        for item in &mut walker {
            if let Some(entry) = item.into_entry() {
                if entry.is_dir {
                    dir_entries += 1;
                } else {
                    file_entries += 1;
                }
            }
        }

        assert_eq!(walker.processed_count(), file_entries);
        assert_eq!(
            walker.processed_count(),
            2,
            "Should have processed exactly 2 files"
        );
        assert!(dir_entries > 0, "Should have encountered directories");
    }

    #[test]
    #[serial]
    fn test_size_hint_decreases_as_items_consumed() {
        let temp = TempDir::new().unwrap();
        fs::write(temp.path().join("file1.txt"), "content").unwrap();
        fs::write(temp.path().join("file2.txt"), "content").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test", "--max-files", "10"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&config).unwrap();

        let (_, upper1) = walker.size_hint();
        let _ = walker.next(); // Consume one item
        let (_, upper2) = walker.size_hint();

        assert!(upper1.is_some() && upper2.is_some());
        assert!(
            upper2.unwrap() <= upper1.unwrap(),
            "Upper bound should not increase after consuming items"
        );
    }

    #[test]
    #[serial]
    fn test_early_termination_on_max_files() {
        let temp = TempDir::new().unwrap();

        for i in 0..10 {
            fs::write(temp.path().join(format!("file_{i}.txt")), "content").unwrap();
        }

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test", "--max-files", "3"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();

        let file_count = walker
            .filter_map(WalkerItem::into_entry)
            .filter(|entry| !entry.is_dir)
            .count();

        assert_eq!(file_count, 3, "Should stop at max_files limit");
    }

    #[test]
    #[serial]
    fn test_walker_handles_empty_directory() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();
        let count = walker.count();

        assert_eq!(count, 0, "Empty directory should yield no entries");
    }

    #[test]
    #[serial]
    fn test_walker_skips_root_directory_entry() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        std::env::set_current_dir(&root).unwrap();

        fs::write(root.join("file.txt"), "content").unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();
        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();

        assert_eq!(entries.len(), 1, "Should yield exactly the one file");
        assert!(
            !entries[0].is_dir,
            "The single entry should be a file, not the root dir"
        );
        assert_eq!(
            entries[0].relative_path,
            PathBuf::from("file.txt"),
            "Relative path should be the filename"
        );
    }

    #[test]
    #[serial]
    fn test_walker_yields_subdirectories_but_not_root() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        std::env::set_current_dir(&root).unwrap();

        fs::create_dir_all(root.join("subdir")).unwrap();
        fs::write(root.join("subdir/file.txt"), "content").unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();
        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();

        let dir_entries: Vec<_> = entries.iter().filter(|e| e.is_dir).collect();
        let file_entries = entries.iter().filter(|e| !e.is_dir);

        assert_eq!(dir_entries.len(), 1, "Should yield one subdirectory");
        assert_eq!(
            dir_entries[0].relative_path,
            PathBuf::from("subdir"),
            "Subdirectory relative path should be 'subdir'"
        );

        assert_eq!(
            file_entries.filter(|e| !e.is_dir).count(),
            1,
            "Should yield one file"
        );

        for entry in &entries {
            assert_ne!(
                entry.path, root,
                "No entry should be the root directory itself"
            );
            assert!(
                !entry.relative_path.as_os_str().is_empty(),
                "No entry should have an empty relative path"
            );
        }
    }

    #[test]
    #[serial]
    fn test_walker_respects_dotfiles_setting() {
        let temp = TempDir::new().unwrap();
        fs::write(temp.path().join(".hidden"), "content").unwrap();
        fs::write(temp.path().join("visible.txt"), "content").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();

        // Test without dotfiles
        let args = Args::parse_from(["test", "--no-dotfiles"]);
        let config = Config::from_args(&args).unwrap();
        let walker = DirectoryWalker::new(&config).unwrap();

        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();
        let has_hidden = entries
            .iter()
            .any(|e| e.path.file_name().unwrap().to_str().unwrap() == ".hidden");

        assert!(!has_hidden, "Should not include hidden files");

        // Test with dotfiles
        let args = Args::parse_from(["test", "--dotfiles"]);
        let config = Config::from_args(&args).unwrap();
        let walker = DirectoryWalker::new(&config).unwrap();

        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();
        let has_hidden = entries
            .iter()
            .any(|e| e.path.file_name().unwrap().to_str().unwrap() == ".hidden");

        assert!(has_hidden, "Should include hidden files with --dotfiles");
    }

    #[test]
    #[serial]
    fn test_directories_yielded_after_file_limit() {
        let temp = TempDir::new().unwrap();

        for i in 0..5 {
            fs::create_dir_all(temp.path().join(format!("dir_{i}"))).unwrap();
        }
        for i in 0..5 {
            fs::write(temp.path().join(format!("file_{i}.txt")), "content").unwrap();
        }

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test", "--max-files", "1"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();

        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();

        let file_count = entries.iter().filter(|e| !e.is_dir).count();
        let dir_count = entries.iter().filter(|e| e.is_dir).count();

        assert_eq!(file_count, 1, "Should yield exactly max_files files");
        assert_eq!(
            dir_count, 5,
            "Should yield ALL directories regardless of file limit"
        );
    }

    #[test]
    #[serial]
    fn test_max_files_one_yields_one_file_plus_directories() {
        let temp = TempDir::new().unwrap();

        fs::create_dir_all(temp.path().join("dir1")).unwrap();
        fs::create_dir_all(temp.path().join("dir2")).unwrap();
        fs::write(temp.path().join("file.txt"), "content").unwrap();
        fs::write(temp.path().join("dir1/nested.txt"), "content").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test", "--max-files", "1"]);
        let config = Config::from_args(&args).unwrap();

        let walker = DirectoryWalker::new(&config).unwrap();
        let entries: Vec<_> = walker.filter_map(WalkerItem::into_entry).collect();

        let file_count = entries.iter().filter(|e| !e.is_dir).count();
        let dir_count = entries.iter().filter(|e| e.is_dir).count();

        assert_eq!(file_count, 1, "max_files=1 should yield exactly one file");
        assert_eq!(dir_count, 2, "Directories should still be yielded");
    }

    #[test]
    #[serial]
    fn test_max_files_rejects_zero() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let args = Args::parse_from(["test", "--max-files", "0"]);
        let result = Config::from_args(&args);

        assert!(
            result.is_err(),
            "max_files=0 should be rejected by validation"
        );
    }

    #[test]
    #[serial]
    fn test_total_yielded_tracks_both_files_and_dirs() {
        let temp = TempDir::new().unwrap();

        fs::create_dir_all(temp.path().join("dir1")).unwrap();
        fs::write(temp.path().join("file1.txt"), "content").unwrap();
        fs::write(temp.path().join("dir1/file2.txt"), "content").unwrap();

        std::env::set_current_dir(temp.path()).unwrap();
        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&config).unwrap();

        let mut count = 0;
        for item in &mut walker {
            if item.into_entry().is_some() {
                count += 1;
            }
        }

        assert_eq!(
            walker.total_yielded(),
            count,
            "total_yielded must equal actual entries yielded"
        );
        assert!(
            walker.total_yielded() >= walker.processed_count(),
            "total_yielded must be >= processed_count (files only)"
        );
    }

    #[test]
    #[serial]
    fn test_max_total_entries_computation() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        // Small max_files: safety cap should be TOTAL_ENTRIES_MINIMUM
        let args = Args::parse_from(["test", "--max-files", "1"]);
        let config = Config::from_args(&args).unwrap();
        let walker = DirectoryWalker::new(&config).unwrap();
        assert_eq!(
            walker.max_total_entries, TOTAL_ENTRIES_MINIMUM,
            "Small max_files should use TOTAL_ENTRIES_MINIMUM"
        );

        // Large max_files: safety cap should be max_files * factor
        let args = Args::parse_from(["test", "--max-files", "100000"]);
        let config = Config::from_args(&args).unwrap();
        let walker = DirectoryWalker::new(&config).unwrap();
        assert_eq!(
            walker.max_total_entries,
            100_000 * TOTAL_ENTRIES_SAFETY_FACTOR,
            "Large max_files should use max_files * safety factor"
        );
    }

    #[test]
    #[serial]
    fn test_warning_flags_initially_false() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();
        let walker = DirectoryWalker::new(&config).unwrap();

        assert!(!walker.max_files_warned);
        assert!(!walker.max_total_warned);
    }

    #[test]
    #[serial]
    fn test_fused_iterator_returns_none_after_exhaustion() {
        let temp = TempDir::new().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        fs::write(temp.path().join("file.txt"), "content").unwrap();

        let args = Args::parse_from(["test"]);
        let config = Config::from_args(&args).unwrap();

        let mut walker = DirectoryWalker::new(&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());
    }
}