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
//! Configuration file support with validation and precedence handling

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::io::Read;
use std::num::NonZeroUsize;
use std::path::Path;

use crate::error::ConfigError;
use crate::format::OutputFormat;

/// CLI-provided overrides that take precedence over config file values
///
/// All fields are optional — `None` means "use the value from the next
/// layer down" (env → config file → default).
#[non_exhaustive]
#[derive(Debug, Default, Clone)]
pub struct CliOverride {
    /// Output format override from CLI --format flag
    pub format: Option<OutputFormat>,
    /// Maximum clipboard size in MB from CLI --max-clipboard-mb flag
    pub max_clipboard_mb: Option<usize>,
    /// Maximum directory depth from CLI --max-depth flag
    pub max_depth: Option<usize>,
    /// Maximum files limit from CLI --max-files flag
    pub max_files: Option<usize>,
    /// Include hidden files and directories
    pub include_dotfiles: Option<bool>,
    /// Respect .gitignore patterns
    pub respect_gitignore: Option<bool>,
    /// Additional glob patterns to ignore
    pub ignore_globs: Option<Vec<String>>,
}

/// Configuration structure for YAML config files
///
/// All fields are optional to allow partial configs. Validation occurs
/// during conversion to [`ValidatedConfig`], ensuring type safety.
///
/// Unknown fields in the YAML source are **rejected** at parse time
/// (`deny_unknown_fields`) so that typos surface immediately instead of
/// being silently swallowed.
///
/// # Serde / `Default` coupling
///
/// The field-level `#[serde(default = "…")]` attributes **must** agree
/// with the `Default` impl.  Both are derived from the same helper
/// functions (`default_false`, `default_true`) to keep a single source
/// of truth.  If you add a new boolean field, follow the same pattern.
///
/// Construct via [`Default::default()`] and override individual fields:
///
/// ```
/// # use luff::config::ConfigFile;
/// let mut config = ConfigFile::default();
/// config.include_dotfiles = true;
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ConfigFile {
    /// Include dotfiles and hidden directories
    #[serde(default = "default_false")]
    pub include_dotfiles: bool,

    /// Respect .gitignore patterns
    #[serde(default = "default_true")]
    pub respect_gitignore: bool,

    /// Output format: "markdown" or "tree"
    #[serde(default)]
    pub format: Option<ConfigFormat>,

    /// Maximum directory depth (0 = unlimited, max: 100)
    #[serde(default)]
    pub max_depth: Option<usize>,

    /// Maximum number of files to collect during directory walk (1-10_000_000)
    #[serde(default)]
    pub max_files: Option<NonZeroUsize>,

    /// Maximum clipboard size in MB (0-1000)
    #[serde(default)]
    pub max_clipboard_mb: Option<usize>,

    /// Additional binary file extensions to ignore (e.g., "custom", "cache")
    #[serde(default)]
    pub ignore_extensions: Vec<String>,

    /// Directory names to always ignore (e.g., "`build_output`", "temp")
    #[serde(default)]
    pub ignore_directories: Vec<String>,

    /// Specific filenames to ignore (e.g., "secret.key")
    #[serde(default)]
    pub ignore_files: Vec<String>,

    /// Glob patterns to ignore (e.g., "src/**/*.test.rs")
    #[serde(default)]
    pub ignore_globs: Vec<String>,
}

impl Default for ConfigFile {
    fn default() -> Self {
        Self {
            include_dotfiles: default_false(),
            respect_gitignore: default_true(),
            format: None,
            max_depth: None,
            max_files: None,
            max_clipboard_mb: None,
            ignore_extensions: Vec::new(),
            ignore_directories: Vec::new(),
            ignore_files: Vec::new(),
            ignore_globs: Vec::new(),
        }
    }
}

/// Configuration file format enum
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ConfigFormat {
    /// Render output as Markdown fenced code blocks
    Markdown,
    /// Render output as a tree structure
    Tree,
}

impl From<ConfigFormat> for OutputFormat {
    fn from(fmt: ConfigFormat) -> Self {
        match fmt {
            ConfigFormat::Markdown => Self::Markdown,
            ConfigFormat::Tree => Self::Tree,
        }
    }
}

/// Upper bound for `max_depth` (inclusive).
const MAX_DEPTH_LIMIT: usize = 100;

/// Upper bound for `max_files` (inclusive).
const MAX_FILES_LIMIT: usize = 10_000_000;

/// Upper bound for `max_clipboard_mb` (inclusive).
const MAX_CLIPBOARD_LIMIT: usize = 1000;

impl ConfigFile {
    /// Validate and convert to [`ValidatedConfig`]
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] if validation fails.
    pub fn validate(&self, cli_override: &CliOverride) -> Result<ValidatedConfig, ConfigError> {
        // Step 1: Compute final values with precedence (CLI > Env > Config > Default)
        let format = cli_override
            .format
            .or_else(|| self.format.map(Into::into))
            .unwrap_or(OutputFormat::Markdown);

        let max_depth = cli_override.max_depth.or(self.max_depth).unwrap_or(0);

        let max_files = cli_override
            .max_files
            .or_else(|| self.max_files.map(NonZeroUsize::get))
            .unwrap_or(1_000_000);

        let max_clipboard_mb = cli_override
            .max_clipboard_mb
            .or(self.max_clipboard_mb)
            .unwrap_or(100);

        // For booleans, apply CLI override if present
        let include_dotfiles = cli_override
            .include_dotfiles
            .unwrap_or(self.include_dotfiles);
        let respect_gitignore = cli_override
            .respect_gitignore
            .unwrap_or(self.respect_gitignore);

        // Step 2: Validate the final computed values
        Self::validate_max_depth(max_depth)?;
        Self::validate_max_files(max_files)?;
        Self::validate_max_clipboard_mb(max_clipboard_mb)?;

        // Step 3: Merge CLI globs with config globs
        let mut ignore_globs = self.ignore_globs.clone();
        if let Some(cli_globs) = &cli_override.ignore_globs {
            ignore_globs.extend(cli_globs.iter().cloned());
        }

        // Step 4: Compile and validate patterns into efficient lookup structures.
        // All simple-pattern validation (empty strings, metacharacters, path
        // separators, leading dots) is handled inside IgnorePatterns::from_config.
        let patterns = crate::config::IgnorePatterns::from_config(
            &self.ignore_extensions,
            &self.ignore_directories,
            &self.ignore_files,
            &ignore_globs,
        )?;

        Ok(ValidatedConfig {
            include_dotfiles,
            respect_gitignore,
            format,
            max_depth,
            max_files,
            max_clipboard_mb,
            patterns,
        })
    }

    /// Validate `max_depth` (0-100)
    #[allow(clippy::missing_const_for_fn)]
    fn validate_max_depth(value: usize) -> Result<(), ConfigError> {
        if value > MAX_DEPTH_LIMIT {
            return Err(ConfigError::InvalidMaxDepth {
                value,
                max: MAX_DEPTH_LIMIT,
            });
        }
        Ok(())
    }

    /// Validate `max_files` (1-10_000_000)
    ///
    /// Rejects 0 because the config file side enforces `NonZeroUsize`, and
    /// the CLI side must maintain the same invariant. A `max_files` of 0
    /// would cause the walker to silently produce empty output.
    #[allow(clippy::missing_const_for_fn)]
    fn validate_max_files(value: usize) -> Result<(), ConfigError> {
        if value == 0 || value > MAX_FILES_LIMIT {
            return Err(ConfigError::InvalidMaxFiles {
                value,
                max: MAX_FILES_LIMIT,
            });
        }
        Ok(())
    }

    /// Validate `max_clipboard_mb` (0-1000)
    #[allow(clippy::missing_const_for_fn)]
    fn validate_max_clipboard_mb(value: usize) -> Result<(), ConfigError> {
        if value > MAX_CLIPBOARD_LIMIT {
            return Err(ConfigError::InvalidMaxClipboardMb {
                value,
                max: MAX_CLIPBOARD_LIMIT,
            });
        }
        Ok(())
    }
}

/// Validated configuration with all invariants enforced
///
/// Constructed exclusively through [`ConfigFile::validate`]. All fields
/// are private to prevent crate-internal code from bypassing validation
/// by mutating fields directly after construction.
#[derive(Debug, Clone)]
pub struct ValidatedConfig {
    /// Include hidden files and directories
    include_dotfiles: bool,
    /// Respect .gitignore patterns
    respect_gitignore: bool,
    /// Output format
    format: OutputFormat,
    /// Maximum directory depth (0 = unlimited)
    max_depth: usize,
    /// Maximum number of files to collect
    max_files: usize,
    /// Maximum clipboard size in MB
    max_clipboard_mb: usize,
    /// Compiled ignore patterns
    patterns: crate::config::IgnorePatterns,
}

impl ValidatedConfig {
    /// Create a `ValidatedConfig` with specific values for testing.
    ///
    /// Bypasses file-based config loading while still going through
    /// [`ConfigFile::validate`] to enforce all invariants. This allows
    /// tests outside the config module to get a `ValidatedConfig` with
    /// non-default values without needing filesystem setup.
    ///
    /// # Panics
    ///
    /// Panics if validation fails, which indicates a bug in the test setup.
    #[cfg(test)]
    #[must_use]
    pub fn for_test(cli_override: &CliOverride) -> Self {
        ConfigFile::default()
            .validate(cli_override)
            .expect("test config must validate")
    }

    /// Get the output format
    #[must_use]
    pub const fn format(&self) -> OutputFormat {
        self.format
    }

    /// Get the maximum directory depth (0 = unlimited)
    #[must_use]
    pub const fn max_depth(&self) -> usize {
        self.max_depth
    }

    /// Get the maximum number of files to collect
    #[must_use]
    pub const fn max_files(&self) -> usize {
        self.max_files
    }

    /// Get the maximum clipboard size in MB
    #[must_use]
    pub const fn max_clipboard_mb(&self) -> usize {
        self.max_clipboard_mb
    }

    /// Check if dotfiles should be included
    #[must_use]
    pub const fn include_dotfiles(&self) -> bool {
        self.include_dotfiles
    }

    /// Check if `.gitignore` patterns should be respected
    #[must_use]
    pub const fn respect_gitignore(&self) -> bool {
        self.respect_gitignore
    }

    /// Get a reference to the compiled ignore patterns
    #[must_use]
    pub const fn patterns(&self) -> &crate::config::IgnorePatterns {
        &self.patterns
    }
}

/// Maximum allowed config file size (1 MiB)
const MAX_CONFIG_FILE_SIZE: u64 = 1_048_576;

/// Load and parse a YAML configuration file into a [`ConfigFile`].
///
/// Opens the file descriptor first, then validates metadata via `fstat` on
/// the open handle, and finally reads from the same fd. This eliminates the
/// TOCTOU gap between validation and parsing — the kernel guarantees that
/// `File::metadata()` and `File::read_to_string()` operate on the same
/// inode.
///
/// Deserialization uses `serde_yaml` directly. The `#[serde(default)]`
/// and `#[serde(deny_unknown_fields)]` attributes on [`ConfigFile`]
/// handle missing-field defaults and typo rejection respectively, so no
/// Figment layering is needed here. Figment is used in the higher-level
/// `Config::from_args_with_env` to compose multiple sources.
///
/// # Errors
///
/// Returns a [`ConfigError`] if the file cannot be loaded or parsed.
pub fn load_config_file(config_path: &Path) -> Result<ConfigFile, ConfigError> {
    // Resolve symlinks so we validate (and open) the real target, not
    // a dangling or intermediate link.
    let canonical = config_path.canonicalize().map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            ConfigError::FileNotFound {
                path: config_path.to_path_buf(),
                source: e,
            }
        } else {
            ConfigError::InvalidPath {
                path: config_path.to_path_buf(),
                source: e,
            }
        }
    })?;

    // Open the file *once*. Every subsequent check (metadata, read) goes
    // through this fd, so the kernel ensures we never switch inodes.
    let mut file = std::fs::File::open(&canonical).map_err(|e| ConfigError::InvalidPath {
        path: config_path.to_path_buf(),
        source: e,
    })?;

    // fstat the open fd — no TOCTOU: this is the file we opened above.
    let metadata = file.metadata().map_err(|e| ConfigError::InvalidPath {
        path: config_path.to_path_buf(),
        source: e,
    })?;

    if !metadata.is_file() {
        return Err(ConfigError::NotAFile {
            path: config_path.to_path_buf(),
        });
    }

    // Reject special file types (FIFOs, sockets) that could block or
    // behave unexpectedly. Symlinks are already resolved by canonicalize().
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt;
        let file_type = metadata.file_type();
        if file_type.is_fifo() || file_type.is_socket() {
            return Err(ConfigError::InvalidFileType {
                path: config_path.to_path_buf(),
                message: "Config file cannot be a FIFO or socket".to_string(),
            });
        }
    }

    let file_size = metadata.len();
    if file_size > MAX_CONFIG_FILE_SIZE {
        return Err(ConfigError::FileTooLarge {
            path: config_path.to_path_buf(),
            size: file_size,
            max_size: MAX_CONFIG_FILE_SIZE,
        });
    }

    // Safe: file_size <= MAX_CONFIG_FILE_SIZE (1 MiB), which fits in usize
    // on all supported platforms (min 32-bit).
    let capacity = usize::try_from(file_size).unwrap_or(0);

    // Read from the same fd we validated — guaranteed same inode.
    // Pre-allocate based on the known size to avoid incremental realloc.
    let mut contents = String::with_capacity(capacity);
    let _ = file
        .read_to_string(&mut contents)
        .map_err(|e| ConfigError::InvalidPath {
            path: config_path.to_path_buf(),
            source: e,
        })?;

    // Parse YAML directly via serde. ConfigFile's #[serde(default = "...")]
    // attributes fill in omitted fields, and #[serde(deny_unknown_fields)]
    // rejects typos. No Figment needed at this layer.
    //
    // Convert serde_yaml::Error → figment::Error via its From<String> impl
    // so the type matches the ConfigError::ParseError source field.
    serde_yaml::from_str(&contents).map_err(|e| ConfigError::ParseError {
        path: config_path.to_path_buf(),
        source: Box::new(figment::Error::from(e.to_string())),
    })
}

/// Default value function for serde `bool` fields that default to `false`.
///
/// Used by `#[serde(default = "default_false")]` so the serde layer and
/// the manual `Default` impl share the same source of truth.
const fn default_false() -> bool {
    false
}

/// Default value function for serde `bool` fields that default to `true`.
///
/// Used by `#[serde(default = "default_true")]` so the serde layer and
/// the manual `Default` impl share the same source of truth.
const fn default_true() -> bool {
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_config_format_to_output_format() {
        assert_eq!(
            OutputFormat::from(ConfigFormat::Markdown),
            OutputFormat::Markdown
        );
        assert_eq!(OutputFormat::from(ConfigFormat::Tree), OutputFormat::Tree);
    }

    #[test]
    fn test_load_config_file_not_found() {
        let result = load_config_file(Path::new("/nonexistent/config.yaml"));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConfigError::FileNotFound { .. }
        ));
    }

    #[test]
    fn test_load_config_file_invalid_yaml() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("invalid.yaml");
        fs::write(&config_path, "invalid: yaml: content: :").unwrap();

        let result = load_config_file(&config_path);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConfigError::ParseError { .. }
        ));
    }

    #[test]
    fn test_load_config_file_rejects_unknown_fields() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("typo.yaml");
        // "include_dotfile" is a typo for "include_dotfiles"
        fs::write(&config_path, "include_dotfile: true\n").unwrap();

        let result = load_config_file(&config_path);
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), ConfigError::ParseError { .. }),
            "unknown fields in config YAML should be rejected"
        );
    }

    #[test]
    fn test_load_config_file_accepts_known_fields() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("valid.yaml");
        fs::write(&config_path, "include_dotfiles: true\nmax_depth: 5\n").unwrap();

        let config = load_config_file(&config_path).unwrap();
        assert!(config.include_dotfiles);
        assert_eq!(config.max_depth, Some(5));
    }

    #[test]
    fn test_load_config_file_rejects_directory() {
        let temp = TempDir::new().unwrap();
        // Pass the directory itself, not a file inside it
        let result = load_config_file(temp.path());
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), ConfigError::NotAFile { .. }),
            "a directory path should be rejected with NotAFile"
        );
    }

    #[test]
    fn test_load_config_file_rejects_too_large() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("huge.yaml");
        // Write just over the 1 MiB limit.
        // `MAX_CONFIG_FILE_SIZE` is 1 MiB which always fits in `usize`
        // (even on 32-bit), but we use `try_from` to satisfy clippy.
        let size = usize::try_from(MAX_CONFIG_FILE_SIZE)
            .expect("MAX_CONFIG_FILE_SIZE must fit in usize")
            + 1;
        let contents = "a".repeat(size);
        fs::write(&config_path, contents).unwrap();

        let result = load_config_file(&config_path);
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), ConfigError::FileTooLarge { .. }),
            "oversized config file should be rejected with FileTooLarge"
        );
    }

    /// Helper: write a `ConfigFile` to YAML and load it back via
    /// `load_config_file`, exercising the full serialization +
    /// security-validation + deserialization pipeline.
    fn round_trip_config(config: &ConfigFile) -> ConfigFile {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("round_trip.yaml");
        let yaml = serde_yaml::to_string(config).expect("ConfigFile must serialize");
        fs::write(&config_path, &yaml).expect("write must succeed");
        load_config_file(&config_path).expect("round-trip load must succeed")
    }

    proptest! {
        /// Any `max_depth` in `0..=MAX_DEPTH_LIMIT` must validate successfully.
        /// Any value above the limit must be rejected.
        #[test]
        fn test_max_depth_boundary(value in 0_usize..=200) {
            let config = ConfigFile {
                max_depth: Some(value),
                ..Default::default()
            };
            let result = config.validate(&CliOverride::default());
            if value <= MAX_DEPTH_LIMIT {
                let v = result.expect("should validate");
                prop_assert_eq!(v.max_depth(), value);
            } else {
                let err = result.expect_err("should reject");
                prop_assert!(
                    matches!(err, ConfigError::InvalidMaxDepth { .. }),
                    "unexpected error variant: {err:?}"
                );
            }
        }

        /// Any `max_files` in `1..=MAX_FILES_LIMIT` must validate; 0 and
        /// values above the limit must be rejected.
        #[test]
        fn test_max_files_boundary(value in 0_usize..=20_000_000) {
            let cli_override = CliOverride {
                max_files: Some(value),
                ..Default::default()
            };
            let config = ConfigFile::default();
            let result = config.validate(&cli_override);
            if (1..=MAX_FILES_LIMIT).contains(&value) {
                let v = result.expect("should validate");
                prop_assert_eq!(v.max_files(), value);
            } else {
                let err = result.expect_err("should reject");
                prop_assert!(
                    matches!(err, ConfigError::InvalidMaxFiles { .. }),
                    "unexpected error variant: {err:?}"
                );
            }
        }

        /// Any `max_clipboard_mb` in `0..=MAX_CLIPBOARD_LIMIT` must validate;
        /// values above the limit must be rejected.
        #[test]
        fn test_max_clipboard_mb_boundary(value in 0_usize..=2000) {
            let config = ConfigFile {
                max_clipboard_mb: Some(value),
                ..Default::default()
            };
            let result = config.validate(&CliOverride::default());
            if value <= MAX_CLIPBOARD_LIMIT {
                let v = result.expect("should validate");
                prop_assert_eq!(v.max_clipboard_mb(), value);
            } else {
                let err = result.expect_err("should reject");
                prop_assert!(
                    matches!(err, ConfigError::InvalidMaxClipboardMb { .. }),
                    "unexpected error variant: {err:?}"
                );
            }
        }

        /// CLI overrides always take precedence over config file values for
        /// any valid combination of format, depth, files, clipboard, and booleans.
        #[test]
        fn test_cli_override_precedence(
            cfg_format in prop::option::of(prop::sample::select(vec![
                ConfigFormat::Markdown,
                ConfigFormat::Tree,
            ])),
            cli_format in prop::option::of(prop::sample::select(vec![
                OutputFormat::Markdown,
                OutputFormat::Tree,
            ])),
            cfg_depth in prop::option::of(0_usize..=100),
            cli_depth in prop::option::of(0_usize..=100),
            cfg_dotfiles in proptest::bool::ANY,
            cli_dotfiles in prop::option::of(proptest::bool::ANY),
            cfg_gitignore in proptest::bool::ANY,
            cli_gitignore in prop::option::of(proptest::bool::ANY),
        ) {
            let config = ConfigFile {
                format: cfg_format,
                max_depth: cfg_depth,
                include_dotfiles: cfg_dotfiles,
                respect_gitignore: cfg_gitignore,
                ..Default::default()
            };
            let cli_override = CliOverride {
                format: cli_format,
                max_depth: cli_depth,
                include_dotfiles: cli_dotfiles,
                respect_gitignore: cli_gitignore,
                ..Default::default()
            };
            let result = config.validate(&cli_override).expect("should validate");

            // Format: CLI > Config > Markdown default
            let expected_format = cli_format
                .or_else(|| cfg_format.map(Into::into))
                .unwrap_or(OutputFormat::Markdown);
            prop_assert_eq!(result.format(), expected_format);

            // Depth: CLI > Config > 0
            let expected_depth = cli_depth.or(cfg_depth).unwrap_or(0);
            prop_assert_eq!(result.max_depth(), expected_depth);

            // Booleans: CLI > Config
            let expected_dotfiles = cli_dotfiles.unwrap_or(cfg_dotfiles);
            prop_assert_eq!(result.include_dotfiles(), expected_dotfiles);

            let expected_gitignore = cli_gitignore.unwrap_or(cfg_gitignore);
            prop_assert_eq!(result.respect_gitignore(), expected_gitignore);
        }

        /// CLI globs are merged with config globs — both sets must be active
        /// in the resulting patterns.
        #[test]
        fn test_cli_globs_merged_with_config_globs(
            cfg_ext in "[a-z]{2,6}",
            cli_ext in "[a-z]{2,6}",
        ) {
            // Use extension-style globs to avoid complex glob syntax
            let cfg_glob = format!("*.{cfg_ext}");
            let cli_glob = format!("*.{cli_ext}");

            let config = ConfigFile {
                ignore_globs: vec![cfg_glob],
                ..Default::default()
            };
            let cli_override = CliOverride {
                ignore_globs: Some(vec![cli_glob]),
                ..Default::default()
            };
            let result = config.validate(&cli_override).expect("should validate");

            prop_assert!(
                result.patterns().should_ignore_glob(Path::new(&format!("app.{cfg_ext}"))),
                "config glob pattern should be active"
            );
            prop_assert!(
                result.patterns().should_ignore_glob(Path::new(&format!("app.{cli_ext}"))),
                "CLI glob pattern should be active"
            );
        }

        /// ConfigFile round-trips through YAML serialization: serialize to
        /// YAML, write to disk, load via `load_config_file`, and verify
        /// all fields match.
        ///
        /// This covers a blind spot: we had no property test ensuring that
        /// arbitrary valid ConfigFile values survive the full
        /// serialize → file I/O → serde_yaml pipeline.
        #[test]
        fn test_config_file_yaml_round_trip(
            include_dotfiles in proptest::bool::ANY,
            respect_gitignore in proptest::bool::ANY,
            format in prop::option::of(prop::sample::select(vec![
                ConfigFormat::Markdown,
                ConfigFormat::Tree,
            ])),
            max_depth in prop::option::of(0_usize..=100),
            max_clipboard_mb in prop::option::of(0_usize..=1000),
        ) {
            let original = ConfigFile {
                include_dotfiles,
                respect_gitignore,
                format,
                max_depth,
                max_files: None, // NonZeroUsize is awkward to generate; covered by boundary tests
                max_clipboard_mb,
                ignore_extensions: Vec::new(),
                ignore_directories: Vec::new(),
                ignore_files: Vec::new(),
                ignore_globs: Vec::new(),
            };

            let loaded = round_trip_config(&original);

            prop_assert_eq!(original.include_dotfiles, loaded.include_dotfiles);
            prop_assert_eq!(original.respect_gitignore, loaded.respect_gitignore);
            prop_assert_eq!(original.format, loaded.format);
            prop_assert_eq!(original.max_depth, loaded.max_depth);
            prop_assert_eq!(original.max_clipboard_mb, loaded.max_clipboard_mb);
        }
    }
}