Repository navigation
Expand file tree
/
Copy pathsearch.rs
More file actions
2357 lines (2127 loc) · 88 KB
/
Copy pathsearch.rs
File metadata and controls
2357 lines (2127 loc) · 88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Shared search-output filter for `rtk grep` and `rtk rg`.
//!
//! Runs the agent's exact engine (grep or rg) — never substituting one for the other — and
//! compresses its output by grouping matches by file, capping, and teeing overflow.
use crate::core::arg_tokenizer::{self, Dialect, Token, TokenKind, ValueSpec};
use crate::core::guard::never_worse;
use crate::core::stream::{
self, CaptureResult, FilterMode, StdinMode, StreamFilter, exec_capture, exec_capture_stdin,
};
use crate::core::tracking;
use crate::core::utils::{ChildArgExt, resolved_command, strip_ansi};
use crate::core::{args_utils, config};
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashMap;
use std::io::IsTerminal;
use std::process::Command;
use std::sync::LazyLock;
/// True if stdin is something the engine actually reads: a regular file, FIFO or socket --
/// ripgrep's own `is_readable_stdin` rule, and confirmed for both engines (`rg foo < file`
/// searches the file; `rg foo < /dev/null`, a character device, searches the cwd instead).
/// `!is_terminal()` is wider and wrongly matches that `/dev/null` case.
#[cfg(unix)]
fn stdin_is_readable() -> bool {
use std::os::fd::AsFd;
use std::os::unix::fs::FileTypeExt;
std::io::stdin()
.as_fd()
.try_clone_to_owned()
.map(std::fs::File::from)
.and_then(|f| f.metadata())
.map(|m| {
let kind = m.file_type();
kind.is_file() || kind.is_fifo() || kind.is_socket()
})
.unwrap_or(false)
}
/// KNOWN LIMITATION: no portable file-type check here, so Windows keeps the wider
/// `!is_terminal()` rule -- `rtk rg foo < NUL` still routes to the streaming path and drops
/// filenames there.
#[cfg(not(unix))]
fn stdin_is_readable() -> bool {
!std::io::stdin().is_terminal()
}
/// Which flags consume a value, transcribed per engine from that engine's own `--help`.
/// grep and rg only intersect -- 13 of ~50 entries -- and disagree outright on `-T`, `-r`,
/// `-E` and `--color`, so one merged table with per-flag exceptions misreads whichever engine
/// it wasn't written for. `-e`/`--regexp`'s value is routed to `patterns` downstream, not
/// `flags`; both tables still report it, since this only answers "does the next token belong
/// to this flag".
fn grep_takes_value(kind: TokenKind, name: &str) -> bool {
match kind {
// `--color[=WHEN]`/`--colour[=WHEN]` attach their value, so they never consume a token.
TokenKind::Long => matches!(
name,
"after-context"
| "before-context"
| "binary-files"
| "context"
| "devices"
| "directories"
| "exclude"
| "exclude-dir"
| "exclude-from"
| "file"
| "group-separator"
| "include"
| "label"
| "max-count"
| "regexp"
),
// `-X` is grep's undocumented matcher selector, still accepted and still value-taking.
TokenKind::Short => matches!(name, "A" | "B" | "C" | "D" | "X" | "d" | "e" | "f" | "m"),
_ => false,
}
}
fn rg_takes_value(kind: TokenKind, name: &str) -> bool {
match kind {
TokenKind::Long => matches!(
name,
"after-context"
| "before-context"
| "color"
| "colors"
| "context"
| "context-separator"
| "dfa-size-limit"
| "encoding"
| "engine"
| "field-context-separator"
| "field-match-separator"
| "file"
| "generate"
| "glob"
| "hostname-bin"
| "hyperlink-format"
| "iglob"
| "ignore-file"
| "max-columns"
| "max-count"
| "max-depth"
| "max-filesize"
| "path-separator"
| "pre"
| "pre-glob"
| "regex-size-limit"
| "regexp"
| "replace"
| "sort"
| "sortr"
| "threads"
| "type"
| "type-add"
| "type-clear"
| "type-not"
),
TokenKind::Short => matches!(
name,
"A" | "B" | "C" | "E" | "M" | "T" | "d" | "e" | "f" | "g" | "j" | "m" | "r" | "t"
),
_ => false,
}
}
/// rg accepts the attached spellings `-A=1`/`-e=PAT` and strips the `=` itself; GNU grep does
/// not ("invalid context length argument"), so only rg's is unwrapped. Attached only: a
/// separate-token value is the user's own text, and `rg -e '=='` must search for `==`.
fn unwrap_attached_value(engine: Engine, value: &str) -> &str {
match engine {
Engine::Rg => value.strip_prefix('=').unwrap_or(value),
Engine::Grep => value,
}
}
/// The module's single tokenizer entry point. Shared so a pre-check and `extract_pattern_path`
/// cannot classify the same argument differently.
fn tokenize_search_args<'a, T: AsRef<str>>(args: &'a [T], engine: Engine) -> Vec<Token<'a>> {
arg_tokenizer::tokenize_grammar(
args,
&|kind, name| search_takes_value(engine, kind, name),
Dialect::Posix,
)
}
/// Every grep/rg value-taking flag claims even a literal `--` as its value, unlike git/cargo --
/// verified against both engines for short and long, numeric- and file-typed flags alike.
fn search_takes_value(engine: Engine, kind: TokenKind, name: &str) -> Option<ValueSpec> {
let takes = match engine {
Engine::Grep => grep_takes_value(kind, name),
Engine::Rg => rg_takes_value(kind, name),
};
takes.then(|| ValueSpec::value().claiming_dash_dash())
}
/// Unique, descriptive tee slug for a file's overflow matches. `idx` disambiguates
/// files within one grep; the tee filename's epoch handles separate runs.
fn grep_slug(idx: usize, path: &str) -> String {
let cleaned: String = path
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let tail = &cleaned[cleaned.len().saturating_sub(32)..];
format!("grep_{}_{}", idx, tail)
}
/// Format a file's matches as `path<sep>line<sep>content`. Tee blocks use the
/// real (un-compacted) `path` so recovered lines stay openable.
fn match_block(path: &str, entries: &[(usize, bool, String)]) -> String {
let mut s = String::new();
for (line_num, is_match, content) in entries {
let sep = if *is_match { ':' } else { '-' };
s.push_str(&format!("{}{}{}{}{}\n", path, sep, line_num, sep, content));
}
s
}
/// Extracts `(patterns, paths, flags, has_format_flag, detected)` from the raw trailing args.
/// `patterns` is the positional pattern plus all `-e`/`--regexp` values (empty → error); `paths`
/// is the remaining positionals (empty → caller defaults to `["."]`); `flags` is everything else
/// forwarded verbatim; `has_format_flag`/`detected` ([`DetectedFlags`]) are computed from this
/// same token pass rather than a second scan over the reconstructed `flags` strings.
fn extract_pattern_path<T: AsRef<str>>(
args: &[T],
engine: Engine,
) -> (Vec<String>, Vec<String>, Vec<String>, bool, DetectedFlags) {
let tokens = tokenize_search_args(args, engine);
let mut e_patterns: Vec<String> = Vec::new();
let mut patterns_from_file = false;
let mut positionals: Vec<String> = Vec::new();
let mut flags: Vec<String> = Vec::new();
let mut has_format_flag = false;
// `None` until the user says either way; the last spelling wins, as both engines do.
let mut show_file_flag: Option<bool> = None;
let mut show_line_flag: Option<bool> = None;
let mut recursive = false;
let mut context = false;
let mut i = 0;
while i < tokens.len() {
let t = &tokens[i];
match t.kind {
TokenKind::Long if t.text == "regexp" => {
if let Some(v) = t.value(&tokens) {
e_patterns.push(v.to_string());
}
}
TokenKind::Long => {
if t.text == "file" {
patterns_from_file = true;
}
if is_format_flag_token(engine, t.kind, t.text) {
has_format_flag = true;
}
if is_show_file_token(t.kind, t.text) {
show_file_flag = Some(true);
}
if is_recursive_token(engine, t.kind, t.text) {
recursive = true;
}
if is_show_line_on_token(t.kind, t.text) {
show_line_flag = Some(true);
}
// Neither negation is forwarded: RTK forces `-nH` so it can parse the output,
// and the user's `--no-filename`/`--no-line-number` would win as the later
// flag, leaving nothing parseable and forcing a second run of the whole search.
if is_show_file_off_token(engine, t.kind, t.text) {
show_file_flag = Some(false);
i += 1;
continue;
}
if is_show_line_off_token(engine, t.kind, t.text) {
show_line_flag = Some(false);
i += 1;
continue;
}
if is_context_token(engine, t.kind, t.text) {
context = true;
}
match t.attached {
Some(v) => flags.push(format!("--{}={v}", t.text)),
None => {
flags.push(format!("--{}", t.text));
if let Some(v) = t.value(&tokens) {
flags.push(v.to_string());
}
}
}
}
// A value consumed by a preceding flag is handled there instead.
TokenKind::Positional if t.is_free_positional() => {
positionals.push(t.text.to_string());
}
TokenKind::Short => {
// A cluster's boolean prefix (e.g. "r" in "-rA") stays glued into one
// flag string, matching how the user typed it; only the trailing
// value-taking char (if any) and its value are their own tokens.
let source = t.source_index;
let start = i;
while i + 1 < tokens.len()
&& tokens[i + 1].kind == TokenKind::Short
&& tokens[i + 1].source_index == source
{
i += 1;
}
let cluster = &tokens[start..=i];
if cluster
.iter()
.any(|c| is_format_flag_token(engine, c.kind, c.text))
{
has_format_flag = true;
}
// Letter by letter, so `-hH` and `-Hh` land where the engine lands them: the
// later spelling wins.
for c in cluster {
if is_show_file_token(c.kind, c.text) {
show_file_flag = Some(true);
} else if is_show_file_off_token(engine, c.kind, c.text) {
show_file_flag = Some(false);
}
if is_show_line_on_token(c.kind, c.text) {
show_line_flag = Some(true);
} else if is_show_line_off_token(engine, c.kind, c.text) {
show_line_flag = Some(false);
}
if is_recursive_token(engine, c.kind, c.text) {
recursive = true;
}
}
if cluster
.iter()
.any(|c| is_context_token(engine, c.kind, c.text))
{
context = true;
}
let (bool_chars, value_char) = match cluster.split_last() {
Some((last, rest))
if search_takes_value(engine, TokenKind::Short, last.text).is_some() =>
{
(rest, Some(last))
}
_ => (cluster, None),
};
// `-h` drops out of the cluster for the same reason as its long form: RTK
// forces `-H` to parse the output and the user's later `-h` would win.
let glued: String = bool_chars
.iter()
.filter(|c| {
!is_show_file_off_token(engine, c.kind, c.text)
&& !is_show_line_off_token(engine, c.kind, c.text)
})
.map(|c| c.text)
.collect();
if !glued.is_empty() {
flags.push(format!("-{glued}"));
}
if let Some(vt) = value_char {
let value = match vt.attached {
Some(attached) => Some(unwrap_attached_value(engine, attached)),
None => vt.value(&tokens),
};
if vt.text == "e" {
match value {
Some(v) => e_patterns.push(v.to_string()),
None => flags.push("-e".to_string()),
}
} else {
if vt.text == "f" {
patterns_from_file = true;
}
flags.push(format!("-{}", vt.text));
if let Some(v) = value {
flags.push(v.to_string());
}
}
}
}
// DashDash itself carries nothing to emit — the `--` boundary is handled by the
// tokenizer (everything after it already comes back as Positional).
_ => {}
}
i += 1;
}
// `-e`/`--regexp` and `-f`/`--file` both supply the patterns, so every positional is a
// path. Taking the first one as the pattern instead left `paths` empty, which made the
// engine read stdin (a hang under an agent harness) or walk the cwd.
let (patterns, paths) = if !e_patterns.is_empty() || patterns_from_file {
(e_patterns, positionals)
} else {
let paths = positionals.iter().skip(1).cloned().collect();
let patterns = positionals.into_iter().take(1).collect();
(patterns, paths)
};
let detected = DetectedFlags {
show_file: show_file_flag,
show_line: show_line_flag.unwrap_or(false),
recursive,
context,
};
(patterns, paths, flags, has_format_flag, detected)
}
fn unparsed_signal(stdout: &str) -> usize {
stdout
.lines()
.filter(|line| {
let trimmed = line.trim();
!trimmed.is_empty() && trimmed != "--" && parse_match_line(line).is_none()
})
.count()
}
/// Run real grep so matches and the savings baseline match the agent's command;
/// rg is the fallback when grep is absent, rejects a flag, or `--type` is used.
/// The search engine the agent actually invoked. RTK runs this binary verbatim
/// and never substitutes one for the other.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Engine {
Grep,
Rg,
}
impl Engine {
fn bin(self) -> &'static str {
match self {
Engine::Grep => "grep",
Engine::Rg => "rg",
}
}
pub fn label(self) -> &'static str {
self.bin()
}
/// `-n -H --null` are parse aids (NUL keeps the regroup unambiguous, #1436);
/// `-I` skips binary noise (-a overrides).
fn parse_flags(self) -> &'static [&'static str] {
match self {
Engine::Grep => &["-n", "-H", "-I", "--null"],
Engine::Rg => &["-n", "--with-filename", "--null"],
}
}
}
/// Runs the agent's exact engine + flags for the grouping path, appending only the
/// parse aids (see `Engine::parse_flags`).
fn engine_capture<T: AsRef<str>>(
engine: Engine,
extra_args: &[T],
patterns: &[String],
paths: &[String],
) -> Result<CaptureResult> {
let mut cmd = engine_command(engine, extra_args, patterns, paths, false);
exec_capture_stdin(&mut cmd).context("search failed")
}
fn engine_command<T: AsRef<str>>(
engine: Engine,
extra_args: &[T],
patterns: &[String],
paths: &[String],
line_buffered: bool,
) -> Command {
let mut cmd = resolved_command(engine.bin());
cmd.child_args(engine.parse_flags());
for a in extra_args {
cmd.child_arg(a.as_ref());
}
if line_buffered {
// The engine writes through a pipe, so flush each match immediately.
cmd.child_arg("--line-buffered");
}
for p in patterns {
cmd.child_args(["-e", p]);
}
cmd.child_arg("--");
cmd.child_args(paths);
cmd
}
fn format_match_line(line: &str, show_file: bool, show_line: bool) -> Option<String> {
let (file, line_num, is_match, content) = parse_match_line(line)?;
let sep = if is_match { ':' } else { '-' };
let mut output = String::new();
if show_file {
output.push_str(&file);
output.push(sep);
}
if show_line {
output.push_str(&line_num.to_string());
output.push(sep);
}
output.push_str(content);
output.push('\n');
Some(output)
}
/// Emits each piped match as it arrives. Buffered search waits for EOF, so
/// `tail -f app.log | rtk grep ERROR` would otherwise show no matches.
struct SearchStreamFilter {
show_file: bool,
show_line: bool,
max_results: usize,
shown: usize,
cap_reported: bool,
}
impl StreamFilter for SearchStreamFilter {
fn feed_line(&mut self, line: &str) -> Option<String> {
let Some(output) = format_match_line(line, self.show_file, self.show_line) else {
if line == "--" && self.shown >= self.max_results {
return None;
}
return Some(format!("{line}\n"));
};
if self.shown >= self.max_results {
if self.cap_reported {
return None;
}
self.cap_reported = true;
return Some(format!(
"[rtk] output capped at {} results\n",
self.max_results
));
}
self.shown += 1;
Some(output)
}
fn flush(&mut self) -> String {
String::new()
}
}
/// The paths-based half of "should the filename be shown": multiple paths, or a directory among
/// them, regardless of any flag. Combined with `extract_pattern_path`'s pre-computed
/// `DetectedFlags::show_file` (the flags-based half) at each call site.
fn wants_show_file(paths: &[String], flags_show_file: bool) -> bool {
paths.len() > 1 || paths.iter().any(|p| std::path::Path::new(p).is_dir()) || flags_show_file
}
#[allow(clippy::too_many_arguments)]
fn run_streaming_search(
timer: &tracking::TimedExecution,
engine: Engine,
extra_args: &[String],
patterns: &[String],
paths: &[String],
max_results: usize,
real_cmd: &str,
detected_flags: DetectedFlags,
) -> Result<i32> {
let filter = SearchStreamFilter {
show_file: detected_flags
.show_file
.unwrap_or_else(|| wants_show_file(paths, detected_flags.recursive)),
show_line: detected_flags.show_line,
max_results,
shown: 0,
cap_reported: false,
};
let mut cmd = engine_command(engine, extra_args, patterns, paths, true);
let result = stream::run_streaming(
&mut cmd,
StdinMode::Inherit,
FilterMode::Streaming(Box::new(filter)),
)
.context("search failed")?;
timer.track(
real_cmd,
&format!("rtk {}", engine.label()),
&result.raw_stdout,
&result.filtered,
);
Ok(result.exit_code)
}
/// Runs the agent's command verbatim for forms RTK does not group: format/shape
/// flags and pattern-less modes (`--files`, `--type-list`).
///
/// One exception: a bare file list (`-l`/`-L`/`--files`, see [`is_bare_file_list`]) has its
/// shared directory prefix folded into a header when captured. The streaming form reads
/// stdin, where the only "file" is `(standard input)`, so it has nothing to fold.
fn passthrough<T: AsRef<str>>(
timer: &tracking::TimedExecution,
engine: Engine,
args: &[T],
real_cmd: &str,
stream_stdin: bool,
fold_file_list: bool,
) -> Result<i32> {
let mut cmd = resolved_command(engine.bin());
if stream_stdin && !std::io::stdout().is_terminal() {
// Keep passthrough output live when stdout is piped.
cmd.child_arg("--line-buffered");
}
for a in args {
cmd.child_arg(a.as_ref());
}
if stream_stdin {
let exit_code =
stream::run_streaming(&mut cmd, StdinMode::Inherit, FilterMode::Passthrough)
.context("search failed")?
.exit_code;
timer.track_passthrough(real_cmd, &format!("rtk {} (passthrough)", real_cmd));
return Ok(exit_code);
}
let result = exec_capture_stdin(&mut cmd).context("search failed")?;
let cleaned = strip_ansi(&result.stdout);
let folded = if fold_file_list {
fold_path_prefix(&cleaned).filter(|f| never_worse(&cleaned, f) == f)
} else {
None
};
match &folded {
Some(folded) => print!("{}", folded),
None => print!("{}", cleaned),
}
if !result.stderr.is_empty() {
eprint!("{}", result.stderr);
}
match &folded {
// Real sizes, so the fold shows up in `rtk gain`.
Some(folded) => timer.track(
real_cmd,
&format!("rtk {}", engine.label()),
&cleaned,
folded,
),
// 0/0 keeps an unchanged passthrough from diluting the savings statistics.
None => timer.track_passthrough(real_cmd, &format!("rtk {} (passthrough)", real_cmd)),
}
Ok(result.exit_code)
}
/// Folds the directory prefix every line of a file list shares into a one-line header, then
/// emits each path's remaining tail in engine order:
///
/// ```text
/// /home/u/proj/src/ (3 files)
/// a/foo.rs
/// a/bar.rs
/// b/baz.rs
/// ```
///
/// Agents search from absolute roots, so `-l` output restates the same long prefix on every
/// line; that prefix is the whole redundancy of the list. The transform is lossless (each path
/// is `prefix + tail`) and needs no cap or tee. `None` when there is nothing to fold: fewer
/// than two lines, a line that is not a plain path (empty, NUL-joined under `-Z`, carrying a
/// `\r` that `lines()` would drop, or an escape such as an rg `--hyperlink-format` OSC 8 link
/// that `strip_ansi` leaves in place), or no shared directory component. The prefix is cut on whole components, never inside one, so
/// `/a/foobar/x` and `/a/foobaz/y` share `/a/`, not `/a/fooba`.
///
/// KNOWN LIMITATION: only `/` separates components, so Windows-style `\` paths never fold.
fn fold_path_prefix(raw: &str) -> Option<String> {
// Checked on the raw text: `lines()` would already have dropped a `\r` before `\n`.
if raw.contains(['\0', '\r', '\x1b']) {
return None;
}
let paths: Vec<&str> = raw.lines().collect();
if paths.len() < 2 || paths.iter().any(|p| p.is_empty()) {
return None;
}
fn dirs(path: &str) -> Vec<&str> {
match path.rsplit_once('/') {
Some((dir, _)) => dir.split('/').collect(),
None => Vec::new(),
}
}
let first = dirs(paths[0]);
let mut common = first.len();
for path in &paths[1..] {
let shared = dirs(path)
.iter()
.zip(&first)
.take(common)
.take_while(|(a, b)| a == b)
.count();
common = shared;
if common == 0 {
return None;
}
}
// An absolute path splits to a leading empty component, so `/a/b` rejoins with its slash;
// a bare `/` root is the one prefix that saves nothing.
let prefix = format!("{}/", first[..common].join("/"));
if prefix.len() <= 1 {
return None;
}
let mut out = format!("{} ({} files)\n", prefix, paths.len());
for path in &paths {
out.push_str(path.strip_prefix(&prefix).unwrap_or(path));
out.push('\n');
}
Some(out)
}
pub fn run(
engine: Engine,
max_line_len: usize,
max_results: usize,
context_only: bool,
args: &[String],
verbose: u8,
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Restored first: every check below classifies these args, and clap ate the boundary.
let args = &args_utils::restore_double_dash(args);
// --version / --help: pass through to the engine without filtering. Token-based and
// scoped before the boundary, because `rtk grep -- --version` searches *for* that string.
// `-h` is engine-specific: rg's is --help, grep's is --no-filename.
let help_tokens = tokenize_search_args(args, engine);
let asks_for_help = arg_tokenizer::before_dashdash(&help_tokens)
.iter()
.any(|t| {
(t.kind == TokenKind::Long && matches!(t.text, "version" | "help"))
|| (t.kind == TokenKind::Short && t.text == "h" && engine == Engine::Rg)
});
let dangling_value_flag = help_tokens.iter().any(|t| {
matches!(t.kind, TokenKind::Long | TokenKind::Short)
&& search_takes_value(engine, t.kind, t.text).is_some()
&& t.value(&help_tokens).is_none()
});
if dangling_value_flag {
let real_cmd = format!("{} {}", engine.bin(), args.join(" "));
return passthrough(&timer, engine, args, &real_cmd, false, false);
}
if asks_for_help {
let mut cmd = resolved_command(engine.bin());
cmd.child_args(args);
let result = exec_capture(&mut cmd).context("search failed")?;
print!("{}", result.stdout);
if !result.stderr.is_empty() {
eprint!("{}", result.stderr);
}
return Ok(result.exit_code);
}
let real_cmd = format!("{} {}", engine.label(), args.join(" "));
let rtk_label = format!("rtk {}", engine.label());
let (patterns, paths, extra_args, extra_args_has_format_flag, detected_flags) =
extract_pattern_path(args, engine);
if patterns.is_empty() {
// `rg --files` lists paths without a pattern; fold it like `-l`.
let fold = is_bare_file_list(engine, args);
return passthrough(&timer, engine, args, &real_cmd, false, fold);
}
let pattern_display = if patterns.len() == 1 {
patterns[0].clone()
} else {
patterns.join("|")
};
let path_display = paths.join(" ");
if verbose > 0 {
eprintln!("grep: '{}' in {}", pattern_display, path_display);
}
let reads_piped_stdin =
stdin_is_readable() && (paths.is_empty() || paths.iter().any(|path| path == "-"));
// format/shape flags (-c/-l/-o/...): already-minimal native output, passthrough.
if extra_args_has_format_flag {
let fold = is_bare_file_list(engine, args);
return passthrough(&timer, engine, args, &real_cmd, reads_piped_stdin, fold);
}
if reads_piped_stdin {
return run_streaming_search(
&timer,
engine,
&extra_args,
&patterns,
&paths,
max_results,
&real_cmd,
detected_flags,
);
}
let result = engine_capture(engine, &extra_args, &patterns, &paths)?;
let exit_code = result.exit_code;
let raw_output = result.stdout.clone();
// Unparseable shape re-runs verbatim below (with its own stderr), so handle it
// before surfacing this run's stderr (#2333).
if unparsed_signal(&raw_output) > 0 {
return passthrough(&timer, engine, args, &real_cmd, false, false);
}
if !result.stderr.is_empty() {
eprint!("{}", result.stderr);
}
if result.stdout.trim().is_empty() {
timer.track(&real_cmd, &rtk_label, &raw_output, "");
return Ok(exit_code);
}
let context_re = if context_only {
Regex::new(&format!(
"(?i).{{0,20}}{}.*",
regex::escape(&pattern_display)
))
.ok()
} else {
None
};
let mut by_file: HashMap<String, Vec<(usize, bool, String)>> = HashMap::new();
for line in raw_output.lines() {
let Some((file, line_num, is_match, content)) = parse_match_line(line) else {
continue;
};
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), &pattern_display);
by_file
.entry(file)
.or_default()
.push((line_num, is_match, cleaned));
}
let total_matches: usize = by_file
.values()
.flat_map(|v| v.iter())
.filter(|(_, is_match, _)| *is_match)
.count();
// Mirror what the real command prints: the filename only when grep/rg would
// show one (multiple files, a directory, -r or -H), the line number only with
// -n. We force -nH--null for robust parsing, then drop what the engine itself
// would not have shown.
// With no path given, rg walks the cwd, and there the filename is the only way to tell
// matches apart -- real rg prints it even when a single file matched. grep with no path
// reads stdin instead (whatever stdin is), where a filename would be `(standard input)`,
// so the same reasoning does not carry over.
let walks_cwd = engine == Engine::Rg && paths.is_empty();
let show_file = detected_flags.show_file.unwrap_or_else(|| {
by_file.len() > 1 || walks_cwd || wants_show_file(&paths, detected_flags.recursive)
});
let show_line = detected_flags.show_line;
// Faithful baseline: exactly what the real command prints, full content.
let mut plain = String::new();
for line in raw_output.lines() {
let Some(output) = format_match_line(line, show_file, show_line) else {
if line == "--" {
plain.push_str("--\n");
}
continue;
};
plain.push_str(&output);
}
let has_context = detected_flags.context;
let per_file = config::limits().grep_max_per_file;
let mut files: Vec<_> = by_file.iter().collect();
files.sort_by_key(|(f, _)| *f);
let mut body = String::new();
let mut shown = 0;
let mut skipped_files = 0;
let mut skipped_block = String::new();
for (idx, (file, entries)) in files.into_iter().enumerate() {
if shown >= max_results {
skipped_files += 1;
skipped_block.push_str(&match_block(file, entries));
continue;
}
let file_display = compact_path(file);
let mut file_shown = 0;
let mut prev_line: usize = 0;
for (line_num, is_match, content) in entries.iter().take(per_file) {
if shown >= max_results {
break;
}
if has_context && prev_line > 0 && *line_num > prev_line + 1 {
body.push_str("--\n");
}
prev_line = *line_num;
let sep = if *is_match { ':' } else { '-' };
if show_file {
body.push_str(&file_display);
body.push(sep);
}
if show_line {
body.push_str(&line_num.to_string());
body.push(sep);
}
body.push_str(content);
body.push('\n');
shown += 1;
file_shown += 1;
}
let remaining = entries.len() - file_shown;
if remaining == 0 {
continue;
}
// Tee the file's full matches (real path) so the tail hint recovers them
// openably, skipping the lines already shown.
let full_block = match_block(file, entries);
match crate::core::tee::force_tee_tail_hint(
&full_block,
&grep_slug(idx, file),
file_shown + 1,
) {
Some(hint) => body.push_str(&format!(
" +{} more in {} {}\n",
remaining, file_display, hint
)),
None => body.push_str(&format!(" +{} more in {}\n", remaining, file_display)),
}
}
if skipped_files > 0 {
let hint = crate::core::tee::force_tee_tail_hint(&skipped_block, "grep_skipped", 1)
.map(|h| format!(" {}", h))
.unwrap_or_default();
body.push_str(&format!("+{} more files{}\n", skipped_files, hint));
}
// Switch to the grouped form only when capping actually shrank the output;
// otherwise emit the faithful baseline, so RTK never exceeds the real command.
let capped = shown < total_matches || skipped_files > 0;
let rtk_output = if capped {
format!(
"{} matches in {} files:\n\n{}",
total_matches,
by_file.len(),
body
)
} else {
body
};
let output = if capped && rtk_output.len() < plain.len() {
rtk_output
} else {
plain
};
print!("{}", output);
timer.track(&real_cmd, &rtk_label, &raw_output, &output);
Ok(exit_code)
}
/// Parses a single rg/grep match or context line of the form `file\0line_number[:-]content`.
/// Requires `-0`/`--null` so the filename is NUL-separated -- NUL can't appear in file paths,
/// so this stays unambiguous even with `:` in the content or path. The `bool` is `true` for a
/// match line (`:` separator), `false` for context (`-`, from `-A`/`-B`/`-C`).
fn parse_match_line(line: &str) -> Option<(String, usize, bool, &str)> {
static MATCH_LINE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^([^\x00]+)\x00(\d+)([:-])(.*)$").unwrap());
MATCH_LINE_RE.captures(line).and_then(|caps| {
let file = caps.get(1)?.as_str().to_string();
let line_num: usize = caps.get(2)?.as_str().parse().ok()?;
let sep = caps.get(3)?.as_str();
let content = caps.get(4)?.as_str();
let is_match = sep == ":";
Some((file, line_num, is_match, content))
})
}
/// Minimal/shape forms the agent already chose (`-c`/`-l`/`--json`/...). `engine`-aware: `-L`
/// is grep's `--files-without-match` but rg's `--follow` (symlinks); `-z` is grep's
/// `--null-data` but rg's `--search-zip` -- neither rg meaning is a shape flag.
fn is_format_flag_token(engine: Engine, kind: TokenKind, text: &str) -> bool {
const LONG: &[&str] = &[
"byte-offset",
"column",
"count",
"count-matches",
"files",
"files-with-matches",
"files-without-match",
"json",
"null",
"null-data",
"only-matching",
"passthru",
"quiet",
"silent",
"vimgrep",
];
match kind {
// grep's `--initial-tab` pads and tabs every match line, so RTK's own `-H --null -n`
// parse reads nothing back and leaked the injected flags into the output. ripgrep has
// no such flag, and its `-T` is `--type-not`, a value-taking flag (see rg_takes_value).
TokenKind::Long => {
LONG.contains(&text) || (engine == Engine::Grep && text == "initial-tab")
}
// -c count, -l/-L lists, -o only-matching, -q quiet, -b byte-offset, -Z NUL are shared;
// -L/-T/-z mean something unrelated to output shape for rg specifically (see above).
TokenKind::Short => match text {
"L" | "T" | "z" => engine == Engine::Grep,
"Z" | "b" | "c" | "l" | "o" | "q" => true,
_ => false,
},
_ => false,
}
}
/// True when the command's only shape flag is a file list -- `-l`/`--files-with-matches`,
/// grep's `-L`/`--files-without-match`, or rg's `--files` -- so every stdout line is one
/// plain path and [`fold_path_prefix`] applies. Any other shape flag changes the line
/// (`-c` appends `:count`, `-Z`/`--null` joins with NUL, `--json` wraps it) or removes it
/// (`-q`), so the list is left verbatim.
pub(crate) fn is_bare_file_list<T: AsRef<str>>(engine: Engine, args: &[T]) -> bool {
let tokens = tokenize_search_args(args, engine);