sift-grep 0.8.1

Grep-like CLI for sift-core
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
use std::process::ExitCode;

use crate::grep::Argv;
use crate::grep::engine::{EngineDecl, MultilineDecl, ThreadingDecl, WalkerDecl};
use crate::grep::filter::FilterResolution;
use crate::grep::filter::{FilterConfig, FilterDecl, GlobFlags, TypeCatalog};
use crate::grep::ignore::MessageFlags;
use crate::grep::ignore::{
    ContextDecl, IgnoreDotDecl, IgnoreExcludeDecl, IgnoreFilesDecl, IgnoreGitDecl,
    IgnoreGlobalDecl, IgnoreMessagesDecl, IgnoreNoDecl, IgnoreParentDecl, IgnoreResolution,
    IgnoreVcsDecl, MessagesDecl, UnrestrictedDecl,
};
use crate::grep::input::ContentTransformConfig;
use crate::grep::output::OutputArgv;
use crate::grep::output::OutputDecl;
use crate::grep::output::{
    ColumnDecl, ColumnsDecl, DebugDecl, ExtraOutputDecl, FilenameDecl, HeadingDecl, JsonDecl,
    LineNumberDecl, NullColorDecl, ReplaceDecl, SeparatorDecl, StatsDecl,
};
use crate::grep::paths::PathArgs;
use crate::grep::pattern::PatternArgv;
use crate::grep::pattern::PatternDecl;
use crate::grep::pattern::{
    BinaryDecl, GrepFlags, GrepScope, PatternArgs, RegexFlagsA, RegexFlagsB,
};
use crate::grep::run::{Run, RunConfig, RunResult};
use crate::index::{
    IndexDecl, IndexExecution, IndexJob, IndexOperation, IndexRequest, IndexSelection,
};
use crate::update;
use sift_core::SearchMode;
use sift_core::ZeroCounts;

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

#[derive(Parser)]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,

    #[command(flatten)]
    pub patterns: PatternArgs,
    #[command(flatten)]
    pub search_scope: GrepScope,
    #[command(flatten)]
    pub regex1: RegexFlagsA,
    #[command(flatten)]
    pub regex2: RegexFlagsB,
    #[command(flatten)]
    pub line_number_decl: LineNumberDecl,
    #[command(flatten)]
    pub search_flags: GrepFlags,
    #[command(flatten)]
    pub filename_decl: FilenameDecl,
    #[command(flatten)]
    pub heading_decl: HeadingDecl,
    #[command(flatten)]
    pub column_decl: ColumnDecl,
    #[command(flatten)]
    pub columns_decl: ColumnsDecl,
    #[command(flatten)]
    pub glob_flags: GlobFlags,
    #[command(flatten)]
    pub ignore_no: IgnoreNoDecl,
    #[command(flatten)]
    pub ignore_vcs: IgnoreVcsDecl,
    #[command(flatten)]
    pub ignore_dot: IgnoreDotDecl,
    #[command(flatten)]
    pub ignore_git: IgnoreGitDecl,
    #[command(flatten)]
    pub ignore_global: IgnoreGlobalDecl,
    #[command(flatten)]
    pub ignore_exclude: IgnoreExcludeDecl,
    #[command(flatten)]
    pub ignore_parent: IgnoreParentDecl,
    #[command(flatten)]
    pub ignore_files_decl: IgnoreFilesDecl,
    #[command(flatten)]
    pub messages_decl: MessagesDecl,
    #[command(flatten)]
    pub ignore_messages_decl: IgnoreMessagesDecl,
    #[command(flatten)]
    pub unrestricted: UnrestrictedDecl,
    #[command(flatten)]
    pub context_decl: ContextDecl,
    #[command(flatten)]
    pub null_color: NullColorDecl,
    #[command(flatten)]
    pub paths: PathArgs,
    #[command(flatten)]
    pub stats_decl: StatsDecl,
    #[command(flatten)]
    pub debug_decl: DebugDecl,
    #[command(flatten)]
    pub json_decl: JsonDecl,
    #[command(flatten)]
    pub separator_decl: SeparatorDecl,
    #[command(flatten)]
    pub filter_decl: FilterDecl,
    #[command(flatten)]
    pub binary_decl: BinaryDecl,
    #[command(flatten)]
    pub replace_decl: ReplaceDecl,
    #[command(flatten)]
    pub extra_output: ExtraOutputDecl,
    #[command(flatten)]
    pub threading: ThreadingDecl,
    #[command(flatten)]
    pub multiline_decl: MultilineDecl,
    #[command(flatten)]
    pub walker_decl: WalkerDecl,
    #[command(flatten)]
    pub engine_decl: EngineDecl,
}

impl Cli {
    /// Resolve pattern flags and search paths for `mode`.
    #[must_use]
    pub fn pattern_config(&self, mode: SearchMode) -> (PatternDecl, Vec<PathBuf>) {
        let (patterns, search_paths) = self.search_scope.resolve(&self.patterns, mode);
        (
            PatternDecl {
                patterns,
                search_flags: self.search_flags.clone(),
                regex1: self.regex1.clone(),
                regex2: self.regex2.clone(),
                multiline: self.multiline_decl.clone(),
                engine: self.engine_decl.clone(),
                binary: self.binary_decl.clone(),
                replace: self.replace_decl.clone(),
                max_count: self.paths.max_count,
            },
            search_paths,
        )
    }

    #[must_use]
    pub fn filter_config(&self) -> FilterConfig {
        FilterConfig {
            decl: self.filter_decl.clone(),
            glob_patterns: self.glob_flags.glob.clone(),
            follow_links: self.paths.follow,
            one_file_system: self.walker_decl.one_file_system,
        }
    }

    #[must_use]
    fn output_config(&self, search_paths: &[PathBuf]) -> OutputDecl {
        OutputDecl {
            column: self.column_decl.clone(),
            columns: self.columns_decl.clone(),
            extra: self.extra_output.clone(),
            replace_trim: self.replace_decl.trim,
            path_separator: self.threading.path_separator.clone(),
            colors: self.engine_decl.colors.clone(),
            hyperlink_format: self.engine_decl.hyperlink_format.clone(),
            hostname_bin: self.engine_decl.hostname_bin.clone(),
            line_number: self.line_number_decl.line_number,
            separators: self.separator_decl.clone(),
            search_paths: search_paths.to_vec(),
            null_data: self.multiline_decl.line_terminator.null_data,
        }
    }

    /// Build a resolved run configuration from parsed CLI state and argv ordering.
    ///
    /// # Errors
    ///
    /// Returns an error if sort/order flags or type filters are invalid.
    pub fn run_config(&self, argv: &Argv<'_>) -> Result<RunConfig, anyhow::Error> {
        let zeros = if self.extra_output.include_zero {
            ZeroCounts::Include
        } else {
            ZeroCounts::Omit
        };
        let mut pattern_argv = PatternArgv::resolve(argv, zeros);
        let search_mode = if self.filter_decl.files {
            SearchMode::Paths
        } else {
            pattern_argv.mode
        };
        pattern_argv.mode = search_mode;
        let (pattern, search_paths) = self.pattern_config(search_mode);
        let filter_resolution = FilterResolution::resolve(argv);
        let type_catalog = TypeCatalog::from_argv(argv)?;
        let type_filters = type_catalog.filters(argv)?;
        let output_argv = OutputArgv::resolve(argv);
        let ignore = IgnoreResolution::resolve(argv);
        let file_order = self.filter_decl.file_order(argv)?;
        Ok(RunConfig {
            pattern,
            pattern_argv,
            filter: self.filter_config(),
            filter_resolution,
            type_filters,
            output: self.output_config(&search_paths),
            output_argv,
            sift_dir: self.paths.sift_dir.clone(),
            search_paths,
            threads: self.threading.threads,
            content: ContentTransformConfig {
                search_zip: self.engine_decl.content.search_zip,
                pre: self.engine_decl.content.pre.clone(),
                pre_globs: self.engine_decl.content.pre_glob.clone(),
            },
            file_order,
            search_mode,
            ignore,
        })
    }

    #[must_use]
    pub fn dispatch(self, argv: &Argv<'_>) -> ExitCode {
        if self.engine_decl.regex.pcre2_version {
            let (major, minor) = grep_pcre2::version();
            println!("PCRE2 {major}.{minor}");
            return ExitCode::SUCCESS;
        }

        if self.filter_decl.type_list {
            return match TypeCatalog::from_argv(argv) {
                Ok(catalog) => {
                    catalog.print_list();
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("sift: {e}");
                    ExitCode::from(2)
                }
            };
        }

        match self.command {
            Some(Commands::Update) => match update::run_binary_update() {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("sift: {e}");
                    ExitCode::from(2)
                }
            },
            Some(Commands::Index { command }) => {
                let daemon = self.paths.daemon();
                let indexes = match IndexSelection::resolve(argv) {
                    Ok(selection) => selection.map(|s| s.indexes),
                    Err(e) => {
                        eprintln!("sift: {e}");
                        return ExitCode::from(2);
                    }
                };
                let (path, operation, execution, build_coverage) = command.into_request_parts();
                let req = IndexRequest {
                    operation,
                    execution,
                    build_coverage,
                    path,
                    indexes,
                    sift_dir: self.paths.sift_dir,
                    follow_links: self.paths.follow,
                    one_file_system: self.walker_decl.one_file_system,
                    max_depth: self.filter_decl.max_depth,
                    max_filesize: self.filter_decl.max_filesize,
                };
                let ignore = IgnoreResolution::resolve(argv);
                match IndexJob::resolve(req, ignore) {
                    Ok(index) => index.run(daemon.as_ref()),
                    Err(e) => {
                        eprintln!("sift: {e}");
                        ExitCode::from(2)
                    }
                }
            }
            None => {
                let daemon = self.paths.daemon();
                let config = match self.run_config(argv) {
                    Ok(config) => config,
                    Err(e) => {
                        eprintln!("sift: {e}");
                        return ExitCode::from(2);
                    }
                };
                let suppress_errors = config.ignore.msg_flags.contains(MessageFlags::NO_MESSAGES);
                let run = Run::new(config);
                Self::exit_from_run(run.execute(daemon.as_ref()), suppress_errors)
            }
        }
    }

    fn exit_from_run(
        result: Result<RunResult, anyhow::Error>,
        suppress_error_messages: bool,
    ) -> ExitCode {
        match result {
            Ok(outcome) if outcome.succeeded() => ExitCode::SUCCESS,
            Ok(RunResult::Found | RunResult::NotFound) => ExitCode::from(1),
            Err(e) => {
                if let Some(ioe) = e.downcast_ref::<std::io::Error>()
                    && ioe.kind() == std::io::ErrorKind::BrokenPipe
                {
                    return ExitCode::SUCCESS;
                }
                if !suppress_error_messages {
                    eprintln!("sift: {e}");
                }
                ExitCode::from(2)
            }
        }
    }
}

#[derive(Subcommand)]
pub enum Commands {
    /// Download and install the latest release over the current binary.
    Update,
    Index {
        #[command(subcommand)]
        command: IndexCommands,
    },
}

#[derive(Subcommand)]
pub enum IndexCommands {
    /// Create an index at `--sift-dir` (fails if an index already exists).
    Build {
        #[arg(default_value = ".")]
        path: PathBuf,

        #[command(flatten)]
        indexes: IndexDecl,

        /// Block until the index build completes (default: async via daemon).
        #[arg(long)]
        wait: bool,

        /// Build a lazy index that may be completed incrementally by searches.
        #[arg(long)]
        lazy: bool,
    },
    /// Incrementally refresh an existing index (fails if no index exists).
    Update {
        #[arg(default_value = ".")]
        path: PathBuf,

        #[command(flatten)]
        indexes: IndexDecl,

        /// Block until the index update completes.
        #[arg(long)]
        wait: bool,
    },
}

impl IndexCommands {
    fn into_request_parts(
        self,
    ) -> (
        PathBuf,
        IndexOperation,
        IndexExecution,
        sift_core::IndexCoverage,
    ) {
        match self {
            Self::Build {
                path,
                indexes: _,
                wait,
                lazy,
            } => {
                let execution = if wait {
                    IndexExecution::Blocking
                } else {
                    IndexExecution::Background
                };
                let coverage = if lazy {
                    sift_core::IndexCoverage::Lazy
                } else {
                    sift_core::IndexCoverage::Complete
                };
                (path, IndexOperation::Build, execution, coverage)
            }
            Self::Update {
                path,
                indexes: _,
                wait,
            } => {
                let execution = if wait {
                    IndexExecution::Blocking
                } else {
                    IndexExecution::Background
                };
                (
                    path,
                    IndexOperation::Update,
                    execution,
                    sift_core::IndexCoverage::Complete,
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::path::Path;

    #[test]
    fn cli_parses_positional_pattern() {
        let cli = Cli::try_parse_from(["sift", "pattern"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.pattern.as_deref(), Some("pattern"));
        assert!(paths.is_empty());
    }

    #[test]
    fn cli_parses_regexp_flag() {
        let cli = Cli::try_parse_from(["sift", "-e", "pattern"]).unwrap();
        assert_eq!(cli.patterns.regexp, vec!["pattern"]);
    }

    #[test]
    fn cli_parses_multiple_regexp_flags() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "-e", "bar"]).unwrap();
        assert_eq!(cli.patterns.regexp, vec!["foo", "bar"]);
    }

    #[test]
    fn cli_parses_update_subcommand() {
        let cli = Cli::try_parse_from(["sift", "update"]).unwrap();
        assert!(matches!(cli.command, Some(Commands::Update)));
    }

    #[test]
    fn cli_parses_index_build_subcommand() {
        let cli = Cli::try_parse_from(["sift", "index", "build"]).unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { path, .. },
            }) => assert_eq!(path, PathBuf::from(".")),
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_parses_index_build_subcommand_with_path() {
        let cli = Cli::try_parse_from(["sift", "index", "build", "/tmp"]).unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { path, .. },
            }) => assert_eq!(path, PathBuf::from("/tmp")),
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_parses_index_kind_and_options() {
        let cli = Cli::try_parse_from([
            "sift",
            "index",
            "build",
            "--index",
            "ngram",
            "--width",
            "5",
            "--norm",
            "ascii-lower",
        ])
        .unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { indexes, .. },
            }) => {
                assert_eq!(indexes.kinds.len(), 1);
                assert_eq!(indexes.width, vec![5]);
                assert_eq!(indexes.norms, vec![crate::index::GramNormArg::AsciiLower]);
            }
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_parses_index_update_subcommand() {
        let cli = Cli::try_parse_from(["sift", "index", "update"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Commands::Index {
                command: IndexCommands::Update { .. }
            })
        ));
    }

    #[test]
    fn cli_parses_no_search_scope() {
        let cli = Cli::try_parse_from(["sift", "pattern"]).unwrap();
        assert_eq!(cli.search_scope.args, vec!["pattern"]);
        let (_, paths) = cli.pattern_config(SearchMode::Lines);
        assert!(paths.is_empty());
    }

    #[test]
    fn cli_parses_search_scope() {
        let cli = Cli::try_parse_from(["sift", "pattern", "src/"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.pattern.as_deref(), Some("pattern"));
        assert_eq!(paths, vec![PathBuf::from("src/")]);
    }

    #[test]
    fn cli_parses_multiple_paths() {
        let cli = Cli::try_parse_from(["sift", "pattern", "src/", "tests/"]).unwrap();
        let (_, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(paths, vec![PathBuf::from("src/"), PathBuf::from("tests/")]);
    }

    #[test]
    fn cli_parses_version_flag() {
        let result = Cli::try_parse_from(["sift", "--version"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_rejects_unknown_flags() {
        let result = Cli::try_parse_from(["sift", "--nonexistent-flag"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_pattern_and_search_scope() {
        let cli = Cli::try_parse_from(["sift", "pat", "dir1", "dir2"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.pattern.as_deref(), Some("pat"));
        assert_eq!(paths, vec![PathBuf::from("dir1"), PathBuf::from("dir2")]);
    }

    #[test]
    fn cli_regexp_positional_becomes_search_path() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "dir1"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1")]);
    }

    #[test]
    fn cli_multiple_regexp_positional_becomes_search_path() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "-e", "bar", "dir1"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo", "bar"]);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1")]);
    }

    #[test]
    fn cli_regexp_preserves_path_order_with_extra_paths() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "dir1", "dir2"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1"), PathBuf::from("dir2")]);
    }

    #[test]
    fn cli_pattern_file_positional_becomes_search_path() {
        let cli = Cli::try_parse_from(["sift", "-f", "pats.txt", "dir1"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(
            config.patterns.pattern_file.as_deref(),
            Some(Path::new("pats.txt"))
        );
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1")]);
    }

    #[test]
    fn cli_regexp_without_path_leaves_paths_empty() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert!(config.patterns.pattern.is_none());
        assert!(paths.is_empty());
    }

    #[test]
    fn cli_positional_only_keeps_pattern_and_paths() {
        let cli = Cli::try_parse_from(["sift", "pat", "dir1", "dir2"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.pattern.as_deref(), Some("pat"));
        assert!(config.patterns.regexp.is_empty());
        assert_eq!(paths, vec![PathBuf::from("dir1"), PathBuf::from("dir2")]);
    }

    #[test]
    fn cli_regexp_double_dash_path_becomes_search_path() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "--", "dir1"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1")]);
    }

    #[test]
    fn cli_regexp_double_dash_hyphen_path() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "--", "-weird"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("-weird")]);
    }

    #[test]
    fn cli_regexp_and_pattern_file_positional_is_path() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "-f", "pats.txt", "dir1"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Lines);
        assert_eq!(config.patterns.regexp, vec!["foo"]);
        assert_eq!(
            config.patterns.pattern_file.as_deref(),
            Some(Path::new("pats.txt"))
        );
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("dir1")]);
    }

    #[test]
    fn cli_run_config_uses_resolved_paths() {
        let cli = Cli::try_parse_from(["sift", "-e", "foo", "dir1"]).unwrap();
        let tokens = ["sift".into(), "-e".into(), "foo".into(), "dir1".into()];
        let argv = Argv::new(&tokens);
        let config = cli.run_config(&argv).unwrap();
        assert_eq!(config.search_paths, vec![PathBuf::from("dir1")]);
        assert!(config.pattern.patterns.pattern.is_none());
        assert_eq!(config.pattern.patterns.regexp, vec!["foo"]);
    }

    #[test]
    fn cli_files_positional_is_search_path() {
        let cli = Cli::try_parse_from(["sift", "--files", "subdir"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Paths);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("subdir")]);
        let tokens = ["sift".into(), "--files".into(), "subdir".into()];
        let config = cli.run_config(&Argv::new(&tokens)).unwrap();
        assert_eq!(config.search_mode, SearchMode::Paths);
        assert_eq!(config.search_paths, vec![PathBuf::from("subdir")]);
    }

    #[test]
    fn cli_files_preserves_path_order_with_extra_paths() {
        let cli = Cli::try_parse_from(["sift", "--files", "a", "b"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Paths);
        assert!(config.patterns.pattern.is_none());
        assert_eq!(paths, vec![PathBuf::from("a"), PathBuf::from("b")]);
    }

    #[test]
    fn cli_files_without_path_leaves_paths_empty() {
        let cli = Cli::try_parse_from(["sift", "--files"]).unwrap();
        let (config, paths) = cli.pattern_config(SearchMode::Paths);
        assert!(config.patterns.pattern.is_none());
        assert!(paths.is_empty());
    }

    #[test]
    fn cli_parses_short_flags_before_pattern() {
        let cli = Cli::try_parse_from(["sift", "-n", "-H", "pattern"]).unwrap();
        assert!(cli.line_number_decl.line_number);
        assert!(cli.filename_decl.with_filename);
    }

    #[test]
    fn cli_parses_long_flags_before_pattern() {
        let cli =
            Cli::try_parse_from(["sift", "--line-number", "--with-filename", "pattern"]).unwrap();
        assert!(cli.line_number_decl.line_number);
        assert!(cli.filename_decl.with_filename);
    }

    #[test]
    fn cli_parses_empty_pattern_file() {
        let cli = Cli::try_parse_from(["sift", "-f", "ignore.txt"]).unwrap();
        assert_eq!(
            cli.patterns.pattern_file.as_deref(),
            Some(Path::new("ignore.txt"))
        );
    }

    #[test]
    fn cli_parses_index_build_defaults_to_background() {
        let cli = Cli::try_parse_from(["sift", "index", "build"]).unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { wait, .. },
            }) => assert!(!wait),
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_parses_index_build_wait_flag() {
        let cli = Cli::try_parse_from(["sift", "index", "build", "--wait"]).unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { wait, .. },
            }) => assert!(wait),
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_parses_index_build_lazy_flag() {
        let cli = Cli::try_parse_from(["sift", "index", "build", "--lazy"]).unwrap();
        match cli.command {
            Some(Commands::Index {
                command: IndexCommands::Build { lazy, .. },
            }) => assert!(lazy),
            _ => panic!("expected index build subcommand"),
        }
    }

    #[test]
    fn cli_rejects_index_update_lazy_flag() {
        let result = Cli::try_parse_from(["sift", "index", "update", "--lazy"]);
        assert!(result.is_err());
    }
}