forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcargo_cmd.rs
More file actions
1764 lines (1547 loc) · 57.4 KB
/
Copy pathcargo_cmd.rs
File metadata and controls
1764 lines (1547 loc) · 57.4 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
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::OnceLock;
#[derive(Debug, Clone)]
pub enum CargoCommand {
Build,
Test,
Clippy,
Check,
Install,
Nextest,
}
pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<()> {
match cmd {
CargoCommand::Build => run_build(args, verbose),
CargoCommand::Test => run_test(args, verbose),
CargoCommand::Clippy => run_clippy(args, verbose),
CargoCommand::Check => run_check(args, verbose),
CargoCommand::Install => run_install(args, verbose),
CargoCommand::Nextest => run_nextest(args, verbose),
}
}
/// Reconstruct args with `--` separator preserved from the original command line.
/// Clap strips `--` from parsed args, but cargo subcommands need it to separate
/// their own flags from test runner flags (e.g. `cargo test -- --nocapture`).
fn restore_double_dash(args: &[String]) -> Vec<String> {
let raw_args: Vec<String> = std::env::args().collect();
restore_double_dash_with_raw(args, &raw_args)
}
/// Testable version that takes raw_args explicitly.
fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<String> {
if args.is_empty() {
return args.to_vec();
}
// If args already contain `--` (Clap preserved it), no restoration needed
if args.iter().any(|a| a == "--") {
return args.to_vec();
}
// Find `--` in the original command line
let sep_pos = match raw_args.iter().position(|a| a == "--") {
Some(pos) => pos,
None => return args.to_vec(),
};
// Count how many of our parsed args appeared before `--` in the original.
// Args before `--` are positional (e.g. test name), args after are flags.
let args_before_sep = raw_args[..sep_pos]
.iter()
.filter(|a| args.contains(a))
.count();
let mut result = Vec::with_capacity(args.len() + 1);
result.extend_from_slice(&args[..args_before_sep]);
result.push("--".to_string());
result.extend_from_slice(&args[args_before_sep..]);
result
}
/// Generic cargo command runner with filtering
fn run_cargo_filtered<F>(subcommand: &str, args: &[String], verbose: u8, filter_fn: F) -> Result<()>
where
F: Fn(&str) -> String,
{
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("cargo");
cmd.arg(subcommand);
let restored_args = restore_double_dash(args);
for arg in &restored_args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: cargo {} {}", subcommand, restored_args.join(" "));
}
let output = cmd
.output()
.with_context(|| format!("Failed to run cargo {}", subcommand))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = output
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
let filtered = filter_fn(&raw);
if let Some(hint) = crate::tee::tee_and_hint(&raw, &format!("cargo_{}", subcommand), exit_code)
{
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
}
timer.track(
&format!("cargo {} {}", subcommand, restored_args.join(" ")),
&format!("rtk cargo {} {}", subcommand, restored_args.join(" ")),
&raw,
&filtered,
);
if !output.status.success() {
std::process::exit(exit_code);
}
Ok(())
}
fn run_build(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("build", args, verbose, filter_cargo_build)
}
fn run_test(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("test", args, verbose, filter_cargo_test)
}
fn run_clippy(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("clippy", args, verbose, filter_cargo_clippy)
}
fn run_check(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("check", args, verbose, filter_cargo_build)
}
fn run_install(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("install", args, verbose, filter_cargo_install)
}
fn run_nextest(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("nextest", args, verbose, filter_cargo_nextest)
}
/// Format crate name + version into a display string
fn format_crate_info(name: &str, version: &str, fallback: &str) -> String {
if name.is_empty() {
fallback.to_string()
} else if version.is_empty() {
name.to_string()
} else {
format!("{} {}", name, version)
}
}
/// Filter cargo install output - strip dep compilation, keep installed/replaced/errors
fn filter_cargo_install(output: &str) -> String {
let mut errors: Vec<String> = Vec::new();
let mut error_count = 0;
let mut compiled = 0;
let mut in_error = false;
let mut current_error = Vec::new();
let mut installed_crate = String::new();
let mut installed_version = String::new();
let mut replaced_lines: Vec<String> = Vec::new();
let mut already_installed = false;
let mut ignored_line = String::new();
for line in output.lines() {
let trimmed = line.trim_start();
// Strip noise: dep compilation, downloading, locking, etc.
if trimmed.starts_with("Compiling") {
compiled += 1;
continue;
}
if trimmed.starts_with("Downloading")
|| trimmed.starts_with("Downloaded")
|| trimmed.starts_with("Locking")
|| trimmed.starts_with("Updating")
|| trimmed.starts_with("Adding")
|| trimmed.starts_with("Finished")
|| trimmed.starts_with("Blocking waiting for file lock")
{
continue;
}
// Keep: Installing line (extract crate name + version)
if trimmed.starts_with("Installing") {
let rest = trimmed.strip_prefix("Installing").unwrap_or("").trim();
if !rest.is_empty() && !rest.starts_with('/') {
if let Some((name, version)) = rest.split_once(' ') {
installed_crate = name.to_string();
installed_version = version.to_string();
} else {
installed_crate = rest.to_string();
}
}
continue;
}
// Keep: Installed line (extract crate + version if not already set)
if trimmed.starts_with("Installed") {
let rest = trimmed.strip_prefix("Installed").unwrap_or("").trim();
if !rest.is_empty() && installed_crate.is_empty() {
let mut parts = rest.split_whitespace();
if let (Some(name), Some(version)) = (parts.next(), parts.next()) {
installed_crate = name.to_string();
installed_version = version.to_string();
}
}
continue;
}
// Keep: Replacing/Replaced lines
if trimmed.starts_with("Replacing") || trimmed.starts_with("Replaced") {
replaced_lines.push(trimmed.to_string());
continue;
}
// Keep: "Ignored package" (already up to date)
if trimmed.starts_with("Ignored package") {
already_installed = true;
ignored_line = trimmed.to_string();
continue;
}
// Keep: actionable warnings (e.g., "be sure to add `/path` to your PATH")
// Skip summary lines like "warning: `crate` generated N warnings"
if line.starts_with("warning:") {
if !(line.contains("generated") && line.contains("warning")) {
replaced_lines.push(line.to_string());
}
continue;
}
// Detect error blocks
if line.starts_with("error[") || line.starts_with("error:") {
if line.contains("aborting due to") || line.contains("could not compile") {
continue;
}
if in_error && !current_error.is_empty() {
errors.push(current_error.join("\n"));
current_error.clear();
}
error_count += 1;
in_error = true;
current_error.push(line.to_string());
} else if in_error {
if line.trim().is_empty() && current_error.len() > 3 {
errors.push(current_error.join("\n"));
current_error.clear();
in_error = false;
} else {
current_error.push(line.to_string());
}
}
}
if !current_error.is_empty() {
errors.push(current_error.join("\n"));
}
// Already installed / up to date
if already_installed {
let info = ignored_line.split('`').nth(1).unwrap_or(&ignored_line);
return format!("cargo install: {} already installed", info);
}
// Errors
if error_count > 0 {
let crate_info = format_crate_info(&installed_crate, &installed_version, "");
let deps_info = if compiled > 0 {
format!(", {} deps compiled", compiled)
} else {
String::new()
};
let mut result = String::new();
if crate_info.is_empty() {
result.push_str(&format!(
"cargo install: {} error{}{}\n",
error_count,
if error_count > 1 { "s" } else { "" },
deps_info
));
} else {
result.push_str(&format!(
"cargo install: {} error{} ({}{})\n",
error_count,
if error_count > 1 { "s" } else { "" },
crate_info,
deps_info
));
}
result.push_str("═══════════════════════════════════════\n");
for (i, err) in errors.iter().enumerate().take(15) {
result.push_str(err);
result.push('\n');
if i < errors.len() - 1 {
result.push('\n');
}
}
if errors.len() > 15 {
result.push_str(&format!("\n... +{} more issues\n", errors.len() - 15));
}
return result.trim().to_string();
}
// Success
let crate_info = format_crate_info(&installed_crate, &installed_version, "package");
let mut result = format!("cargo install ({}, {} deps compiled)", crate_info, compiled);
for line in &replaced_lines {
result.push_str(&format!("\n {}", line));
}
result
}
/// Push a completed failure block (header + body) into the failures list, then clear the buffers.
fn flush_failure_block(header: &mut String, body: &mut Vec<String>, failures: &mut Vec<String>) {
if header.is_empty() {
return;
}
let mut block = header.clone();
if !body.is_empty() {
block.push('\n');
block.push_str(&body.join("\n"));
}
failures.push(block);
header.clear();
body.clear();
}
/// Filter cargo nextest output - show failures + compact summary
fn filter_cargo_nextest(output: &str) -> String {
static SUMMARY_RE: OnceLock<regex::Regex> = OnceLock::new();
let summary_re = SUMMARY_RE.get_or_init(|| {
regex::Regex::new(
r"Summary \[\s*([\d.]+)s\]\s+(\d+) tests? run:\s+(\d+) passed(?:,\s+(\d+) failed)?(?:,\s+(\d+) skipped)?"
).expect("invalid nextest summary regex")
});
static STARTING_RE: OnceLock<regex::Regex> = OnceLock::new();
let starting_re = STARTING_RE.get_or_init(|| {
regex::Regex::new(r"Starting \d+ tests? across (\d+) binar(?:y|ies)")
.expect("invalid nextest starting regex")
});
let mut failures: Vec<String> = Vec::new();
let mut in_failure_block = false;
let mut past_summary = false;
let mut current_failure_header = String::new();
let mut current_failure_body = Vec::new();
let mut summary_line = String::new();
let mut binaries: u32 = 0;
let mut has_cancel_line = false;
for line in output.lines() {
let trimmed = line.trim();
// Strip compilation noise
if trimmed.starts_with("Compiling")
|| trimmed.starts_with("Downloading")
|| trimmed.starts_with("Downloaded")
|| trimmed.starts_with("Finished")
|| trimmed.starts_with("Locking")
|| trimmed.starts_with("Updating")
{
continue;
}
// Strip separator lines (────)
if trimmed.starts_with("────") {
continue;
}
// Skip post-summary recap lines (FAIL duplicates + "error: test run failed")
if past_summary {
continue;
}
// Parse binary count from Starting line
if trimmed.starts_with("Starting") {
if let Some(caps) = starting_re.captures(trimmed) {
if let Some(m) = caps.get(1) {
binaries = m.as_str().parse().unwrap_or(0);
}
}
continue;
}
// Strip PASS lines
if trimmed.starts_with("PASS") {
if in_failure_block {
flush_failure_block(
&mut current_failure_header,
&mut current_failure_body,
&mut failures,
);
in_failure_block = false;
}
continue;
}
// Detect FAIL lines
if trimmed.starts_with("FAIL") {
// Close previous failure block if any
if in_failure_block {
flush_failure_block(
&mut current_failure_header,
&mut current_failure_body,
&mut failures,
);
}
current_failure_header = trimmed.to_string();
in_failure_block = true;
continue;
}
// Cancellation notice
if trimmed.starts_with("Cancelling") || trimmed.starts_with("Canceling") {
has_cancel_line = true;
continue;
}
// Nextest run ID line
if trimmed.starts_with("Nextest run ID") {
continue;
}
// Parse summary
if trimmed.starts_with("Summary") {
summary_line = trimmed.to_string();
if in_failure_block {
flush_failure_block(
&mut current_failure_header,
&mut current_failure_body,
&mut failures,
);
in_failure_block = false;
}
past_summary = true;
continue;
}
// Collect failure body lines (stdout/stderr sections)
if in_failure_block {
current_failure_body.push(line.to_string());
}
}
// Close last failure block
if in_failure_block {
flush_failure_block(
&mut current_failure_header,
&mut current_failure_body,
&mut failures,
);
}
// Parse summary with regex
if let Some(caps) = summary_re.captures(&summary_line) {
let duration = caps.get(1).map_or("?", |m| m.as_str());
let passed: u32 = caps
.get(3)
.and_then(|m| m.as_str().parse().ok())
.unwrap_or(0);
let failed: u32 = caps
.get(4)
.and_then(|m| m.as_str().parse().ok())
.unwrap_or(0);
let skipped: u32 = caps
.get(5)
.and_then(|m| m.as_str().parse().ok())
.unwrap_or(0);
let binary_text = if binaries == 1 {
"1 binary".to_string()
} else if binaries > 1 {
format!("{} binaries", binaries)
} else {
String::new()
};
if failed == 0 {
// All pass - compact single line
let mut parts = vec![format!("{} passed", passed)];
if skipped > 0 {
parts.push(format!("{} skipped", skipped));
}
let meta = if binary_text.is_empty() {
format!("{}s", duration)
} else {
format!("{}, {}s", binary_text, duration)
};
return format!("cargo nextest: {} ({})", parts.join(", "), meta);
}
// With failures - show failure details then summary
let mut result = String::new();
for failure in &failures {
result.push_str(failure);
result.push('\n');
}
if has_cancel_line {
result.push_str("Cancelling due to test failure\n");
}
let mut summary_parts = vec![format!("{} passed", passed)];
if failed > 0 {
summary_parts.push(format!("{} failed", failed));
}
if skipped > 0 {
summary_parts.push(format!("{} skipped", skipped));
}
let meta = if binary_text.is_empty() {
format!("{}s", duration)
} else {
format!("{}, {}s", binary_text, duration)
};
result.push_str(&format!(
"cargo nextest: {} ({})",
summary_parts.join(", "),
meta
));
return result.trim().to_string();
}
// Fallback: if summary regex didn't match, show what we have
if !failures.is_empty() {
let mut result = String::new();
for failure in &failures {
result.push_str(failure);
result.push('\n');
}
if !summary_line.is_empty() {
result.push_str(&summary_line);
}
return result.trim().to_string();
}
if !summary_line.is_empty() {
return summary_line;
}
// Empty or unrecognized
String::new()
}
/// Filter cargo build/check output - strip "Compiling"/"Checking" lines, keep errors + summary
fn filter_cargo_build(output: &str) -> String {
let mut errors: Vec<String> = Vec::new();
let mut warnings = 0;
let mut error_count = 0;
let mut compiled = 0;
let mut in_error = false;
let mut current_error = Vec::new();
for line in output.lines() {
if line.trim_start().starts_with("Compiling") || line.trim_start().starts_with("Checking") {
compiled += 1;
continue;
}
if line.trim_start().starts_with("Downloading")
|| line.trim_start().starts_with("Downloaded")
{
continue;
}
if line.trim_start().starts_with("Finished") {
continue;
}
// Detect error/warning blocks
if line.starts_with("error[") || line.starts_with("error:") {
// Skip "error: aborting due to" summary lines
if line.contains("aborting due to") || line.contains("could not compile") {
continue;
}
if in_error && !current_error.is_empty() {
errors.push(current_error.join("\n"));
current_error.clear();
}
error_count += 1;
in_error = true;
current_error.push(line.to_string());
} else if line.starts_with("warning:")
&& line.contains("generated")
&& line.contains("warning")
{
// "warning: `crate` generated N warnings" summary line
continue;
} else if line.starts_with("warning:") || line.starts_with("warning[") {
if in_error && !current_error.is_empty() {
errors.push(current_error.join("\n"));
current_error.clear();
}
warnings += 1;
in_error = true;
current_error.push(line.to_string());
} else if in_error {
if line.trim().is_empty() && current_error.len() > 3 {
errors.push(current_error.join("\n"));
current_error.clear();
in_error = false;
} else {
current_error.push(line.to_string());
}
}
}
if !current_error.is_empty() {
errors.push(current_error.join("\n"));
}
if error_count == 0 && warnings == 0 {
return format!("cargo build ({} crates compiled)", compiled);
}
let mut result = String::new();
result.push_str(&format!(
"cargo build: {} errors, {} warnings ({} crates)\n",
error_count, warnings, compiled
));
result.push_str("═══════════════════════════════════════\n");
for (i, err) in errors.iter().enumerate().take(15) {
result.push_str(err);
result.push('\n');
if i < errors.len() - 1 {
result.push('\n');
}
}
if errors.len() > 15 {
result.push_str(&format!("\n... +{} more issues\n", errors.len() - 15));
}
result.trim().to_string()
}
/// Aggregated test results for compact display
#[derive(Debug, Default, Clone)]
struct AggregatedTestResult {
passed: usize,
failed: usize,
ignored: usize,
measured: usize,
filtered_out: usize,
suites: usize,
duration_secs: f64,
has_duration: bool,
}
impl AggregatedTestResult {
/// Parse a test result summary line
/// Format: "test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s"
fn parse_line(line: &str) -> Option<Self> {
static RE: OnceLock<regex::Regex> = OnceLock::new();
let re = RE.get_or_init(|| {
regex::Regex::new(
r"test result: (\w+)\.\s+(\d+) passed;\s+(\d+) failed;\s+(\d+) ignored;\s+(\d+) measured;\s+(\d+) filtered out(?:;\s+finished in ([\d.]+)s)?"
).unwrap()
});
let caps = re.captures(line)?;
let status = caps.get(1)?.as_str();
// Only aggregate if status is "ok" (all tests passed)
if status != "ok" {
return None;
}
let passed = caps.get(2)?.as_str().parse().ok()?;
let failed = caps.get(3)?.as_str().parse().ok()?;
let ignored = caps.get(4)?.as_str().parse().ok()?;
let measured = caps.get(5)?.as_str().parse().ok()?;
let filtered_out = caps.get(6)?.as_str().parse().ok()?;
let (duration_secs, has_duration) = if let Some(duration_match) = caps.get(7) {
(duration_match.as_str().parse().unwrap_or(0.0), true)
} else {
(0.0, false)
};
Some(Self {
passed,
failed,
ignored,
measured,
filtered_out,
suites: 1,
duration_secs,
has_duration,
})
}
/// Merge another test result into this one
fn merge(&mut self, other: &Self) {
self.passed += other.passed;
self.failed += other.failed;
self.ignored += other.ignored;
self.measured += other.measured;
self.filtered_out += other.filtered_out;
self.suites += other.suites;
self.duration_secs += other.duration_secs;
self.has_duration = self.has_duration && other.has_duration;
}
/// Format as compact single line
fn format_compact(&self) -> String {
let mut parts = vec![format!("{} passed", self.passed)];
if self.ignored > 0 {
parts.push(format!("{} ignored", self.ignored));
}
if self.filtered_out > 0 {
parts.push(format!("{} filtered out", self.filtered_out));
}
let counts = parts.join(", ");
let suite_text = if self.suites == 1 {
"1 suite".to_string()
} else {
format!("{} suites", self.suites)
};
if self.has_duration {
format!(
"cargo test: {} ({}, {:.2}s)",
counts, suite_text, self.duration_secs
)
} else {
format!("cargo test: {} ({})", counts, suite_text)
}
}
}
/// Filter cargo test output - show failures + summary only
fn filter_cargo_test(output: &str) -> String {
let mut failures: Vec<String> = Vec::new();
let mut summary_lines: Vec<String> = Vec::new();
let mut in_failure_section = false;
let mut current_failure = Vec::new();
for line in output.lines() {
// Skip compilation lines
if line.trim_start().starts_with("Compiling")
|| line.trim_start().starts_with("Downloading")
|| line.trim_start().starts_with("Downloaded")
|| line.trim_start().starts_with("Finished")
{
continue;
}
// Skip "running N tests" and individual "test ... ok" lines
if line.starts_with("running ") || (line.starts_with("test ") && line.ends_with("... ok")) {
continue;
}
// Detect failures section
if line == "failures:" {
in_failure_section = true;
continue;
}
if in_failure_section {
if line.starts_with("test result:") {
in_failure_section = false;
summary_lines.push(line.to_string());
} else if line.starts_with(" ") || line.starts_with("---- ") {
current_failure.push(line.to_string());
} else if line.trim().is_empty() && !current_failure.is_empty() {
failures.push(current_failure.join("\n"));
current_failure.clear();
} else if !line.trim().is_empty() {
current_failure.push(line.to_string());
}
}
// Capture test result summary
if !in_failure_section && line.starts_with("test result:") {
summary_lines.push(line.to_string());
}
}
if !current_failure.is_empty() {
failures.push(current_failure.join("\n"));
}
let mut result = String::new();
if failures.is_empty() && !summary_lines.is_empty() {
// All passed - try to aggregate
let mut aggregated: Option<AggregatedTestResult> = None;
let mut all_parsed = true;
for line in &summary_lines {
if let Some(parsed) = AggregatedTestResult::parse_line(line) {
if let Some(ref mut agg) = aggregated {
agg.merge(&parsed);
} else {
aggregated = Some(parsed);
}
} else {
all_parsed = false;
break;
}
}
// If all lines parsed successfully and we have at least one suite, return compact format
if all_parsed {
if let Some(agg) = aggregated {
if agg.suites > 0 {
return agg.format_compact();
}
}
}
// Fallback: use original behavior if regex failed
for line in &summary_lines {
result.push_str(&format!("{}\n", line));
}
return result.trim().to_string();
}
if !failures.is_empty() {
result.push_str(&format!("FAILURES ({}):\n", failures.len()));
result.push_str("═══════════════════════════════════════\n");
for (i, failure) in failures.iter().enumerate().take(10) {
result.push_str(&format!("{}. {}\n", i + 1, truncate(failure, 200)));
}
if failures.len() > 10 {
result.push_str(&format!("\n... +{} more failures\n", failures.len() - 10));
}
result.push('\n');
}
for line in &summary_lines {
result.push_str(&format!("{}\n", line));
}
if result.trim().is_empty() {
// Fallback: show last meaningful lines
let meaningful: Vec<&str> = output
.lines()
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with("Compiling"))
.collect();
for line in meaningful.iter().rev().take(5).rev() {
result.push_str(&format!("{}\n", line));
}
}
result.trim().to_string()
}
/// Filter cargo clippy output - group warnings by lint rule
fn filter_cargo_clippy(output: &str) -> String {
let mut by_rule: HashMap<String, Vec<String>> = HashMap::new();
let mut error_count = 0;
let mut warning_count = 0;
// Parse clippy output lines
// Format: "warning: description\n --> file:line:col\n |\n | code\n"
let mut current_rule = String::new();
for line in output.lines() {
// Skip compilation lines
if line.trim_start().starts_with("Compiling")
|| line.trim_start().starts_with("Checking")
|| line.trim_start().starts_with("Downloading")
|| line.trim_start().starts_with("Downloaded")
|| line.trim_start().starts_with("Finished")
{
continue;
}
// "warning: unused variable [unused_variables]" or "warning: description [clippy::rule_name]"
if (line.starts_with("warning:") || line.starts_with("warning["))
|| (line.starts_with("error:") || line.starts_with("error["))
{
// Skip summary lines: "warning: `rtk` (bin) generated 5 warnings"
if line.contains("generated") && line.contains("warning") {
continue;
}
// Skip "error: aborting" / "error: could not compile"
if line.contains("aborting due to") || line.contains("could not compile") {
continue;
}
let is_error = line.starts_with("error");
if is_error {
error_count += 1;
} else {
warning_count += 1;
}
// Extract rule name from brackets
current_rule = if let Some(bracket_start) = line.rfind('[') {
if let Some(bracket_end) = line.rfind(']') {
line[bracket_start + 1..bracket_end].to_string()
} else {
line.to_string()
}
} else {
// No bracket: use the message itself as the rule
let prefix = if is_error { "error: " } else { "warning: " };
line.strip_prefix(prefix).unwrap_or(line).to_string()
};
} else if line.trim_start().starts_with("--> ") {
let location = line.trim_start().trim_start_matches("--> ").to_string();
if !current_rule.is_empty() {
by_rule
.entry(current_rule.clone())
.or_default()
.push(location);
}
}
}
if error_count == 0 && warning_count == 0 {
return "cargo clippy: No issues found".to_string();
}
let mut result = String::new();
result.push_str(&format!(
"cargo clippy: {} errors, {} warnings\n",
error_count, warning_count
));
result.push_str("═══════════════════════════════════════\n");
// Sort rules by frequency
let mut rule_counts: Vec<_> = by_rule.iter().collect();
rule_counts.sort_by(|a, b| b.1.len().cmp(&a.1.len()));
for (rule, locations) in rule_counts.iter().take(15) {
result.push_str(&format!(" {} ({}x)\n", rule, locations.len()));
for loc in locations.iter().take(3) {
result.push_str(&format!(" {}\n", loc));
}
if locations.len() > 3 {
result.push_str(&format!(" ... +{} more\n", locations.len() - 3));
}
}
if by_rule.len() > 15 {
result.push_str(&format!("\n... +{} more rules\n", by_rule.len() - 15));
}
result.trim().to_string()
}
/// Runs an unsupported cargo subcommand by passing it through directly
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("cargo passthrough: {:?}", args);
}
let status = resolved_command("cargo")
.args(args)
.status()
.context("Failed to run cargo")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("cargo {}", args_str),
&format!("rtk cargo {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_restore_double_dash_with_separator() {
// rtk cargo test -- --nocapture → clap gives ["--nocapture"]
let args: Vec<String> = vec!["--nocapture".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"--".into(),
"--nocapture".into(),
];