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
//! Command-line argument definitions with config file support

use clap::{ArgAction, Parser, Subcommand};
use std::path::PathBuf;

// Import OutputFormat from the shared, feature-independent module
use crate::format::OutputFormat;

/// Output mode for controlling stdout and clipboard behavior
///
/// This enum provides type-safe representation of output modes,
/// eliminating boolean blindness and invalid state combinations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputMode {
    /// Stream output directly to stdout (default mode)
    Stdout,
    /// Buffer output and copy to clipboard
    Clipboard {
        /// Whether to also print to stdout after clipboard copy
        show_stdout: bool,
    },
}

impl OutputMode {
    /// Construct `OutputMode` from CLI flags
    #[must_use]
    pub const fn from_flags(clip: bool, suppress_stdout: bool) -> Self {
        match (clip, suppress_stdout) {
            (false, _) => Self::Stdout,
            (true, false) => Self::Clipboard { show_stdout: true },
            (true, true) => Self::Clipboard { show_stdout: false },
        }
    }

    /// Check if output should be buffered (vs streamed)
    #[must_use]
    pub const fn should_buffer(&self) -> bool {
        matches!(self, Self::Clipboard { .. })
    }

    /// Check if output should be written to stdout
    #[must_use]
    pub const fn should_show_stdout(&self) -> bool {
        match self {
            Self::Stdout => true,
            Self::Clipboard { show_stdout } => *show_stdout,
        }
    }

    /// Check if output should be copied to clipboard
    #[must_use]
    pub const fn should_copy_clipboard(&self) -> bool {
        matches!(self, Self::Clipboard { .. })
    }
}

/// Print file content with Markdown formatting.
/// Either walks a directory or processes a specific list of files.
#[allow(clippy::struct_excessive_bools)]
#[derive(Parser, Debug, Clone)]
#[command(name = "luff")]
#[command(version, about, long_about = None)]
pub struct Args {
    /// Optional subcommand for advanced functionality (e.g., schema generation)
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// A list of files to process (positional).
    ///
    /// These are positional arguments. You can specify multiple files.
    #[arg(value_name = "FILE")]
    files_pos: Option<Vec<PathBuf>>,

    /// A list of files to process (via flag).
    ///
    /// Alternative to positional arguments. Supports multiple occurrences and multiple values.
    #[arg(short = 'f', long = "files", value_name = "FILE", action = ArgAction::Append, num_args = 1..)]
    files_flag: Option<Vec<PathBuf>>,

    /// Path to config file (YAML format)
    #[arg(long, value_name = "PATH")]
    config: Option<PathBuf>,

    /// Run from the root of the git repository (only for directory walk)
    #[arg(short, long)]
    git: bool,

    /// Include dot-directories in the directory walk
    ///
    /// This flag can be negated with --no-dotfiles to override a config file setting.
    #[arg(long, action = ArgAction::SetTrue, overrides_with = "no_dotfiles")]
    dotfiles: bool,

    /// Exclude dot-directories from the directory walk
    ///
    /// Negates --dotfiles. Useful for overriding config files that enable dotfiles.
    #[arg(long, action = ArgAction::SetTrue, overrides_with = "dotfiles")]
    no_dotfiles: bool,

    /// Add files that would otherwise be ignored by .gitignore
    ///
    /// Overrides the default behavior of respecting .gitignore.
    /// Replaces the old --ignored flag.
    #[arg(short = 'a', long = "add", action = ArgAction::SetTrue)]
    add_ignored: bool,

    /// Explicitly ignore files matching these glob patterns
    ///
    /// Supports bash-style glob syntax (e.g., "*.log", "target/**").
    /// Multiple patterns can be specified in several ways:
    ///
    /// Examples:
    ///   --ignore "*.log" "*.tmp" "*.bak"       # Multiple patterns in one flag
    ///   --ignore "*.log" --ignore "*.tmp"      # Multiple flags
    ///   --ignore "*.log" "*.tmp" --ignore "*.bak"  # Mixed approach
    ///
    /// All patterns are collected and applied. Glob patterns can contain any
    /// characters (including commas) since patterns are separated by spaces, not commas.
    ///
    /// Complex globs:
    ///   --ignore "*.{log,tmp}"                 # Brace expansion (works correctly)
    ///   --ignore "target/**" "build/**"        # Multiple directory patterns
    ///
    /// These patterns are applied in addition to .gitignore rules.
    ///
    /// **Important**: When mixing multiple patterns with positional file arguments,
    /// use the -f flag explicitly or place positional files before --ignore:
    ///   --ignore "*.log" "*.tmp" -f file.rs    # Use -f to separate
    ///   file.rs --ignore "*.log" "*.tmp"       # Or put files first
    #[arg(short = 'i', long = "ignore", value_name = "PATTERN", action = ArgAction::Append, num_args = 1..)]
    ignore: Option<Vec<String>>,

    /// Copy output to clipboard (in addition to stdout)
    ///
    /// ⚠️  **Memory Warning**: This mode buffers the entire output in memory before copying.
    /// To prevent memory exhaustion, a hard limit of 1GB is enforced regardless of
    /// --max-clipboard-mb setting. For large repositories, consider streaming mode
    /// (without --clip) which uses O(1) memory.
    #[arg(short, long)]
    clip: bool,

    /// Suppress stdout output (useful with --clip for clipboard-only mode)
    #[arg(short = 'S', long)]
    suppress_stdout: bool,

    /// Enable debug logging
    #[arg(short, long)]
    verbose: bool,

    /// Output format (markdown, tree)
    #[arg(long, value_enum)]
    format: Option<OutputFormat>,

    /// Maximum depth for directory traversal (0 = unlimited, max: 100)
    #[arg(long)]
    max_depth: Option<usize>,

    /// Maximum number of files to collect during directory walk.
    /// Prevents memory exhaustion on very large repositories.
    /// Memory usage: approximately 100 bytes per file path.
    /// At 1M files: ~100MB, at 10M files: ~1GB.
    #[arg(long)]
    max_files: Option<usize>,

    /// Maximum size for clipboard operations in MB.
    /// Prevents memory exhaustion when copying large outputs.
    /// Default: 100MB. Hard limit: 1000MB (cannot be overridden).
    /// Set to 0 to use the hard limit only.
    #[arg(long)]
    max_clipboard_mb: Option<usize>,
}

/// Subcommands for advanced functionality
#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
    /// Generate JSON schema for config files (for IDE autocomplete)
    ///
    /// Outputs a JSON Schema that can be used by editors to provide
    /// autocomplete and validation for luff.yaml files.
    ///
    /// Example usage:
    ///   luff schema > luff.schema.json
    ///   # Configure your editor to use luff.schema.json for YAML validation
    Schema {
        /// Output file (stdout if not specified)
        output: Option<PathBuf>,
    },
}

impl Args {
    /// Parse command-line arguments from environment
    #[must_use]
    pub fn parse_args() -> Self {
        Self::parse()
    }

    /// Get the list of explicitly specified files
    ///
    /// Combines files specified positionally and via the -f/--files flag.
    #[must_use]
    pub fn files(&self) -> Option<Vec<PathBuf>> {
        let mut files = Vec::new();
        if let Some(pos) = &self.files_pos {
            files.extend(pos.iter().cloned());
        }
        if let Some(flag) = &self.files_flag {
            files.extend(flag.iter().cloned());
        }

        if files.is_empty() { None } else { Some(files) }
    }

    /// Get the config file path if specified
    #[must_use]
    pub const fn config_path(&self) -> Option<&PathBuf> {
        self.config.as_ref()
    }

    /// Check if git repository root should be used as the base directory
    #[must_use]
    pub const fn use_git_root(&self) -> bool {
        self.git
    }

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

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

    /// Check if `.gitignore` patterns should be respected
    ///
    /// Returns `false` if `--add` flag is set (don't respect gitignore)
    /// Returns `true` if flag not specified (respect gitignore by default)
    #[must_use]
    pub const fn respect_gitignore(&self) -> bool {
        !self.add_ignored
    }

    /// Check if output should be copied to clipboard
    #[must_use]
    pub const fn use_clipboard(&self) -> bool {
        self.clip
    }

    /// Check if stdout output should be suppressed
    #[must_use]
    pub const fn suppress_stdout(&self) -> bool {
        self.suppress_stdout
    }

    /// Get the output mode (type-safe combination of clipboard/stdout flags)
    #[must_use]
    pub const fn output_mode(&self) -> OutputMode {
        OutputMode::from_flags(self.clip, self.suppress_stdout)
    }

    /// Check if verbose (debug) logging is enabled
    #[must_use]
    pub const fn verbose(&self) -> bool {
        self.verbose
    }

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

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

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

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

    /// Get the subcommand if any
    #[must_use]
    pub const fn command(&self) -> Option<&Commands> {
        self.command.as_ref()
    }

    /// Check whether any files were explicitly specified (positional or via -f)
    ///
    /// This is cheaper than `files()` when you only need to know whether
    /// file-list mode is active, since it avoids allocating a merged `Vec`.
    #[must_use]
    pub fn has_files(&self) -> bool {
        self.files_pos.as_ref().is_some_and(|v| !v.is_empty())
            || self.files_flag.as_ref().is_some_and(|v| !v.is_empty())
    }

    /// Convert Args to `CliOverride` for config precedence handling
    ///
    /// This method preserves all explicitly provided CLI values, allowing
    /// them to override config file and environment variable values.
    ///
    /// Note: `clap` handles the conflict resolution between `--dotfiles` and
    /// `--no-dotfiles` via `overrides_with`, so we can simply check which one is set.
    #[must_use]
    pub fn to_cli_override(&self) -> crate::config::CliOverride {
        let include_dotfiles = if self.dotfiles {
            Some(true)
        } else if self.no_dotfiles {
            Some(false)
        } else {
            None
        };

        // --add means DON'T respect gitignore
        let respect_gitignore = if self.add_ignored { Some(false) } else { None };

        // With num_args = 1.., clap automatically flattens multiple values into a single Vec
        // No need for comma-separated parsing - patterns are space-separated
        let ignore_globs = self.ignore.clone();

        crate::config::CliOverride {
            format: self.format,
            max_clipboard_mb: self.max_clipboard_mb,
            max_depth: self.max_depth,
            max_files: self.max_files,
            include_dotfiles,
            respect_gitignore,
            ignore_globs,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::error::ErrorKind;
    use proptest::prelude::*;
    use std::path::PathBuf;

    proptest! {
        /// Property: Ignore patterns should be preserved exactly as provided
        ///
        /// The character class deliberately excludes `-` to prevent generating
        /// strings that clap would interpret as flags (e.g., `-?`, `--foo`).
        /// Hyphen-containing patterns are tested separately via the `--`
        /// end-of-options separator.
        #[test]
        fn prop_ignore_patterns_preserved_exactly(
            patterns in prop::collection::vec("[a-zA-Z0-9*?._/]{1,50}", 1..10)
        ) {
            let mut args_vec = vec!["luff".to_string(), "--ignore".to_string()];
            args_vec.extend(patterns.clone());

            let args = Args::try_parse_from(&args_vec)
                .expect("Valid ignore patterns should parse successfully");

            assert_eq!(
                args.ignore.as_ref().unwrap(),
                &patterns,
                "Ignore patterns should be preserved exactly"
            );
        }

        /// Property: CLI override should preserve all explicit values
        #[test]
        fn prop_cli_override_preserves_explicit_values(
            max_depth in 0usize..100,
            max_files in 1usize..10_000,
            max_clipboard in 1usize..1000
        ) {
            let args = Args::try_parse_from([
                "luff",
                "--max-depth",
                &max_depth.to_string(),
                "--max-files",
                &max_files.to_string(),
                "--max-clipboard-mb",
                &max_clipboard.to_string(),
            ])
            .expect("Valid numeric args should parse successfully");

            let override_ = args.to_cli_override();

            assert_eq!(override_.max_depth, Some(max_depth));
            assert_eq!(override_.max_files, Some(max_files));
            assert_eq!(override_.max_clipboard_mb, Some(max_clipboard));
        }

        /// Property: Any valid argument combination should parse without panic
        #[test]
        fn prop_never_panics_on_valid_args(
            use_git in any::<bool>(),
            use_clip in any::<bool>(),
            verbose in any::<bool>()
        ) {
            let mut args_vec = vec!["luff"];

            if use_git {
                args_vec.push("--git");
            }
            if use_clip {
                args_vec.push("--clip");
            }
            if verbose {
                args_vec.push("--verbose");
            }

            let args = Args::try_parse_from(args_vec)
                .expect("Valid boolean flag combinations should parse successfully");

            assert_eq!(args.use_git_root(), use_git);
            assert_eq!(args.use_clipboard(), use_clip);
            assert_eq!(args.verbose(), verbose);
        }

        /// Property: OutputMode truth table is exhaustive and precise
        #[test]
        fn prop_output_mode_covers_all_combinations(
            clip in any::<bool>(),
            suppress in any::<bool>()
        ) {
            let mode = OutputMode::from_flags(clip, suppress);

            // Verify the mode is valid and consistent
            match mode {
                OutputMode::Stdout => {
                    // Stdout is only returned when clip is false;
                    // suppress_stdout is irrelevant without clip.
                    assert!(!clip, "Stdout mode requires clip=false, got clip={clip}");
                    assert!(mode.should_show_stdout());
                    assert!(!mode.should_buffer());
                    assert!(!mode.should_copy_clipboard());
                }
                OutputMode::Clipboard { show_stdout } => {
                    assert!(clip, "Clipboard mode requires clip=true, got clip={clip}");
                    assert!(mode.should_buffer());
                    assert!(mode.should_copy_clipboard());
                    assert_eq!(mode.should_show_stdout(), show_stdout);
                    assert_eq!(show_stdout, !suppress);
                }
            }
        }

        /// Property: has_files() and files().is_some() must always agree
        #[test]
        fn prop_has_files_consistent_with_files(
            use_positional in any::<bool>(),
            use_flag in any::<bool>(),
        ) {
            let mut args_vec = vec!["luff".to_string()];

            if use_positional {
                // Must place positional before any flags to avoid ambiguity
                args_vec.push("dummy.rs".to_string());
            }
            if use_flag {
                args_vec.push("-f".to_string());
                args_vec.push("flag.rs".to_string());
            }

            let args = Args::try_parse_from(&args_vec)
                .expect("Valid file combinations should parse");

            assert_eq!(
                args.has_files(),
                args.files().is_some(),
                "has_files() must agree with files().is_some()"
            );
        }

        /// Property: to_cli_override with no explicit flags produces all-None
        /// (This catches regressions where a default value leaks into overrides)
        #[test]
        fn prop_bare_invocation_override_is_none(
            _dummy in 0usize..10
        ) {
            let args = Args::try_parse_from(["luff"])
                .expect("bare invocation should parse");
            let o = args.to_cli_override();

            assert_eq!(o.format, None);
            assert_eq!(o.max_clipboard_mb, None);
            assert_eq!(o.max_depth, None);
            assert_eq!(o.max_files, None);
            assert_eq!(o.include_dotfiles, None);
            assert_eq!(o.respect_gitignore, None);
            assert_eq!(o.ignore_globs, None);
        }
    }

    #[test]
    fn test_default_args() {
        let args = Args::try_parse_from(["luff"]).expect("bare invocation should parse");
        assert_eq!(args.files(), None);
        assert_eq!(args.config_path(), None);
        assert!(!args.use_git_root());
        assert!(!args.dotfiles());
        assert!(!args.no_dotfiles());
        assert!(args.respect_gitignore());
        assert!(!args.use_clipboard());
        assert!(!args.suppress_stdout());
        assert!(!args.verbose());
        assert_eq!(args.max_files(), None);
        assert_eq!(args.max_clipboard_mb(), None);
        assert_eq!(args.output_format(), None);
        assert_eq!(args.max_depth(), None);
        assert!(!args.has_files());
    }

    #[test]
    fn test_positional_files() {
        let args = Args::try_parse_from(["luff", "file1.txt", "file2.txt"])
            .expect("positional files should parse");
        let files = args.files().expect("Should have files");
        assert_eq!(files.len(), 2);
        assert_eq!(files[0], PathBuf::from("file1.txt"));
        assert_eq!(files[1], PathBuf::from("file2.txt"));
        assert!(args.has_files());
    }

    #[test]
    fn test_flag_files() {
        let args = Args::try_parse_from(["luff", "-f", "file1.txt", "file2.txt"])
            .expect("-f flag should parse");
        let files = args.files().expect("Should have files");
        assert_eq!(files.len(), 2);
        assert_eq!(files[0], PathBuf::from("file1.txt"));
        assert_eq!(files[1], PathBuf::from("file2.txt"));
        assert!(args.has_files());
    }

    // Keep ONE representative test for each API pattern documented in help text
    #[test]
    fn test_ignore_multiple_values_single_flag() {
        let args = Args::try_parse_from(["luff", "--ignore", "*.log", "*.tmp", "*.bak"])
            .expect("multiple ignore values should parse");
        assert_eq!(
            args.ignore,
            Some(vec![
                "*.log".to_string(),
                "*.tmp".to_string(),
                "*.bak".to_string()
            ])
        );
    }

    #[test]
    fn test_ignore_with_brace_expansion() {
        let args = Args::try_parse_from(["luff", "--ignore", "*.{log,tmp}"])
            .expect("brace expansion should parse");
        assert_eq!(args.ignore, Some(vec!["*.{log,tmp}".to_string()]));
    }

    #[test]
    fn test_ignore_with_positional_using_explicit_flag() {
        let args = Args::try_parse_from(["luff", "--ignore", "*.log", "-f", "Cargo.toml"])
            .expect("ignore + -f should parse");
        assert_eq!(args.ignore, Some(vec!["*.log".to_string()]));

        let files = args.files().expect("Should have positional file");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0], PathBuf::from("Cargo.toml"));
    }

    /// Verify that hyphen-containing patterns work via the `--` separator.
    ///
    /// Clap interprets values starting with `-` as flags, so users must
    /// use `--` to pass literal patterns like `-backup` or `-old`.
    /// This test documents that behavior and ensures it works correctly.
    #[test]
    fn test_ignore_hyphen_patterns_via_double_dash() {
        // Patterns containing hyphens passed as positional files after `--`
        // work correctly (these become positional FILE args, not --ignore values).
        let args = Args::try_parse_from(["luff", "--ignore", "*.log", "--", "-backup.txt"])
            .expect("-- separator should allow hyphen-prefixed positional args");
        assert_eq!(args.ignore, Some(vec!["*.log".to_string()]));
        let files = args.files().expect("Should have positional file");
        assert_eq!(files[0], PathBuf::from("-backup.txt"));
    }

    /// Verify that a bare hyphen-prefixed value after --ignore is rejected by clap.
    #[test]
    fn test_ignore_rejects_hyphen_prefixed_value_as_flag() {
        let result = Args::try_parse_from(["luff", "--ignore", "-?"]);
        assert!(result.is_err(), "clap should reject -? as unknown flag");
        let err = result.unwrap_err();
        assert_eq!(
            err.kind(),
            ErrorKind::UnknownArgument,
            "Error should be UnknownArgument, got: {err}"
        );
    }

    #[test]
    fn test_config_path_getter() {
        let args = Args::try_parse_from(["luff", "--config", "/path/to/config.yaml"])
            .expect("--config should parse");
        assert_eq!(
            args.config_path().expect("Should have config path"),
            &PathBuf::from("/path/to/config.yaml")
        );
    }

    #[test]
    fn test_schema_subcommand() {
        let args =
            Args::try_parse_from(["luff", "schema"]).expect("schema subcommand should parse");
        assert!(matches!(
            args.command,
            Some(Commands::Schema { output: None })
        ));
    }

    #[test]
    fn test_schema_subcommand_with_output() {
        let args = Args::try_parse_from(["luff", "schema", "/tmp/schema.json"])
            .expect("schema with output should parse");
        assert!(matches!(
            args.command,
            Some(Commands::Schema { output: Some(_) })
        ));
    }

    #[test]
    fn test_output_mode_truth_table() {
        let cases = [
            (false, false, OutputMode::Stdout),
            (true, false, OutputMode::Clipboard { show_stdout: true }),
            (true, true, OutputMode::Clipboard { show_stdout: false }),
            (false, true, OutputMode::Stdout), // Edge case
        ];

        for (clip, suppress, expected) in cases {
            let mode = OutputMode::from_flags(clip, suppress);
            assert_eq!(
                mode, expected,
                "from_flags({clip}, {suppress}) should return {expected:?}"
            );
        }
    }

    #[test]
    fn test_to_cli_override_with_no_values() {
        let args = Args::try_parse_from(["luff"]).expect("bare invocation should parse");
        let override_ = args.to_cli_override();

        assert_eq!(override_.format, None);
        assert_eq!(override_.max_clipboard_mb, None);
        assert_eq!(override_.max_depth, None);
        assert_eq!(override_.max_files, None);
        assert_eq!(override_.include_dotfiles, None);
        assert_eq!(override_.respect_gitignore, None);
        assert_eq!(override_.ignore_globs, None);
    }

    #[test]
    fn test_to_cli_override_with_explicit_values() {
        let args = Args::try_parse_from([
            "luff",
            "--format",
            "tree",
            "--max-clipboard-mb",
            "50",
            "--max-depth",
            "3",
            "--max-files",
            "500",
            "--dotfiles",
            "--add",
            "--ignore",
            "*.log",
        ])
        .expect("full override args should parse");
        let override_ = args.to_cli_override();

        assert_eq!(override_.format, Some(OutputFormat::Tree));
        assert_eq!(override_.max_clipboard_mb, Some(50));
        assert_eq!(override_.max_depth, Some(3));
        assert_eq!(override_.max_files, Some(500));
        assert_eq!(override_.include_dotfiles, Some(true));
        assert_eq!(override_.respect_gitignore, Some(false));
        assert_eq!(override_.ignore_globs, Some(vec!["*.log".to_string()]));
    }

    #[test]
    fn test_boolean_override_logic() {
        // Test --dotfiles flag
        let args = Args::try_parse_from(["luff", "--dotfiles"]).expect("--dotfiles should parse");
        assert!(args.dotfiles());
        assert!(!args.no_dotfiles());
        assert_eq!(args.to_cli_override().include_dotfiles, Some(true));

        // Test --no-dotfiles flag
        let args =
            Args::try_parse_from(["luff", "--no-dotfiles"]).expect("--no-dotfiles should parse");
        assert!(!args.dotfiles());
        assert!(args.no_dotfiles());
        assert_eq!(args.to_cli_override().include_dotfiles, Some(false));

        // Test override: --dotfiles --no-dotfiles (last wins)
        let args = Args::try_parse_from(["luff", "--dotfiles", "--no-dotfiles"])
            .expect("--dotfiles --no-dotfiles should parse");
        assert!(!args.dotfiles());
        assert!(args.no_dotfiles());
        assert_eq!(args.to_cli_override().include_dotfiles, Some(false));

        // Test override: --no-dotfiles --dotfiles (last wins)
        let args = Args::try_parse_from(["luff", "--no-dotfiles", "--dotfiles"])
            .expect("--no-dotfiles --dotfiles should parse");
        assert!(args.dotfiles());
        assert!(!args.no_dotfiles());
        assert_eq!(args.to_cli_override().include_dotfiles, Some(true));
    }

    #[test]
    fn test_add_ignored_logic() {
        let args = Args::try_parse_from(["luff", "--add"]).expect("--add should parse");
        assert!(args.add_ignored);
        assert_eq!(args.to_cli_override().respect_gitignore, Some(false));

        let args = Args::try_parse_from(["luff"]).expect("bare invocation should parse");
        assert!(!args.add_ignored);
        assert_eq!(args.to_cli_override().respect_gitignore, None);
    }

    #[test]
    fn test_format_value_enum_variants() {
        // Verify ValueEnum parsing
        let args =
            Args::try_parse_from(["luff", "--format", "markdown"]).expect("markdown should parse");
        assert_eq!(args.output_format(), Some(OutputFormat::Markdown));

        let args = Args::try_parse_from(["luff", "--format", "md"]).expect("md alias should parse");
        assert_eq!(args.output_format(), Some(OutputFormat::Markdown));

        let args = Args::try_parse_from(["luff", "--format", "tree"]).expect("tree should parse");
        assert_eq!(args.output_format(), Some(OutputFormat::Tree));

        let result = Args::try_parse_from(["luff", "--format", "invalid"]);
        assert!(result.is_err(), "invalid format should be rejected");
    }

    #[test]
    fn test_has_files_consistency_with_files() {
        // has_files() and files().is_some() must always agree
        let args = Args::try_parse_from(["luff"]).unwrap();
        assert_eq!(args.has_files(), args.files().is_some());

        let args = Args::try_parse_from(["luff", "foo.rs"]).unwrap();
        assert_eq!(args.has_files(), args.files().is_some());

        let args = Args::try_parse_from(["luff", "-f", "bar.rs"]).unwrap();
        assert_eq!(args.has_files(), args.files().is_some());
    }
}