seagrep 0.7.0

Indexed regex search for private S3 buckets
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
mod globs;
mod index;
mod json;
mod patterns;
mod printer;
mod progress;
mod scope;

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use scope::Scope;
use seagrep_core::{BlobStore, MatchOptions, Strategy};
use seagrep_index::{
    search_streaming, update_index, IndexChanged, KeyScope, MatchSink, SearchStats,
    SegmentedReader, SourceIdentity, UpdateOptions,
};
use seagrep_s3::{
    build_fetch_config, build_index_namespace, is_index_key, list_prefix, ObjectMeta, S3BlobStore,
    S3Client, S3Corpus,
};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::time::Duration;

#[derive(Parser)]
#[command(
    name = "seagrep",
    version,
    args_conflicts_with_subcommands = true,
    subcommand_negates_reqs = true,
    about = "Indexed regex search over S3 buckets",
    long_about = "seagrep PATTERN TARGET searches a prebuilt index.\n\
        TARGET is s3://bucket[/prefix].\n\
        To search for a pattern named like the `index` subcommand,\n\
        use -e: `seagrep -e index s3://bucket`."
)]
struct Cli {
    #[command(subcommand)]
    cmd: Option<Cmd>,
    #[command(flatten)]
    search: SearchArgs,
}

// Doc comments on clap structs are --help text; markdown would leak into it.
#[allow(clippy::doc_markdown)]
#[derive(Subcommand)]
enum Cmd {
    /// Build or update the index for TARGET (s3://bucket[/prefix]).
    Index {
        #[arg(value_name = "TARGET")]
        target: String,
        #[command(flatten)]
        index: IndexArgs,
        /// Index strategy; picked automatically from sampled content when omitted.
        #[arg(long, value_enum)]
        strategy: Option<StrategyArg>,
        /// Ignore any existing index and re-ingest everything.
        #[arg(long)]
        rebuild: bool,
        /// Physically remove tombstoned snapshot bytes during this update.
        #[arg(long)]
        purge_deleted: bool,
        #[arg(long, requires = "interval", help = "Continuously update the index")]
        watch: bool,
        #[arg(
            long,
            value_name = "SECONDS",
            requires = "watch",
            value_parser = parse_positive_u64,
            help = "Wait SECONDS after each index attempt"
        )]
        interval: Option<u64>,
        #[arg(long, help = "Emit one JSON status object per line")]
        json: bool,
        #[command(flatten)]
        connect: ConnectArgs,
    },
}

// Doc comments on clap structs are --help text; markdown would leak into it.
#[allow(clippy::doc_markdown)]
#[derive(clap::Args)]
struct ConnectArgs {
    /// AWS region (s3:// targets only). Uses the AWS SDK chain when omitted.
    #[arg(long)]
    region: Option<String>,
    /// Custom S3-compatible endpoint (e.g. http://127.0.0.1:9000 for MinIO).
    #[arg(long)]
    endpoint: Option<String>,
    /// Peak S3 fetch concurrency.
    #[arg(long, default_value_t = 750, value_parser = parse_concurrency)]
    concurrency: usize,
}

#[derive(clap::Args)]
struct IndexArgs {
    /// Index location (`s3://bucket/prefix`).
    #[arg(long = "index", value_name = "LOCATION")]
    location: Option<String>,
    /// AWS region for an s3:// index location.
    #[arg(long = "index-region", requires = "location")]
    index_region: Option<String>,
    /// Custom endpoint for an s3:// index location.
    #[arg(long = "index-endpoint", requires = "location")]
    index_endpoint: Option<String>,
}

#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum ColorArg {
    Never,
    Auto,
    Always,
    Ansi,
}

// Doc comments on clap structs are --help text; markdown would leak into it.
#[allow(clippy::doc_markdown)]
#[derive(clap::Args)]
struct SearchArgs {
    /// PATTERN then TARGET. With -e, the single positional is the TARGET.
    #[arg(value_name = "PATTERN|TARGET", required = true)]
    args: Vec<String>,
    /// A pattern to search for (repeatable; a line matching any pattern is printed).
    #[arg(short = 'e', long = "regexp", value_name = "PATTERN")]
    regexp: Vec<String>,
    /// Treat all patterns as literal strings.
    #[arg(short = 'F', long)]
    fixed_strings: bool,
    /// Case-insensitive search.
    #[arg(short = 'i', long, overrides_with_all = ["smart_case", "case_sensitive"])]
    ignore_case: bool,
    /// Case-insensitive when all patterns are lowercase.
    #[arg(short = 'S', long, overrides_with_all = ["ignore_case", "case_sensitive"])]
    smart_case: bool,
    /// Case-sensitive search (default).
    #[arg(short = 's', long, overrides_with_all = ["ignore_case", "smart_case"])]
    case_sensitive: bool,
    /// Wrap every pattern in word boundaries.
    #[arg(short = 'w', long)]
    word_regexp: bool,
    /// Print matches from binary content instead of the suppression notice.
    #[arg(short = 'a', long)]
    text: bool,
    /// Print only the keys of matching objects.
    #[arg(short = 'l', long, conflicts_with_all = ["count", "count_matches", "json"])]
    files_with_matches: bool,
    /// Print the count of matching lines per object.
    #[arg(
        short = 'c',
        long,
        overrides_with = "count_matches",
        conflicts_with = "json"
    )]
    count: bool,
    /// Print the count of individual matches per object.
    #[arg(long, overrides_with = "count", conflicts_with = "json")]
    count_matches: bool,
    /// Limit the number of matching lines per object.
    #[arg(short = 'm', long, value_name = "NUM")]
    max_count: Option<u64>,
    /// Print NUM lines after each match.
    #[arg(short = 'A', long, value_name = "NUM")]
    after_context: Option<usize>,
    /// Print NUM lines before each match.
    #[arg(short = 'B', long, value_name = "NUM")]
    before_context: Option<usize>,
    /// Print NUM lines before and after each match.
    #[arg(short = 'C', long, value_name = "NUM")]
    context: Option<usize>,
    /// Show line numbers (default: on when printing to a terminal).
    #[arg(short = 'n', long, overrides_with = "no_line_number")]
    line_number: bool,
    /// Suppress line numbers.
    #[arg(short = 'N', long, overrides_with = "line_number")]
    no_line_number: bool,
    /// Show the 1-based byte column of the first match per line. Implies --line-number.
    #[arg(long)]
    column: bool,
    /// Group matches under their object key (default: on when printing to a terminal).
    #[arg(long, overrides_with = "no_heading")]
    heading: bool,
    /// One line per match: key:line:text.
    #[arg(long, overrides_with = "heading")]
    no_heading: bool,
    /// Include or exclude keys (gitignore-style glob; prefix with ! to exclude; repeatable).
    #[arg(short = 'g', long = "glob", value_name = "GLOB")]
    glob: Vec<String>,
    /// Print nothing; exit 0 at the first match.
    #[arg(short = 'q', long)]
    quiet: bool,
    /// When to use colors.
    #[arg(long, value_enum, default_value_t = ColorArg::Auto, value_name = "WHEN")]
    color: ColorArg,
    /// Emit results as JSON Lines (ripgrep-compatible wire format).
    #[arg(long)]
    json: bool,
    /// Print search statistics to stderr (with --json: the summary message).
    #[arg(long)]
    stats: bool,
    #[command(flatten)]
    index: IndexArgs,
    /// Only search objects whose key starts with this prefix.
    #[arg(long)]
    key_prefix: Option<String>,
    /// Only search objects whose key matches this regex.
    #[arg(long)]
    key_regex: Option<String>,
    /// Only search objects covering times at or after this instant
    /// (`2026-06-09`, `2026-06-09T14:30[:00][Z]`, or relative 30m/6h/2d/1w).
    #[arg(long)]
    since: Option<String>,
    /// Only search objects covering times at or before this instant (same formats).
    #[arg(long)]
    until: Option<String>,
    #[command(flatten)]
    connect: ConnectArgs,
}

struct S3Target {
    bucket: String,
    prefix: String,
}

fn parse_s3_target(raw: &str) -> Result<S3Target> {
    let rest = raw
        .strip_prefix("s3://")
        .with_context(|| format!("S3 location must be s3://bucket[/prefix], got {raw}"))?;
    let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, ""));
    anyhow::ensure!(!bucket.is_empty(), "s3:// target needs a bucket");
    Ok(S3Target {
        bucket: bucket.to_owned(),
        prefix: prefix.to_owned(),
    })
}

struct S3Source {
    client: S3Client,
    endpoint: String,
    bucket: String,
    prefix: String,
}

struct IndexStorage {
    client: S3Client,
    endpoint: String,
    bucket: String,
    root: String,
    cache: PathBuf,
}

impl IndexStorage {
    fn store(&self) -> Box<dyn BlobStore> {
        self.store_with_progress(None)
    }

    fn store_with_progress(
        &self,
        progress: Option<seagrep_core::ProgressSender>,
    ) -> Box<dyn BlobStore> {
        let mut store =
            S3BlobStore::at(self.client.clone(), self.bucket.clone(), self.root.clone());
        if let Some(progress) = progress {
            store.set_progress(progress);
        }
        Box::new(store)
    }

    fn cache(&self) -> &Path {
        &self.cache
    }

    fn location(&self) -> String {
        if self.root.is_empty() {
            format!("s3://{}", self.bucket)
        } else {
            format!("s3://{}/{}", self.bucket, self.root)
        }
    }

    fn contains_source_key(&self, source: &S3Source, key: &str) -> bool {
        is_same_s3_bucket(
            &self.endpoint,
            &self.bucket,
            &source.endpoint,
            &source.bucket,
        ) && (key == self.root
            || key
                .strip_prefix(&self.root)
                .is_some_and(|relative| relative.starts_with('/')))
    }
}

fn open_source(target: S3Target, connect: &ConnectArgs) -> Result<S3Source> {
    let client = S3Client::connect(
        connect.region.clone(),
        connect.endpoint.clone(),
        build_fetch_config(connect.concurrency),
    )?;
    let endpoint = client.endpoint_identity();
    Ok(S3Source {
        client,
        endpoint,
        bucket: target.bucket,
        prefix: target.prefix,
    })
}

fn validate_index_namespace(
    source_endpoint: &str,
    source_bucket: &str,
    source_prefix: &str,
    index_endpoint: &str,
    index_bucket: &str,
    index_root: &str,
) -> Result<()> {
    anyhow::ensure!(
        !index_root.is_empty(),
        "s3:// index location needs a prefix"
    );
    let covers_source =
        is_same_s3_bucket(source_endpoint, source_bucket, index_endpoint, index_bucket)
            && (source_prefix == index_root || source_prefix.starts_with(&list_prefix(index_root)));
    anyhow::ensure!(
        !covers_source,
        "index namespace s3://{index_bucket}/{index_root} contains source s3://{source_bucket}/{source_prefix}"
    );
    Ok(())
}

fn is_same_s3_bucket(
    first_endpoint: &str,
    first_bucket: &str,
    second_endpoint: &str,
    second_bucket: &str,
) -> bool {
    first_endpoint == second_endpoint && first_bucket == second_bucket
}

fn open_index_storage(
    source: &S3Source,
    index: &IndexArgs,
    concurrency: usize,
) -> Result<IndexStorage> {
    let target = match index.location.as_deref() {
        Some(location) => parse_s3_target(location)?,
        None => S3Target {
            bucket: source.bucket.clone(),
            prefix: build_index_namespace(&source.prefix),
        },
    };
    let root = target.prefix.trim_matches('/').to_owned();
    let client = if index.index_region.is_none() && index.index_endpoint.is_none() {
        source.client.clone()
    } else {
        S3Client::connect(
            index.index_region.clone(),
            index.index_endpoint.clone(),
            build_fetch_config(concurrency),
        )?
    };
    let endpoint = client.endpoint_identity();
    validate_index_namespace(
        &source.endpoint,
        &source.bucket,
        &source.prefix,
        &endpoint,
        &target.bucket,
        &root,
    )?;
    let cache = build_cache_dir(Some(&endpoint), &target.bucket, &root)?;
    Ok(IndexStorage {
        client,
        endpoint,
        bucket: target.bucket,
        root,
        cache,
    })
}

/// rg's rule: once any -e is given, every positional is a TARGET.
fn split_pattern_target(args: Vec<String>, regexp: Vec<String>) -> Result<(Vec<String>, String)> {
    if !regexp.is_empty() {
        let [target] = <[String; 1]>::try_from(args)
            .map_err(|_| anyhow::anyhow!("with -e/--regexp, provide exactly one TARGET"))?;
        return Ok((regexp, target));
    }
    let [pattern, target] = <[String; 2]>::try_from(args)
        .map_err(|_| anyhow::anyhow!("usage: seagrep PATTERN TARGET"))?;
    Ok((vec![pattern], target))
}

#[derive(Clone, Copy, ValueEnum)]
enum StrategyArg {
    Trigram,
    Sparse,
}

impl From<StrategyArg> for Strategy {
    fn from(value: StrategyArg) -> Strategy {
        match value {
            StrategyArg::Trigram => Strategy::Trigram,
            StrategyArg::Sparse => Strategy::Sparse,
        }
    }
}

fn parse_concurrency(value: &str) -> std::result::Result<usize, String> {
    let concurrency = value.parse::<usize>().map_err(|err| err.to_string())?;
    if concurrency == 0 {
        return Err("concurrency must be greater than 0".to_owned());
    }
    Ok(concurrency)
}

fn parse_positive_u64(value: &str) -> std::result::Result<u64, String> {
    let value = value.parse::<u64>().map_err(|error| error.to_string())?;
    if value == 0 {
        return Err("value must be greater than 0".to_owned());
    }
    Ok(value)
}

fn build_source_identity(source: &S3Source) -> SourceIdentity {
    SourceIdentity::S3 {
        endpoint: source.endpoint.clone(),
        bucket: source.bucket.clone(),
        prefix: list_prefix(&source.prefix),
    }
}

fn list_user_objects(
    src: &S3Source,
    index: &IndexStorage,
    progress: Option<&seagrep_core::ProgressSender>,
) -> Result<Vec<ObjectMeta>> {
    Ok(src
        .client
        .list_with_progress(&src.bucket, &list_prefix(&src.prefix), progress)?
        .into_iter()
        .filter(|object| {
            !is_index_key(&src.prefix, &object.key) && !index.contains_source_key(src, &object.key)
        })
        .collect())
}

fn build_s3(
    src: &S3Source,
    index: &IndexStorage,
    strategy: Option<Strategy>,
    rebuild: bool,
    purge_deleted: bool,
    show_progress: bool,
) -> Result<index::IndexResult> {
    let (progress, bar) = if show_progress {
        let (sender, receiver) = seagrep_core::ProgressSender::channel();
        let target = format!("s3://{}/{}", src.bucket, src.prefix);
        (
            Some(sender),
            Some(progress::IndexProgressBar::spawn(receiver, target)),
        )
    } else {
        (None, None)
    };
    let result = build_s3_inner(src, index, strategy, rebuild, purge_deleted, progress);
    if let Some(bar) = bar {
        bar.finish();
    }
    result
}

fn build_s3_inner(
    src: &S3Source,
    index: &IndexStorage,
    strategy: Option<Strategy>,
    rebuild: bool,
    purge_deleted: bool,
    progress: Option<seagrep_core::ProgressSender>,
) -> Result<index::IndexResult> {
    // Real sizes ride the listing so the build bounds its fetch chunks by
    // bytes, not just doc count — a bucket of huge objects must not OOM.
    let listing = list_user_objects(src, index, progress.as_ref())?
        .into_iter()
        .map(|object| (object.key, object.etag, object.size))
        .collect::<Vec<_>>();
    if let Some(progress) = &progress {
        progress.emit(seagrep_core::ProgressEvent::ListingComplete {
            objects: listing.len() as u64,
        });
    }
    let store = index.store_with_progress(progress.clone());
    let source = SourceIdentity::S3 {
        endpoint: src.endpoint.clone(),
        bucket: src.bucket.clone(),
        prefix: list_prefix(&src.prefix),
    };
    let client = src.client.clone();
    let bucket = src.bucket.clone();
    let report = update_index(
        store.as_ref(),
        index.cache(),
        &source,
        strategy,
        &listing,
        UpdateOptions {
            rebuild,
            purge_deleted,
            progress,
        },
        &|shard| {
            Ok(Box::new(S3Corpus::new(
                client.clone(),
                bucket.clone(),
                shard,
            )))
        },
    )?;
    Ok(index::IndexResult {
        report,
        location: index.location(),
    })
}

/// Run one search against the snapshot index bound to the source identity.
/// Scope filtering, stats, and undated-key notes are shared across outputs.
#[derive(Clone, Copy)]
struct SearchExecution<'a> {
    pattern: &'a str,
    scope: Option<&'a Scope>,
    options: MatchOptions,
    stats_line: bool,
}

fn pick_candidate_prefix<'a>(
    target_prefix: &'a str,
    key_prefix: Option<&'a str>,
) -> Option<&'a str> {
    let key_prefix = key_prefix.filter(|prefix| !prefix.is_empty());
    match key_prefix {
        Some(prefix) if prefix.starts_with(target_prefix) => Some(prefix),
        _ if target_prefix.is_empty() => None,
        _ => Some(target_prefix),
    }
}

fn execute_search(
    source: &S3Source,
    index: &IndexStorage,
    execution: SearchExecution<'_>,
    sink: &dyn MatchSink,
) -> Result<SearchStats> {
    let source_identity = build_source_identity(source);
    let key_filter = execution.scope.map(|scope| {
        move |key: &str| {
            scope
                .key_prefix()
                .is_none_or(|prefix| key.starts_with(prefix))
                && scope.matches(key)
        }
    });
    let key_matches = key_filter
        .as_ref()
        .map(|filter| filter as &(dyn Fn(&str) -> bool + Sync));
    let target_prefix = list_prefix(&source.prefix);
    let candidate_prefix =
        pick_candidate_prefix(&target_prefix, execution.scope.and_then(Scope::key_prefix));
    let search_stats = search_with_reopen(
        || {
            SegmentedReader::open(index.store(), index.cache(), &source_identity).with_context(
                || {
                    format!(
                        "index location: {} (default is the .seagrep namespace inside the searched bucket; pass --index if it lives elsewhere)",
                        index.location()
                    )
                },
            )
        },
        execution.pattern,
        KeyScope {
            prefix: candidate_prefix,
            matches: key_matches,
        },
        execution.options,
        sink,
    )?;
    if let Some(scope) = execution.scope {
        scope.report();
    }
    if search_stats.excluded_objects > 0 {
        eprintln!(
            "note: {} object(s) in this index could not be decoded and are not searchable (see the index build warnings)",
            search_stats.excluded_objects
        );
    }
    if execution.stats_line {
        eprintln!(
            "candidates={} total={} hits={}",
            search_stats.candidates, search_stats.total_docs, search_stats.hit_count,
        );
    }
    Ok(search_stats)
}

fn search_with_reopen(
    mut open: impl FnMut() -> Result<SegmentedReader>,
    pattern: &str,
    scope: KeyScope<'_>,
    options: MatchOptions,
    sink: &dyn MatchSink,
) -> Result<SearchStats> {
    let reader = open()?;
    match search_streaming(&reader, pattern, scope, options, sink) {
        Err(error) if error.is::<IndexChanged>() => {
            let reader = open()?;
            search_streaming(&reader, pattern, scope, options, sink)
        }
        result => result,
    }
}

/// Returns whether anything matched (drives the exit code).
fn run_search(args: SearchArgs) -> Result<bool> {
    let (patterns, target_raw) = split_pattern_target(args.args, args.regexp)?;
    let pattern = patterns::build_pattern(
        &patterns,
        args.fixed_strings,
        args.word_regexp,
        args.ignore_case,
        args.smart_case,
    )
    .with_context(|| format!("invalid pattern {:?}", patterns.join("|")))?;
    let globs = globs::build_glob_filter(&args.glob)?;
    let scope = Scope::from_args(
        args.key_prefix,
        args.key_regex,
        args.since,
        args.until,
        globs,
    )?;
    let standard_mode =
        !args.quiet && !args.json && !args.files_with_matches && !args.count && !args.count_matches;
    // standard output AND --json render context (rg emits context messages
    // on the JSON wire too); count/quiet/-l modes do not
    let renders_context = standard_mode || args.json;
    let before = args.before_context.or(args.context).unwrap_or(0);
    let after = args.after_context.or(args.context).unwrap_or(0);
    let options = MatchOptions {
        before_context: if renders_context { before } else { 0 },
        after_context: if renders_context { after } else { 0 },
        max_count: args.max_count,
    };

    let is_tty = std::io::stdout().is_terminal();
    let heading = if args.heading {
        true
    } else if args.no_heading {
        false
    } else {
        is_tty
    };
    let line_numbers = if args.line_number {
        true
    } else if args.no_line_number {
        false
    } else {
        args.column || is_tty
    };
    let color = printer::resolve_color(args.color, is_tty);

    let source = open_source(parse_s3_target(&target_raw)?, &args.connect)?;
    let index = open_index_storage(&source, &args.index, args.connect.concurrency)?;
    let stats_line = args.stats && !args.json;
    let execution = SearchExecution {
        pattern: &pattern,
        scope: scope.as_ref(),
        options,
        stats_line,
    };

    if args.quiet {
        let sink = printer::QuietSink::new(!args.stats);
        let result = execute_search(&source, &index, execution, &sink);
        return match result {
            Ok(_) => Ok(sink.matched()),
            // rg's quiet error-mask: a found match wins over later errors
            Err(_) if sink.matched() => Ok(true),
            Err(err) => Err(err),
        };
    }
    if args.json {
        let started = std::time::Instant::now();
        let sink = json::JsonSink::new();
        let stats = execute_search(&source, &index, execution, &sink)?;
        sink.write_summary(&stats, started.elapsed())?;
        return Ok(stats.hit_count > 0);
    }
    let sink: Box<dyn MatchSink> = if args.files_with_matches {
        Box::new(printer::PathSink::new(color))
    } else if args.count || args.count_matches {
        Box::new(printer::CountSink::new(args.count_matches, color))
    } else {
        Box::new(printer::StandardSink::new(
            printer::RenderConfig {
                heading,
                line_numbers,
                column: args.column,
                context_active: options.before_context > 0 || options.after_context > 0,
                text: args.text,
            },
            color,
        ))
    };
    let stats = execute_search(&source, &index, execution, sink.as_ref())?;
    Ok(stats.hit_count > 0)
}

fn run() -> Result<bool> {
    let cli = Cli::parse();
    match cli.cmd {
        Some(Cmd::Index {
            target,
            index,
            strategy,
            rebuild,
            purge_deleted,
            watch: _,
            interval,
            json,
            connect,
        }) => {
            let interval = interval.map(Duration::from_secs);
            let strategy = strategy.map(Into::into);
            let config = index::IndexConfig {
                target: &target,
                interval,
                rebuild,
                json,
            };
            let started = std::time::Instant::now();
            let (source, storage) = match (|| -> Result<(S3Source, IndexStorage)> {
                let source = open_source(parse_s3_target(&target)?, &connect)?;
                let storage = open_index_storage(&source, &index, connect.concurrency)?;
                Ok((source, storage))
            })() {
                Ok(opened) => opened,
                Err(error) => {
                    index::write_start_error(&target, json, started.elapsed(), &error)?;
                    return Err(error);
                }
            };
            let show_progress = !json && std::io::stderr().is_terminal();
            index::run_index(config, |cycle_rebuild| {
                build_s3(
                    &source,
                    &storage,
                    strategy,
                    cycle_rebuild,
                    purge_deleted,
                    show_progress,
                )
            })?;
            Ok(true)
        }
        None => run_search(cli.search),
    }
}

fn main() -> std::process::ExitCode {
    match run() {
        Ok(true) => std::process::ExitCode::SUCCESS,
        Ok(false) => std::process::ExitCode::from(1),
        Err(err) => {
            eprintln!("seagrep: {err:#}");
            std::process::ExitCode::from(2)
        }
    }
}

/// Cache dir per (endpoint, bucket, prefix): readable bucket name plus a
/// short hash so `a/b` vs `a__b` prefixes (or the same bucket name on two
/// endpoints) can never share state.
fn build_cache_dir(endpoint: Option<&str>, bucket: &str, prefix: &str) -> Result<PathBuf> {
    let mut path = seagrep_core::cache_home()?;
    path.push("seagrep");
    let scope = format!("{}\0{bucket}\0{prefix}", endpoint.unwrap_or(""));
    path.push(format!(
        "{bucket}-{:016x}",
        seagrep_core::hash_cache_scope(scope.as_bytes())
    ));
    Ok(path)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cli_args_are_consistent() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    #[test]
    fn picks_most_selective_candidate_prefix() {
        assert_eq!(pick_candidate_prefix("", None), None);
        assert_eq!(pick_candidate_prefix("", Some("")), None);
        assert_eq!(pick_candidate_prefix("", Some("logs/")), Some("logs/"));
        assert_eq!(pick_candidate_prefix("logs/", None), Some("logs/"));
        assert_eq!(
            pick_candidate_prefix("logs/", Some("logs/2026/")),
            Some("logs/2026/")
        );
        assert_eq!(
            pick_candidate_prefix("logs/app/", Some("logs/")),
            Some("logs/app/")
        );
        assert_eq!(
            pick_candidate_prefix("logs/", Some("metrics/")),
            Some("logs/")
        );
    }

    #[test]
    fn parse_s3_target_forms() {
        assert!(matches!(
            parse_s3_target("s3://bkt").unwrap(),
            S3Target { bucket, prefix } if bucket == "bkt" && prefix.is_empty()
        ));
        assert!(matches!(
            parse_s3_target("s3://bkt/a/b").unwrap(),
            S3Target { bucket, prefix } if bucket == "bkt" && prefix == "a/b"
        ));
        assert!(matches!(
            parse_s3_target("s3://bkt/a//b/").unwrap(),
            S3Target { bucket, prefix } if bucket == "bkt" && prefix == "a//b/"
        ));
        assert!(parse_s3_target("s3://").is_err());
    }

    #[test]
    fn split_pattern_target_rules() {
        let (pats, target) =
            split_pattern_target(vec!["ERROR".into(), "s3://b".into()], vec![]).unwrap();
        assert_eq!(pats, vec!["ERROR"]);
        assert_eq!(target, "s3://b");
        let (pats, target) =
            split_pattern_target(vec!["s3://b".into()], vec!["a".into(), "b".into()]).unwrap();
        assert_eq!(pats, vec!["a", "b"]);
        assert_eq!(target, "s3://b");
        assert!(split_pattern_target(vec!["onlypattern".into()], vec![]).is_err());
        assert!(split_pattern_target(vec!["t1".into(), "t2".into()], vec!["p".into()]).is_err());
    }

    #[test]
    fn clap_parses_rg_style_invocations() {
        // subcommand wins the first positional
        let cli = Cli::try_parse_from(["seagrep", "index", "s3://b", "--purge-deleted"]).unwrap();
        assert!(matches!(
            cli.cmd,
            Some(Cmd::Index {
                purge_deleted: true,
                ..
            })
        ));
        // -e escape hatch searches for the literal word "index"
        let cli = Cli::try_parse_from(["seagrep", "-e", "index", "s3://b"]).unwrap();
        assert!(cli.cmd.is_none());
        assert_eq!(cli.search.regexp, vec!["index"]);
        // last case flag wins
        let cli = Cli::try_parse_from(["seagrep", "-i", "-s", "p", "t"]).unwrap();
        assert!(cli.search.case_sensitive && !cli.search.ignore_case);
        // --json conflicts with -c
        assert!(Cli::try_parse_from(["seagrep", "--json", "-c", "p", "t"]).is_err());
    }

    #[test]
    fn clap_parses_independent_index_locations() {
        let cli = Cli::try_parse_from([
            "seagrep",
            "index",
            "s3://source/logs",
            "--index",
            "s3://search-index/seagrep/logs",
            "--index-region",
            "us-west-2",
            "--index-endpoint",
            "http://127.0.0.1:9000",
        ])
        .unwrap();
        let Some(Cmd::Index { index, .. }) = cli.cmd else {
            panic!("expected index command");
        };
        assert_eq!(
            index.location.as_deref(),
            Some("s3://search-index/seagrep/logs")
        );
        assert_eq!(index.index_region.as_deref(), Some("us-west-2"));
        assert_eq!(
            index.index_endpoint.as_deref(),
            Some("http://127.0.0.1:9000")
        );
        assert!(Cli::try_parse_from([
            "seagrep",
            "needle",
            "s3://source/logs",
            "--index-region",
            "us-west-2"
        ])
        .is_err());
    }

    #[test]
    fn s3_index_location_rejects_bucket_root() {
        let error = validate_index_namespace(
            "https://source",
            "source",
            "logs",
            "https://index",
            "index",
            "",
        )
        .unwrap_err();
        assert_eq!(error.to_string(), "s3:// index location needs a prefix");
    }

    #[test]
    fn s3_index_location_rejects_a_source_covered_by_its_namespace() {
        let error = validate_index_namespace(
            "https://s3.us-east-1.amazonaws.com",
            "bucket",
            "logs/app",
            "https://s3.us-east-1.amazonaws.com",
            "bucket",
            "logs",
        )
        .unwrap_err();
        assert_eq!(
            error.to_string(),
            "index namespace s3://bucket/logs contains source s3://bucket/logs/app"
        );
        validate_index_namespace(
            "https://s3",
            "bucket",
            "logs",
            "https://s3",
            "bucket",
            "logs/index",
        )
        .unwrap();
        validate_index_namespace(
            "https://s3",
            "source",
            "logs",
            "https://s3",
            "index",
            "logs",
        )
        .unwrap();
        validate_index_namespace(
            "https://aws",
            "bucket",
            "logs/app",
            "http://minio",
            "bucket",
            "logs",
        )
        .unwrap();
    }
}