Repository navigation
Expand file tree
/
Copy pathrunner.rs
More file actions
1750 lines (1604 loc) · 63.3 KB
/
Copy pathrunner.rs
File metadata and controls
1750 lines (1604 loc) · 63.3 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 command execution skeleton for filter modules.
use anyhow::{Context, Result};
use regex::Regex;
use std::borrow::Cow;
use std::process::Command;
use std::sync::LazyLock;
use crate::core::stream::{self, FilterMode, StdinMode, StreamFilter};
use crate::core::tracking;
use crate::core::truncate::{CAP_LIST, CAP_WARNINGS};
/// Compose `filtered` with an optional recovery `hint` and print it, or print `raw`
/// instead when the command's own output is estimated to cost fewer tokens. Both
/// sides are weighed as printed, each under its terminator, and a tie goes to the
/// composed form. Returns what was emitted so the caller tracks exactly that.
pub fn emit_guarded(filtered: &str, hint: Option<&str>, raw: &str) -> String {
emit(filtered, hint, raw, &[])
}
/// [`emit_guarded`], with the guard waived when `raw` is one of `clean_outputs`
/// (see [`guard_stdout`]).
fn emit(filtered: &str, hint: Option<&str>, raw: &str, clean_outputs: &[&str]) -> String {
let shown = guarded_output(filtered, hint, raw, clean_outputs);
print!("{}", shown);
shown
}
/// The exact bytes `emit` writes: the guarded body, terminated.
///
/// Filters disagree on whether their last line already carries its terminator,
/// so it is supplied rather than assumed. Supplying one unconditionally costs a
/// byte the command never emitted whenever the body ends in a newline of its
/// own -- the shape every guard fallback takes, a command's output being
/// newline-terminated in the ordinary case. A command whose own output is
/// unterminated still gets the one newline a printed line needs; that byte is
/// the price of not gluing the next prompt to the output.
///
/// A body that is the empty string prints nothing at all. A filter with nothing
/// to report, like a command with nothing to say, should not cost a blank line.
fn guarded_output(filtered: &str, hint: Option<&str>, raw: &str, clean_outputs: &[&str]) -> String {
let body = with_hint(filtered, hint);
// Both sides weighed as they will be printed. The printer's terminator is paid by
// whichever form wins, so charging it to one side only decides close calls on a
// byte that is not the difference between them.
let body = terminated(&body);
let raw = terminated(raw);
guard_stdout(&raw, &body, clean_outputs).to_string()
}
/// `filtered` followed by the recovery `hint`, as [`emit_guarded`] composes them.
///
/// The hint goes on the line after the filtered text, whose own terminator is
/// reused rather than doubled; with no filtered text, the hint is the whole body.
pub fn with_hint<'a>(filtered: &'a str, hint: Option<&str>) -> Cow<'a, str> {
match hint {
Some(h) => Cow::Owned(format!("{}{}", terminated(filtered), h)),
None => Cow::Borrowed(filtered),
}
}
/// `text` under a trailing newline, and none at all when it is empty.
///
/// Only ever adds the missing one: a text that ends in a blank line keeps it,
/// since the blank line is the command's output and not a stray terminator.
fn terminated(text: &str) -> Cow<'_, str> {
if text.is_empty() || text.ends_with('\n') {
Cow::Borrowed(text)
} else {
Cow::Owned(format!("{}\n", text))
}
}
pub fn print_with_hint(
filtered: &str,
tee_raw: &str,
guard_raw: &str,
tee_label: &str,
exit_code: i32,
) -> String {
let hint = crate::core::tee::tee_and_hint(tee_raw, tee_label, exit_code);
emit_guarded(filtered, hint.as_deref(), guard_raw)
}
#[cfg(test)]
mod guarded_output_tests {
use super::*;
const HINT: &str = "[full output: ~/.local/share/rtk/tee/1_go_test.log]";
/// Long enough that the guard keeps the filtered form, so a test about the
/// terminator is not really a test about the fallback.
fn bulky_raw() -> String {
"go: downloading example.com/module v1.2.3\n".repeat(20)
}
/// The guard hands back the command's own output when the filtered form would cost
/// more, and that output is already newline-terminated: terminating it again is a
/// byte the command never emitted.
#[test]
fn terminated_fallback_costs_exactly_the_command() {
for raw in ["ok\n", "ok ex\n", "PASS\n", "a\nb\n"] {
let out = guarded_output(
"a summary longer than the output it summarises",
None,
raw,
&[],
);
assert_eq!(out, raw, "guard fallback must emit the raw bytes unchanged");
}
}
/// Most filters leave their last line unterminated and count on the printer for it.
#[test]
fn unterminated_body_gains_one_newline() {
assert_eq!(
guarded_output("3 passed", None, &bulky_raw(), &[]),
"3 passed\n"
);
}
#[test]
fn hint_is_terminated_once() {
let out = guarded_output("3 passed", Some(HINT), &bulky_raw(), &[]);
assert_eq!(out, format!("3 passed\n{}\n", HINT));
}
#[test]
fn already_terminated_hint_gains_nothing() {
let out = guarded_output("3 passed", Some(&format!("{}\n", HINT)), &bulky_raw(), &[]);
assert_eq!(out, format!("3 passed\n{}\n", HINT));
}
/// A filtered text that brings its own terminator is not given a blank line
/// before the hint.
#[test]
fn terminated_body_and_hint_gain_no_blank_line() {
let out = guarded_output("3 passed\n", Some(HINT), &bulky_raw(), &[]);
assert_eq!(out, format!("3 passed\n{}\n", HINT));
}
/// The join itself, on every shape a filtered text and a hint come in.
#[test]
fn with_hint_joins_on_the_next_line() {
assert_eq!(
with_hint("3 passed\n", Some(HINT)),
format!("3 passed\n{}", HINT)
);
assert_eq!(
with_hint("3 passed", Some(HINT)),
format!("3 passed\n{}", HINT)
);
assert_eq!(with_hint("", Some(HINT)), HINT);
assert_eq!(with_hint("3 passed", None), "3 passed");
assert_eq!(with_hint("3 passed\n", None), "3 passed\n");
}
/// With nothing filtered to show, the hint alone is printed, without a blank line
/// above it.
#[test]
fn empty_body_with_hint_prints_the_hint_alone() {
let out = guarded_output("", Some(HINT), &bulky_raw(), &[]);
assert_eq!(out, format!("{}\n", HINT));
}
/// A body that ties with the command's output only because its terminator has not
/// been added yet outgrows that output the moment it is printed.
#[test]
fn the_terminator_counts_toward_the_guard() {
assert_eq!(
guarded_output("abcdefgh", None, "abc\ndef\n", &[]),
"abc\ndef\n"
);
}
/// The other side of the same scale: a command that left its own output unterminated
/// owes the printer the same byte, so it must not win a tie the filtered form loses
/// only for having been charged it alone.
#[test]
fn an_unterminated_raw_is_weighed_terminated_too() {
assert_eq!(
guarded_output("abcdefgh", None, "12345678", &[]),
"abcdefgh\n"
);
}
/// The empty form of a format rtk injected, like ruff's `[]`, is not what the user
/// asked for: the summary replaces it, terminated once.
#[test]
fn an_injected_clean_output_shows_the_summary_terminated() {
let summary = "Ruff: No issues found";
assert_eq!(
guarded_output(summary, None, "[]\n", &["[]"]),
format!("{}\n", summary)
);
}
/// A command that printed nothing must not gain a blank line.
#[test]
fn empty_stays_empty() {
assert_eq!(guarded_output("", None, "", &[]), "");
assert_eq!(guarded_output("", None, &bulky_raw(), &[]), "");
}
}
#[derive(Default)]
pub struct RunOptions<'a> {
pub tee_label: Option<&'a str>,
pub filter_stdout_only: bool,
pub skip_filter_on_failure: bool,
pub no_trailing_newline: bool,
/// Forward rtk's own stdin to the child process. Needed for commands that
/// can read from a pipe (e.g. `cat file | rtk wc`); without it the child
/// gets an empty stdin and reports zero.
pub inherit_stdin: bool,
/// What the tool prints on a clean run in the output format rtk injected, e.g. ruff's
/// `[]`. See [`guard_stdout`]. Not consulted when `tee_label` is set.
pub clean_outputs: &'a [&'a str],
}
impl<'a> RunOptions<'a> {
pub fn with_tee(label: &'a str) -> Self {
Self {
tee_label: Some(label),
..Default::default()
}
}
pub fn stdout_only() -> Self {
Self {
filter_stdout_only: true,
..Default::default()
}
}
pub fn tee(mut self, label: &'a str) -> Self {
self.tee_label = Some(label);
self
}
pub fn early_exit_on_failure(mut self) -> Self {
self.skip_filter_on_failure = true;
self
}
pub fn no_trailing_newline(mut self) -> Self {
self.no_trailing_newline = true;
self
}
pub fn inherit_stdin(mut self) -> Self {
self.inherit_stdin = true;
self
}
pub fn clean_outputs(mut self, outputs: &'a [&'a str]) -> Self {
self.clean_outputs = outputs;
self
}
}
/// The stdout to show: `filtered`, unless it costs more tokens than `raw`.
///
/// A `raw` that is exactly one of `clean_outputs` is the empty form of a format rtk injected,
/// not output the user asked for, so the filter's summary is shown even though it is longer.
fn guard_stdout<'a>(raw: &'a str, filtered: &'a str, clean_outputs: &[&str]) -> &'a str {
if clean_outputs.contains(&raw.trim()) {
filtered
} else {
crate::core::guard::never_worse(raw, filtered)
}
}
pub type CaptureFilter<'a> = Box<dyn Fn(&str) -> String + 'a>;
pub type ExitAwareCaptureFilter<'a> = Box<dyn Fn(&str, i32) -> String + 'a>;
pub enum RunMode<'a> {
Filtered(CaptureFilter<'a>),
FilteredWithExit(ExitAwareCaptureFilter<'a>),
Streamed(Box<dyn StreamFilter + 'a>),
Passthrough,
}
fn run_captured_filter<F>(
mut cmd: Command,
tool_name: &str,
cmd_label: &str,
filter_fn: F,
opts: RunOptions<'_>,
timer: tracking::TimedExecution,
) -> Result<i32>
where
F: Fn(&str, i32) -> String,
{
let stdin_mode = if opts.inherit_stdin {
StdinMode::Inherit
} else {
StdinMode::Null
};
let result = stream::run_streaming(&mut cmd, stdin_mode, FilterMode::CaptureOnly)
.with_context(|| format!("Failed to run {}", tool_name))?;
let exit_code = result.exit_code;
let raw = &result.raw;
let raw_stdout = &result.raw_stdout;
if opts.skip_filter_on_failure && exit_code != 0 {
if !result.raw_stdout.trim().is_empty() {
print!("{}", result.raw_stdout);
}
if !result.raw_stderr.trim().is_empty() {
eprint!("{}", result.raw_stderr);
}
timer.track(cmd_label, &format!("rtk {}", cmd_label), raw, raw);
return Ok(exit_code);
}
let text_to_filter = if opts.filter_stdout_only {
raw_stdout
} else {
raw
};
let filtered = filter_fn(text_to_filter, exit_code);
let raw_for_tracking = if opts.filter_stdout_only {
raw_stdout
} else {
raw
};
// The guard governs the stdout rtk replaces. stderr is forwarded separately below, and
// only ever shrinks there, so it cannot push the total past what the command emitted.
let shown = if let Some(label) = opts.tee_label {
print_with_hint(&filtered, raw, raw_for_tracking, label, exit_code)
} else if opts.no_trailing_newline {
// The filters that opt out own their line endings: what they return is already
// exactly what the command would have printed, terminator included.
let guarded = guard_stdout(raw_for_tracking, &filtered, opts.clean_outputs).to_string();
print!("{}", guarded);
guarded
} else {
emit(&filtered, None, raw_for_tracking, opts.clean_outputs)
};
// Stdout-only filters parse structured stdout; stderr still carries diagnostics
// (config errors, missing linters) that the user needs.
let forwarded = (opts.filter_stdout_only && !result.raw_stderr.trim().is_empty()).then(|| {
forwarded_stderr(&result.raw_stderr, exit_code, &shown, |stderr| {
crate::core::tee::force_tee_hint(
stderr,
&format!("{}-stderr", opts.tee_label.unwrap_or(tool_name)),
)
})
});
if let Some(text) = &forwarded {
eprint!("{}", text);
}
// Forwarded stderr reaches the user just as much as stdout does, so counting only
// stdout would book a passed-through stream as if the filter had removed it.
let emitted = match &forwarded {
Some(text) => Cow::Owned(format!("{}{}", shown, text)),
None => Cow::Borrowed(shown.as_str()),
};
timer.track(cmd_label, &format!("rtk {}", cmd_label), raw, &emitted);
Ok(exit_code)
}
/// How many stderr lines survive the cap. Warning-shaped data, so the warnings cap.
const MAX_FORWARDED_STDERR_LINES: usize = CAP_WARNINGS;
/// The stderr a stdout-only filter forwards.
///
/// Whole, whenever stderr is the report: the command failed, or the filter had nothing to show
/// for stdout. Those are the cases stderr forwarding exists for -- a golangci-lint config
/// error leaves stdout empty, and dropping its stderr left the user with no output at all.
///
/// Capped otherwise, because on a run that succeeded and reported on stdout, stderr is as
/// often progress chatter -- `go: downloading …` once per module on a cold cache -- and
/// forwarding all of it verbatim leaves rtk emitting as much as the command it stands in
/// front of.
///
/// The cap keeps the END. A tool resolves and downloads before it builds, so its chatter comes
/// first and anything it has to say -- a deprecation warning, "matched no packages" -- comes
/// after: a cap on the head keeps the noise and drops exactly the lines worth forwarding.
///
/// Three things make it give up and forward the lot. A stderr below the recovery store's own
/// floor, which is not worth a stored file and the eviction that comes with it. `recovery_hint`
/// returning `None`, meaning there is no store to point at, and a count of lines nobody can
/// read is worse than the lines (`curl_cmd` declines the same way). And a result that is not
/// actually smaller, since the note and the hint cost bytes of their own -- rtk emits no more
/// than the command it stands in front of, on either stream.
fn forwarded_stderr<'a>(
stderr: &'a str,
exit_code: i32,
shown_stdout: &str,
recovery_hint: impl FnOnce(&str) -> Option<String>,
) -> Cow<'a, str> {
if exit_code != 0 || shown_stdout.trim().is_empty() {
return Cow::Borrowed(stderr);
}
// Below the recovery store's own floor there is nothing to gain and a file to write for
// it: the store would hold a stderr smaller than the note and hint that point at it, and
// every write evicts an older entry. `tsc_cmd` declines on the same threshold.
if stderr.len() < crate::core::tee::MIN_TEE_SIZE {
return Cow::Borrowed(stderr);
}
let Some((offset, held_back)) = last_lines_offset(stderr, MAX_FORWARDED_STDERR_LINES) else {
return Cow::Borrowed(stderr);
};
let Some(hint) = recovery_hint(stderr) else {
return Cow::Borrowed(stderr);
};
let capped = format!(
"... (+{} earlier stderr {} not shown)\n{}{}\n",
held_back,
if held_back == 1 { "line" } else { "lines" },
&stderr[offset..],
hint
);
if capped.len() >= stderr.len() {
return Cow::Borrowed(stderr);
}
Cow::Owned(capped)
}
/// Where `text`'s last `n` lines begin, as a byte offset, and how many lines that skips.
/// `None` when it has no more than `n`.
///
/// A byte offset rather than `lines().collect()` and a re-join: `str::lines` drops the `\r` of
/// a CRLF ending and nothing puts it back, so re-joining would rewrite the line endings of a
/// stderr that happened to be long enough to cap. It also reads none of the lines it skips.
/// `\n` is ASCII, so the offset is always a char boundary.
fn last_lines_offset(text: &str, n: usize) -> Option<(usize, usize)> {
let skipped = text.lines().count().checked_sub(n).filter(|&s| s > 0)?;
text.match_indices('\n')
.nth(skipped - 1)
.map(|(index, _)| (index + 1, skipped))
}
pub fn run(
cmd: Command,
tool_name: &str,
args_display: &str,
mode: RunMode<'_>,
opts: RunOptions<'_>,
) -> Result<i32> {
let result = run_inner(cmd, tool_name, args_display, mode, opts);
// #2375
stream::die_by_relayed_signal();
result
}
fn run_inner(
mut cmd: Command,
tool_name: &str,
args_display: &str,
mode: RunMode<'_>,
opts: RunOptions<'_>,
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let cmd_label = crate::core::shell::with_args(tool_name, args_display);
match mode {
RunMode::Filtered(filter_fn) => run_captured_filter(
cmd,
tool_name,
&cmd_label,
move |text, _| filter_fn(text),
opts,
timer,
),
RunMode::FilteredWithExit(filter_fn) => run_captured_filter(
cmd,
tool_name,
&cmd_label,
move |text, exit_code| filter_fn(text, exit_code),
opts,
timer,
),
RunMode::Streamed(filter) => {
let result =
stream::run_streaming(&mut cmd, StdinMode::Null, FilterMode::Streaming(filter))
.with_context(|| format!("Failed to run {}", tool_name))?;
if let Some(label) = opts.tee_label
&& let Some(hint) =
crate::core::tee::tee_and_hint(&result.raw, label, result.exit_code)
{
println!("{}", hint);
}
timer.track(
&cmd_label,
&format!("rtk {}", cmd_label),
&result.raw,
&result.filtered,
);
Ok(result.exit_code)
}
RunMode::Passthrough => {
let result =
stream::run_streaming(&mut cmd, StdinMode::Inherit, FilterMode::Passthrough)
.with_context(|| format!("Failed to run {}", tool_name))?;
timer.track_passthrough(&cmd_label, &tracking::passthrough_label(&cmd_label));
Ok(result.exit_code)
}
}
}
pub fn run_filtered<F>(
cmd: Command,
tool_name: &str,
args_display: &str,
filter_fn: F,
opts: RunOptions<'_>,
) -> Result<i32>
where
F: Fn(&str) -> String,
{
run(
cmd,
tool_name,
args_display,
RunMode::Filtered(Box::new(filter_fn)),
opts,
)
}
pub fn run_filtered_with_exit<F>(
cmd: Command,
tool_name: &str,
args_display: &str,
filter_fn: F,
opts: RunOptions<'_>,
) -> Result<i32>
where
F: Fn(&str, i32) -> String,
{
run(
cmd,
tool_name,
args_display,
RunMode::FilteredWithExit(Box::new(filter_fn)),
opts,
)
}
pub fn run_passthrough(tool: &str, args: &[std::ffi::OsString], verbose: u8) -> Result<i32> {
if verbose > 0 {
eprintln!("{} passthrough: {:?}", tool, args);
}
let mut cmd = crate::core::utils::resolved_command(tool);
crate::core::utils::ChildArgExt::child_args(&mut cmd, args);
let args_str = tracking::args_display(args);
run(
cmd,
tool,
&args_str,
RunMode::Passthrough,
RunOptions::default(),
)
}
pub fn run_streamed(
cmd: Command,
tool_name: &str,
args_display: &str,
filter: Box<dyn StreamFilter + '_>,
opts: RunOptions<'_>,
) -> Result<i32> {
run(
cmd,
tool_name,
args_display,
RunMode::Streamed(filter),
opts,
)
}
// Ecosystem-agnostic err/test command runners. Used by cargo, bun, deno, and the
// shell-string wrappers in cmds::rust::runner.
const MAX_RUNNER_FAILURES: usize = CAP_WARNINGS;
const MAX_RUNNER_LINES: usize = CAP_LIST;
static ERROR_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
vec![
// Generic errors
Regex::new(r"(?i)^.*error[\s:\[].*$").unwrap(),
Regex::new(r"(?i)^.*\berr\b.*$").unwrap(),
Regex::new(r"(?i)^.*warning[\s:\[].*$").unwrap(),
Regex::new(r"(?i)^.*\bwarn\b.*$").unwrap(),
Regex::new(r"(?i)^.*failed.*$").unwrap(),
Regex::new(r"(?i)^.*failure.*$").unwrap(),
Regex::new(r"(?i)^.*exception.*$").unwrap(),
Regex::new(r"(?i)^.*panic.*$").unwrap(),
// Rust specific
Regex::new(r"^error\[E\d+\]:.*$").unwrap(),
Regex::new(r"^\s*--> .*:\d+:\d+$").unwrap(),
// Python
Regex::new(r"^Traceback.*$").unwrap(),
Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap(),
// JavaScript/TypeScript
Regex::new(r"^\s*at .*:\d+:\d+.*$").unwrap(),
// Go
Regex::new(r"^.*\.go:\d+:.*$").unwrap(),
]
});
struct ErrorStreamFilter {
in_error_block: bool,
blank_count: usize,
emitted_any: bool,
}
impl ErrorStreamFilter {
fn new() -> Self {
Self {
in_error_block: false,
blank_count: 0,
emitted_any: false,
}
}
}
impl StreamFilter for ErrorStreamFilter {
fn feed_line(&mut self, line: &str) -> Option<String> {
let is_error = ERROR_PATTERNS.iter().any(|p| p.is_match(line));
if is_error {
self.in_error_block = true;
self.blank_count = 0;
self.emitted_any = true;
Some(format!("{}\n", line))
} else if self.in_error_block {
if line.trim().is_empty() {
self.blank_count += 1;
if self.blank_count >= 2 {
self.in_error_block = false;
None
} else {
self.emitted_any = true;
Some(format!("{}\n", line))
}
} else if line.starts_with(' ') || line.starts_with('\t') {
self.blank_count = 0;
self.emitted_any = true;
Some(format!("{}\n", line))
} else {
self.in_error_block = false;
None
}
} else {
None
}
}
fn flush(&mut self) -> String {
String::new()
}
fn on_exit(&mut self, exit_code: i32, raw: &str) -> Option<String> {
if self.emitted_any {
return None;
}
if exit_code == 0 {
Some("[ok] Command completed successfully (no errors)".to_string())
} else {
let mut msg = format!("[FAIL] Command failed (exit code: {})\n", exit_code);
let lines: Vec<&str> = raw.lines().collect();
for line in lines.iter().rev().take(10).rev() {
msg.push_str(&format!(" {}\n", line));
}
Some(msg)
}
}
}
/// Run a prebuilt command (no shell) and filter output to show only errors/warnings.
/// `display` is used only for logging, tee keys, and tracking, never executed.
///
/// `tool` is the command the user actually ran. It keys tracking and the tee
/// slug, so passing a real name keeps `rtk gain --history` showing invocations
/// that exist and stops recovery files colliding across ecosystems.
pub fn run_err_cmd(
cmd: Command,
tool: &str,
display: &str,
tee_label: &str,
verbose: u8,
) -> Result<i32> {
if verbose > 0 {
eprintln!("Running: {}", display);
}
run_streamed(
cmd,
tool,
display,
Box::new(ErrorStreamFilter::new()),
RunOptions::with_tee(tee_label),
)
}
/// Render a program that could not be run through the err filter's own failure
/// path.
///
/// The interposed shell used to produce this: `[FAIL] Command failed (exit
/// code: 127)` over its `command not found` line, or 126 over `Permission
/// denied`. Direct execution answers for the program itself, so RTK renders it
/// instead of bailing out with an `anyhow` chain on stderr.
pub fn run_err_unrunnable(
tool: &str,
display: &str,
outcome: &crate::core::shell::Unrunnable,
verbose: u8,
) -> i32 {
report_unrunnable(tool, display, outcome, verbose, |raw, code| {
ErrorStreamFilter::new()
.on_exit(code, raw)
.unwrap_or_default()
})
}
/// [`run_err_unrunnable`] for the test runner, rendered by the test summarizer.
pub fn run_test_unrunnable(
tool: &str,
display: &str,
outcome: &crate::core::shell::Unrunnable,
eco: TestEcosystem,
verbose: u8,
) -> i32 {
report_unrunnable(tool, display, outcome, verbose, |raw, _| {
extract_test_summary(raw, eco)
})
}
fn report_unrunnable(
tool: &str,
display: &str,
outcome: &crate::core::shell::Unrunnable,
verbose: u8,
render: impl FnOnce(&str, i32) -> String,
) -> i32 {
if verbose > 0 {
eprintln!("Running: {}", display);
}
let timer = tracking::TimedExecution::start();
let rendered = render(&outcome.message, outcome.code);
println!("{}", rendered.trim_end());
let label = format!("{} {}", tool, display);
timer.track(
&label,
&format!("rtk {}", label),
&outcome.message,
&rendered,
);
outcome.code
}
/// Test-output ecosystem, chosen once at the boundary. Modules that know
/// their runner statically pass the variant directly; shell-string entry
/// points convert once via `detect`. Matching on the enum makes substring
/// co-firing ("cargo test" contains "go test") unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TestEcosystem {
Cargo,
Pytest,
Jest,
Go,
Bun,
Deno,
Unknown,
}
impl TestEcosystem {
/// Detect from a display or shell string. First match wins; Cargo is
/// checked before Go because "cargo test" contains "go test".
pub fn detect(command: &str) -> Self {
if command.contains("cargo test") {
Self::Cargo
} else if command.contains("pytest") {
Self::Pytest
} else if command.contains("jest")
|| command.contains("npm test")
|| command.contains("yarn test")
{
Self::Jest
} else if command.contains("bun test") {
Self::Bun
} else if command.contains("deno test") {
Self::Deno
} else if command.contains("go test") {
Self::Go
} else {
Self::Unknown
}
}
}
/// Watch mode never exits, and the filtered runners buffer the whole stream
/// until the child does, so a watched run prints nothing at all and loses the
/// buffer on Ctrl-C. Callers send these through unfiltered instead.
pub fn is_watch_mode(args: &[String]) -> bool {
args.iter()
.any(|a| a == "--watch" || a.starts_with("--watch="))
}
/// Run a prebuilt test command (no shell), showing only failures.
/// `display` is used only for logging and tracking, never executed.
pub fn run_test_cmd(
cmd: Command,
tool: &str,
display: &str,
tee_label: &str,
eco: TestEcosystem,
verbose: u8,
) -> Result<i32> {
if verbose > 0 {
eprintln!("Running tests: {}", display);
}
run_filtered(
cmd,
tool,
display,
move |raw| extract_test_summary(raw, eco),
RunOptions::with_tee(tee_label),
)
}
#[cfg(test)]
fn filter_errors(output: &str) -> String {
let mut result = Vec::new();
let mut in_error_block = false;
let mut blank_count = 0;
for line in output.lines() {
let is_error_line = ERROR_PATTERNS.iter().any(|p| p.is_match(line));
if is_error_line {
in_error_block = true;
blank_count = 0;
result.push(line.to_string());
} else if in_error_block {
if line.trim().is_empty() {
blank_count += 1;
if blank_count >= 2 {
in_error_block = false;
} else {
result.push(line.to_string());
}
} else if line.starts_with(' ') || line.starts_with('\t') {
result.push(line.to_string());
blank_count = 0;
} else {
in_error_block = false;
}
}
}
result.join("\n")
}
/// Whether a block's ending vouches for it. `Vouched` means the ending itself
/// attributes the block to a real failure (bun's `(fail)` marker).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Close {
Vouched,
Plain,
}
/// Whether the runner is currently printing its own diagnostics or relaying the
/// test's stdout.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Section {
Trusted,
Untrusted,
}
/// Which lines belong to a real failure rather than to the test's own stdout.
///
/// Bun and deno answer the same questions (what opens a diagnostic block, what
/// closes it and whether that ending vouches for it, and where the runner's own
/// output begins and ends), so they share one engine
/// and differ only in this table. As two separate state machines they drifted:
/// a guard added on one side had to be rediscovered on the other, and deno had
/// no proof rule at all, reporting passing suites as failed.
struct BlockPolicy {
/// Opens a diagnostic block. Opening also closes any block already open.
opens: fn(&str) -> bool,
/// Ends the current block. A vouched close is the runner's own marker
/// claiming what came before it.
closes: fn(&str) -> Option<Close>,
/// Keeps a line inside the block. Separator rules are noise.
keeps: fn(&str) -> bool,
/// Moves in and out of the region where the runner prints its own
/// diagnostics. A block opened outside it needs a vouched close to count.
section: fn(&str) -> Option<Section>,
}
/// Buffers a diagnostic block until something decides whether the runner wrote
/// it. Kept when it opened inside a trusted section, or when the runner's own
/// marker vouches for it. Anything else is the test's own stdout and is dropped.
#[derive(Default)]
struct FailureBlocks {
pending: Vec<String>,
open: bool,
opened_trusted: bool,
trusted: bool,
kept: Vec<String>,
}
impl FailureBlocks {
fn feed(&mut self, line: &str, trimmed: &str, policy: &BlockPolicy) {
if let Some(section) = (policy.section)(trimmed) {
self.close(None);
self.trusted = section == Section::Trusted;
}
if let Some(close) = (policy.closes)(trimmed) {
self.close(Some(close));
return;
}
if (policy.opens)(trimmed) {
self.close(None);
self.open = true;
self.opened_trusted = self.trusted;
self.pending.push(line.to_string());
return;
}
if self.open && (policy.keeps)(trimmed) {
self.pending.push(line.to_string());
}
}
fn close(&mut self, close: Option<Close>) {
if !self.open {
self.pending.clear();
return;
}
if self.opened_trusted || close == Some(Close::Vouched) {
self.kept.append(&mut self.pending);
} else {
self.pending.clear();
}
self.open = false;
}
}
/// Bun writes a diagnostic before the marker it belongs to, so a block only
/// counts once a `(fail)` marker claims it. A test logging its own `error:`,
/// even with a stack, gets claimed by `(pass)` or by the counts instead.
/// Module-level failures carry no marker at all, which is what the
/// unhandled-error banner is for.
const BUN_POLICY: BlockPolicy = BlockPolicy {
opens: |t| t.starts_with("error:"),
closes: |t| {
if BUN_FAILURE_MARKER.is_match(t) {
Some(Close::Vouched)
} else if t.starts_with("(pass)") || is_bun_count_line(t) || BUN_RAN_FOOTER.is_match(t) {
Some(Close::Plain)
} else {
None
}
},
// The frame carries the file and line. Without it two failing tests that
// share a name, or a module error that has no marker at all, cannot be
// located. Bun prints one frame per failure, so this costs a line each.
keeps: |t| !t.is_empty() && !t.chars().all(|c| c == '-'),
section: |t| {
if t == "# Unhandled error between tests" {
Some(Section::Trusted)
} else if is_bun_count_line(t) || BUN_RAN_FOOTER.is_match(t) {
Some(Section::Untrusted)
} else {
None
}
},
};
/// Deno's type-check diagnostics, "TS2322 `[ERROR]`: Type 'string' is not
/// assignable to type 'number'." They are not introduced by an `error:` line and
/// carry no ERRORS section, so nothing else in the deno policy would keep them.
static DENO_TS_ERROR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^TS\d+ \[ERROR\]:").unwrap());
/// Deno fences output it did not write between rules: "------- output -------"
/// around a test's own stdout, "------- pre-test output -------" around what a
/// module printed while loading. Returns whether the rule opens a fence.
fn deno_output_fence(trimmed: &str) -> Option<bool> {
if !trimmed.starts_with("-----") || !trimmed.contains("output") {
return None;
}
Some(!trimmed.contains("output end"))
}
/// Bun's run footer, "Ran 4 tests across 1 file. [12.00ms]". Unanchored, the
/// prefix also matches anything a test logs starting with those characters.
static BUN_RAN_FOOTER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Ran \d+ test").unwrap());
/// Bun's failure markers carry the test's duration: "(fail) name [1.86ms]",