-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathgo_cmd.rs
More file actions
1229 lines (1069 loc) · 43.3 KB
/
go_cmd.rs
File metadata and controls
1229 lines (1069 loc) · 43.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
//! Filters Go command output — test results, build errors, vet warnings.
use crate::core::runner;
use crate::core::tracking;
use crate::core::truncate::CAP_ERRORS;
use crate::core::utils::{exit_code_from_output, resolved_command, truncate};
use crate::golangci_cmd;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
use std::ffi::OsString;
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct GoTestEvent {
#[serde(rename = "Time")]
time: Option<String>,
#[serde(rename = "Action")]
action: String,
#[serde(rename = "Package")]
package: Option<String>,
#[serde(rename = "Test")]
test: Option<String>,
#[serde(rename = "Output")]
output: Option<String>,
#[serde(rename = "Elapsed")]
elapsed: Option<f64>,
#[serde(rename = "ImportPath")]
import_path: Option<String>,
#[serde(rename = "FailedBuild")]
failed_build: Option<String>,
}
#[derive(Debug, Default)]
struct PackageResult {
pass: usize,
fail: usize,
skip: usize,
build_failed: bool,
build_errors: Vec<String>,
failed_tests: Vec<(String, Vec<String>)>, // (test_name, output_lines)
package_failed: bool, // package-level failure (timeout, signal, etc.)
package_fail_output: Vec<String>, // output lines collected before the package fail
}
pub fn run_test(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("test");
let skip_json = args.iter().any(|a| a == "-json" || a.starts_with("-bench"));
if !skip_json {
cmd.arg("-json");
}
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!(
"Running: go test {}{}",
if !skip_json { "-json " } else { "" },
args.join(" ")
);
}
let filter: fn(&str) -> String = if skip_json {
|s: &str| s.to_string()
} else {
filter_go_test_json
};
// No tee: the raw stream is `go test -json` (3–8× more verbose than native
// output). A `[full output: …go_test.log]` pointer just advertises that
// firehose — agents cat it and pull back more bytes than the unfiltered run.
// The filter surfaces build errors and per-test failure detail inline instead.
runner::run_filtered(
cmd,
"go test",
&args.join(" "),
filter,
crate::core::runner::RunOptions::stdout_only(),
)
}
pub fn run_build(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("build");
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: go build {}", args.join(" "));
}
runner::run_filtered_with_exit(
cmd,
"go build",
&args.join(" "),
filter_go_build_with_exit,
crate::core::runner::RunOptions::with_tee("go_build"),
)
}
pub fn run_vet(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("vet");
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: go vet {}", args.join(" "));
}
runner::run_filtered(
cmd,
"go vet",
&args.join(" "),
filter_go_vet,
crate::core::runner::RunOptions::with_tee("go_vet"),
)
}
pub fn run_other(args: &[OsString], verbose: u8) -> Result<i32> {
if args.is_empty() {
anyhow::bail!("go: no subcommand specified");
}
// Intercept: `go tool <known>` invocations for filtered output
if let Some((tool, tool_args)) = match_go_tool(args) {
match tool {
GoTool::GolangciLint => return run_go_tool_golangci_lint(tool_args, verbose),
}
}
let timer = tracking::TimedExecution::start();
let subcommand = args[0].to_string_lossy();
let mut cmd = resolved_command("go");
cmd.arg(&*subcommand);
for arg in &args[1..] {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: go {} ...", subcommand);
}
let output = cmd
.output()
.with_context(|| format!("Failed to run go {}", subcommand))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
print!("{}", stdout);
eprint!("{}", stderr);
timer.track(
&format!("go {}", subcommand),
&format!("rtk go {}", subcommand),
&raw,
&raw, // No filtering for unsupported commands
);
Ok(exit_code_from_output(&output, "go"))
}
/// Detect golangci-lint major version when invoked via `go tool`.
/// Returns 1 on any failure (safe fallback — v1 behaviour).
fn detect_go_tool_golangci_version() -> u32 {
let output = resolved_command("go")
.arg("tool")
.arg("golangci-lint")
.arg("--version")
.output();
match output {
Ok(o) => {
let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr);
let version_text = if stdout.trim().is_empty() {
&*stderr
} else {
&*stdout
};
golangci_cmd::parse_major_version(version_text)
}
Err(_) => 1,
}
}
fn has_golangci_format_flag(args: &[OsString]) -> bool {
args.iter().any(|a| {
let s = a.to_string_lossy();
s == "--out-format"
|| s.starts_with("--out-format=")
|| s == "--output.json.path"
|| s.starts_with("--output.json.path=")
})
}
/// Known `go tool` subcommands that RTK provides filtered output for.
#[derive(Debug, Clone, Copy, PartialEq)]
enum GoTool {
GolangciLint,
}
impl GoTool {
fn from_name(name: &str) -> Option<Self> {
match name {
"golangci-lint" => Some(Self::GolangciLint),
_ => None,
}
}
}
/// If the first arg is `tool` identify if it is a tool we already handle.
fn match_go_tool(args: &[OsString]) -> Option<(GoTool, &[OsString])> {
if args.first().map(|a| a == "tool").unwrap_or(false) {
if let Some(tool_arg) = args.get(1) {
if let Some(tool) = GoTool::from_name(&tool_arg.to_string_lossy()) {
return Some((tool, &args[2..]));
}
}
}
None
}
/// Run `go tool golangci-lint` and filter its output via the golangci JSON filter.
/// Reusing parts of golangci_cmd.
fn run_go_tool_golangci_lint(args: &[OsString], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let version = detect_go_tool_golangci_version();
let mut cmd = resolved_command("go");
cmd.arg("tool").arg("golangci-lint");
let has_format = has_golangci_format_flag(args);
if !has_format {
if version >= 2 {
cmd.arg("run").arg("--output.json.path").arg("stdout");
} else {
cmd.arg("run").arg("--out-format=json");
}
} else {
cmd.arg("run");
}
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
if version >= 2 {
eprintln!("Running: go tool golangci-lint run --output.json.path stdout");
} else {
eprintln!("Running: go tool golangci-lint run --out-format=json");
}
}
let output = cmd
.output()
.context("Failed to run go tool golangci-lint")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
// v2 outputs JSON on first line + trailing text; v1 outputs just JSON
let json_output = if version >= 2 {
stdout.lines().next().unwrap_or("")
} else {
&*stdout
};
let exit_code = exit_code_from_output(&output, "go tool golangci-lint");
// golangci-lint: exit 0 = clean, exit 1 = lint issues found (not an error),
// exit 2+ = config/build error, None = killed by signal (OOM, SIGKILL)
let mapped_exit = if exit_code == 1 { 0 } else { exit_code };
// User chose their own output format — emit it verbatim rather than parsing
// it as JSON (which would fail and surface a parse-error string).
if has_format {
print!("{}", stdout);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
"go tool golangci-lint",
"rtk go tool golangci-lint (passthrough)",
&raw,
&raw,
);
return Ok(mapped_exit);
}
let filtered = golangci_cmd::filter_golangci_json(json_output, version);
println!("{}", filtered);
if !stderr.trim().is_empty() && verbose > 0 {
eprintln!("{}", stderr.trim());
}
timer.track(
"go tool golangci-lint",
"rtk go tool golangci-lint",
&raw,
&filtered,
);
Ok(mapped_exit)
}
/// Parse go test -json output (NDJSON format)
pub(crate) fn filter_go_test_json(output: &str) -> String {
let mut packages: HashMap<String, PackageResult> = HashMap::new();
let mut current_test_output: HashMap<(String, String), Vec<String>> = HashMap::new(); // (package, test) -> outputs
let mut build_output: HashMap<String, Vec<String>> = HashMap::new(); // import_path -> error lines
for line in output.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let event: GoTestEvent = match serde_json::from_str(trimmed) {
Ok(e) => e,
Err(_) => continue, // Skip non-JSON lines
};
// Handle build-output/build-fail events (use ImportPath, no Package)
match event.action.as_str() {
"build-output" => {
if let (Some(import_path), Some(output_text)) = (&event.import_path, &event.output)
{
let text = output_text.trim_end().to_string();
if !text.is_empty() {
build_output
.entry(import_path.clone())
.or_default()
.push(text);
}
}
continue;
}
"build-fail" => {
// build-fail has ImportPath — we'll handle it when the package-level fail arrives
continue;
}
_ => {}
}
let package = event.package.unwrap_or_else(|| "unknown".to_string());
let pkg_result = packages.entry(package.clone()).or_default();
match event.action.as_str() {
"pass" if event.test.is_some() => {
pkg_result.pass += 1;
}
"fail" => {
if let Some(test) = &event.test {
// Individual test failure
pkg_result.fail += 1;
// Collect output for failed test
let key = (package.clone(), test.clone());
let outputs = current_test_output.remove(&key).unwrap_or_default();
pkg_result.failed_tests.push((test.clone(), outputs));
} else if event.failed_build.is_some() {
// Package-level build failure
pkg_result.build_failed = true;
// Collect build errors from the import path
if let Some(import_path) = &event.failed_build {
if let Some(errors) = build_output.remove(import_path) {
pkg_result.build_errors = errors;
}
}
} else {
// Package-level failure without a specific test or build error
// (timeout, signal kill, panic before test execution, etc.)
pkg_result.package_failed = true;
}
}
"skip" if event.test.is_some() => {
pkg_result.skip += 1;
}
"output" => {
if let Some(output_text) = &event.output {
if let Some(test) = &event.test {
// Collect output for current test
let key = (package.clone(), test.clone());
current_test_output
.entry(key)
.or_default()
.push(output_text.trim_end().to_string());
} else {
// Package-level output (timeout messages, signal info, etc.)
let trimmed = output_text.trim();
if !trimmed.is_empty() {
pkg_result.package_fail_output.push(trimmed.to_string());
}
}
}
}
_ => {} // run, pause, cont, etc.
}
}
// Build summary
let total_packages = packages.len();
let total_pass: usize = packages.values().map(|p| p.pass).sum();
let total_fail: usize = packages.values().map(|p| p.fail).sum();
let total_skip: usize = packages.values().map(|p| p.skip).sum();
let total_build_fail: usize = packages.values().filter(|p| p.build_failed).count();
// Only count package-level fails for packages with no individual test or build failures.
// go test -json emits a trailing package-level {"action":"fail"} after any test failure
// too, but that event is just a cascade — the individual test failures are already counted.
let total_pkg_fail: usize = packages
.values()
.filter(|p| p.package_failed && p.fail == 0 && !p.build_failed)
.count();
let has_failures = total_fail > 0 || total_build_fail > 0 || total_pkg_fail > 0;
if !has_failures && total_pass == 0 {
return "Go test: No tests found".to_string();
}
if !has_failures {
return format!(
"Go test: {} passed in {} packages",
total_pass, total_packages
);
}
let mut result = String::new();
result.push_str(&format!(
"Go test: {} passed, {} failed",
total_pass,
total_fail + total_build_fail + total_pkg_fail
));
if total_skip > 0 {
result.push_str(&format!(", {} skipped", total_skip));
}
result.push_str(&format!(" in {} packages\n", total_packages));
// Show package-level failures first (timeouts, signals, panics).
// Skip packages that already have individual test-level failures — those are displayed
// in the per-package section below and the package-level event is just a cascade.
for (package, pkg_result) in packages.iter() {
if !pkg_result.package_failed || pkg_result.fail > 0 || pkg_result.build_failed {
continue;
}
result.push_str(&format!("\n{} [FAIL]\n", compact_package_name(package)));
for line in &pkg_result.package_fail_output {
let trimmed = line.trim();
if !trimmed.is_empty() {
result.push_str(&format!(" {}\n", truncate(trimmed, 120)));
}
}
}
// Show build failures
for (package, pkg_result) in packages.iter() {
if !pkg_result.build_failed {
continue;
}
result.push_str(&format!(
"\n{} [build failed]\n",
compact_package_name(package)
));
for line in &pkg_result.build_errors {
let trimmed = line.trim();
// Skip the "# package" header line
if !trimmed.starts_with('#') && !trimmed.is_empty() {
result.push_str(&format!(" {}\n", truncate(trimmed, 120)));
}
}
}
// Show failed tests grouped by package
for (package, pkg_result) in packages.iter() {
if pkg_result.fail == 0 {
continue;
}
result.push_str(&format!(
"\n{} ({} passed, {} failed)\n",
compact_package_name(package),
pkg_result.pass,
pkg_result.fail
));
for (test, outputs) in &pkg_result.failed_tests {
result.push_str(&format!(" [FAIL] {}\n", test));
for line in select_go_test_failure_lines(outputs) {
result.push_str(&format!(" {}\n", truncate(&line, 100)));
}
}
}
result.trim().to_string()
}
fn select_go_test_failure_lines(outputs: &[String]) -> Vec<String> {
let mut relevant = Vec::new();
let mut keep_next_context_line = false;
for line in outputs {
let trimmed = line.trim();
if trimmed.is_empty()
|| trimmed.starts_with("=== RUN")
|| trimmed.starts_with("--- FAIL")
|| trimmed.starts_with("--- PASS")
{
keep_next_context_line = false;
continue;
}
let is_location = is_go_test_location_line(trimmed);
let is_failure = is_go_test_failure_line(trimmed);
if is_location || is_failure || keep_next_context_line {
relevant.push(trimmed.to_string());
keep_next_context_line = is_location;
} else {
keep_next_context_line = false;
}
if relevant.len() >= 5 {
break;
}
}
if relevant.is_empty() {
if let Some(line) = outputs.iter().map(|line| line.trim()).find(|line| {
!line.is_empty()
&& !line.starts_with("=== RUN")
&& !line.starts_with("--- FAIL")
&& !line.starts_with("--- PASS")
}) {
relevant.push(line.to_string());
}
}
relevant
}
fn is_go_test_location_line(line: &str) -> bool {
if let Some((_, rest)) = line.split_once(".go:") {
rest.chars()
.next()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
} else {
false
}
}
fn is_go_test_failure_line(line: &str) -> bool {
let lower = line.to_lowercase();
lower.starts_with("panic:")
|| lower.starts_with("error:")
|| lower.contains(" error:")
|| lower.contains("expected")
|| lower.contains("got")
|| lower.contains("want")
|| lower.contains("actual")
|| lower.contains("assert")
|| lower.contains("mismatch")
|| lower.contains("unexpected")
|| lower.contains("fatal")
|| line.starts_with("at ")
}
/// Filter go build output - show only errors
pub(crate) fn filter_go_build(output: &str) -> String {
filter_go_build_with_exit(output, 0)
}
fn filter_go_build_with_exit(output: &str, exit_code: i32) -> String {
let mut errors: Vec<String> = Vec::new();
for line in output.lines() {
let trimmed = line.trim();
if is_go_build_error_line(trimmed) {
errors.push(trimmed.to_string());
}
}
if errors.is_empty() {
return if exit_code == 0 {
"Go build: Success".to_string()
} else {
format_go_build_failure(output, exit_code)
};
}
let mut result = String::new();
result.push_str(&format!("Go build: {} errors\n", errors.len()));
const MAX_GO_BUILD_ERRORS: usize = CAP_ERRORS;
for (i, error) in errors.iter().take(MAX_GO_BUILD_ERRORS).enumerate() {
result.push_str(&format!("{}. {}\n", i + 1, truncate(error, 120)));
}
if errors.len() > MAX_GO_BUILD_ERRORS {
result.push_str(&format!("\n… +{} more errors\n", errors.len() - MAX_GO_BUILD_ERRORS));
let all_errors = errors.join("\n");
if let Some(hint) = crate::core::tee::force_tee_tail_hint(&all_errors, "go-build", MAX_GO_BUILD_ERRORS + 1) {
result.push_str(&format!(" {}\n", hint));
}
}
result.trim().to_string()
}
fn format_go_build_failure(output: &str, exit_code: i32) -> String {
let lines: Vec<String> = output
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(str::to_string)
.collect();
if lines.is_empty() {
return format!("Go build: failed (exit {})", exit_code);
}
let mut result = String::new();
result.push_str(&format!("Go build: failed (exit {})\n", exit_code));
result.push_str("═══════════════════════════════════════\n");
const MAX_GO_BUILD_ERRORS: usize = CAP_ERRORS;
for (i, line) in lines.iter().take(MAX_GO_BUILD_ERRORS).enumerate() {
result.push_str(&format!("{}. {}\n", i + 1, truncate(line, 120)));
}
if lines.len() > MAX_GO_BUILD_ERRORS {
result.push_str(&format!(
"\n… +{} more output lines\n",
lines.len() - MAX_GO_BUILD_ERRORS
));
}
result.trim().to_string()
}
fn is_go_build_error_line(line: &str) -> bool {
let trimmed = line.trim();
if trimmed.is_empty() {
return false;
}
let lower = trimmed.to_lowercase();
// Go download/progress lines often contain package names like pkg/errors,
// xerrors, or multierror. These are not compilation failures.
if lower.starts_with("go: downloading ")
|| lower.starts_with("go: finding ")
|| lower.starts_with("go: extracting ")
{
return false;
}
// Package headers are context, not errors by themselves.
if trimmed.starts_with('#') {
return false;
}
// Canonical compiler/config error locations: file:line:col: ...
let is_go_config_location = !lower.starts_with("go: ")
&& (lower.contains("go.mod:") || lower.contains("go.work:") || lower.contains("go.sum:"));
if trimmed.contains(".go:") || is_go_config_location {
return true;
}
// Some compiler/module failures do not include a file.go:line:col location.
let non_file_error_prefixes = [
"undefined: ",
"cannot use ",
"cannot find package ",
"no required module provides package ",
"missing go.sum entry for module providing package ",
"found packages ",
"go: go.mod file not found in current directory or any parent directory",
"go: cannot load module ",
"go: build failed",
"go: error ",
"error: ",
"pattern ",
"go: updates to go.mod needed",
"go: inconsistent vendoring",
"no go files in ",
];
non_file_error_prefixes
.iter()
.any(|prefix| lower.starts_with(prefix))
|| lower.contains("import cycle not allowed")
|| lower.contains("build constraints exclude all go files")
|| lower.contains("function main is undeclared in the main package")
}
/// Filter go vet output - show issues.
///
/// vet only prints when something is wrong, so every non-`#` line is signal —
/// including location-less compiler/cgo failures (`fatal error: …`) that have
/// no `.go:`. Filtering on `.go:` dropped those and reported "No issues found"
/// on a hard failure; truncation cut the message tail an agent retries to read.
fn filter_go_vet(output: &str) -> String {
let issues: Vec<&str> = output
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.collect();
if issues.is_empty() {
return "Go vet: No issues found".to_string();
}
let mut result = format!("Go vet: {} issues\n", issues.len());
const MAX_GO_VET_ISSUES: usize = CAP_ERRORS;
for (i, issue) in issues.iter().take(MAX_GO_VET_ISSUES).enumerate() {
result.push_str(&format!("{}. {}\n", i + 1, issue));
}
if issues.len() > MAX_GO_VET_ISSUES {
result.push_str(&format!(
"\n… +{} more issues\n",
issues.len() - MAX_GO_VET_ISSUES
));
let all_issues = issues.join("\n");
if let Some(hint) =
crate::core::tee::force_tee_tail_hint(&all_issues, "go-vet", MAX_GO_VET_ISSUES + 1)
{
result.push_str(&format!(" {}\n", hint));
}
}
result.trim().to_string()
}
/// Compact package name (remove long paths)
fn compact_package_name(package: &str) -> String {
// Remove common module prefixes like github.com/user/repo/
if let Some(pos) = package.rfind('/') {
package[pos + 1..].to_string()
} else {
package.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_go_test_all_pass() {
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestBar"}
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestBar","Output":"=== RUN TestBar\n"}
{"Time":"2024-01-01T10:00:02Z","Action":"pass","Package":"example.com/foo","Test":"TestBar","Elapsed":0.5}
{"Time":"2024-01-01T10:00:02Z","Action":"pass","Package":"example.com/foo","Elapsed":0.5}"#;
let result = filter_go_test_json(output);
assert!(result.contains("Go test"));
assert!(result.contains("1 passed"));
assert!(result.contains("1 packages"));
}
#[test]
fn test_filter_go_test_with_failures() {
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestFail"}
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":"=== RUN TestFail\n"}
{"Time":"2024-01-01T10:00:02Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" Error: expected 5, got 3\n"}
{"Time":"2024-01-01T10:00:03Z","Action":"fail","Package":"example.com/foo","Test":"TestFail","Elapsed":0.5}
{"Time":"2024-01-01T10:00:03Z","Action":"fail","Package":"example.com/foo","Elapsed":0.5}"#;
let result = filter_go_test_json(output);
assert!(result.contains("1 failed"));
assert!(result.contains("TestFail"));
assert!(result.contains("expected 5, got 3"));
}
#[test]
fn test_filter_go_test_preserves_file_location_and_followup_context() {
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestFail"}
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":"=== RUN TestFail\n"}
{"Time":"2024-01-01T10:00:02Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" foo_test.go:42:\n"}
{"Time":"2024-01-01T10:00:03Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" values differ after normalization\n"}
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Test":"TestFail","Elapsed":0.5}
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Elapsed":0.5}"#;
let result = filter_go_test_json(output);
assert!(result.contains("foo_test.go:42:"));
assert!(result.contains("values differ after normalization"));
}
#[test]
fn test_filter_go_test_timeout_package_fail() {
// When go test times out, the JSON stream has a package-level "fail"
// with no Test field and no FailedBuild field. This should be reported
// as a failure, not "No tests found".
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"start","Package":"example.com/foo"}
{"Time":"2024-01-01T10:01:03Z","Action":"output","Package":"example.com/foo","Output":"*** Test killed with quit: ran too long (1m3s).\n"}
{"Time":"2024-01-01T10:01:03Z","Action":"output","Package":"example.com/foo","Output":"FAIL\texample.com/foo\t63.001s\n"}
{"Time":"2024-01-01T10:01:03Z","Action":"fail","Package":"example.com/foo","Elapsed":63.003}"#;
let result = filter_go_test_json(output);
assert!(
result.contains("1 failed"),
"Expected '1 failed' in output, got: {}",
result
);
assert!(
!result.contains("No tests found"),
"Should not say 'No tests found' on timeout, got: {}",
result
);
assert!(
result.contains("FAIL"),
"Expected failure output in summary, got: {}",
result
);
}
#[test]
fn test_filter_go_test_no_double_count_on_test_failure() {
// go test -json always emits a package-level {"action":"fail"} after each
// test-level failure. The package-level event is a cascade, not an additional
// failure. The summary header must show "1 failed", not "2 failed".
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestFail"}
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":"=== RUN TestFail\n"}
{"Time":"2024-01-01T10:00:02Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" Error: expected 5, got 3\n"}
{"Time":"2024-01-01T10:00:03Z","Action":"fail","Package":"example.com/foo","Test":"TestFail","Elapsed":0.5}
{"Time":"2024-01-01T10:00:03Z","Action":"fail","Package":"example.com/foo","Elapsed":0.5}"#;
let result = filter_go_test_json(output);
// The summary header must say "1 failed", not "2 failed" (no double-counting).
assert!(
result.starts_with("Go test: 0 passed, 1 failed"),
"Expected header 'Go test: 0 passed, 1 failed', got: {}",
result
);
assert!(result.contains("TestFail"));
assert!(result.contains("expected 5, got 3"));
// The package must NOT appear twice (once as "[FAIL]" and once with test details).
assert_eq!(
result.matches("foo").count(),
1,
"Package name should appear exactly once, got: {}",
result
);
}
#[test]
fn test_filter_go_test_timeout_with_signal_quit_output() {
// Exact reproduction of the scenario from issue #958: the signal: quit line
// appears as a separate JSON output event.
let output = r#"{"Action":"start","Package":"example.com/pkg"}
{"Action":"output","Package":"example.com/pkg","Output":"*** Test killed with quit: ran too long (1m30s).\n"}
{"Action":"output","Package":"example.com/pkg","Output":"signal: quit\n"}
{"Action":"output","Package":"example.com/pkg","Output":"FAIL\texample.com/pkg\t90.000s\n"}
{"Action":"fail","Package":"example.com/pkg","Elapsed":90.001}"#;
let result = filter_go_test_json(output);
assert!(
result.starts_with("Go test: 0 passed, 1 failed"),
"Expected 'Go test: 0 passed, 1 failed', got: {}",
result
);
assert!(
!result.contains("No tests found"),
"Must not say 'No tests found' on timeout, got: {}",
result
);
assert!(
result.contains("Test killed with quit"),
"Should show the timeout message, got: {}",
result
);
}
#[test]
fn test_filter_go_test_timeout_with_passing_tests_before_kill() {
// Some tests pass before the package times out.
// Summary should show both pass and fail counts.
let output = r#"{"Action":"run","Package":"example.com/foo","Test":"TestFast"}
{"Action":"pass","Package":"example.com/foo","Test":"TestFast","Elapsed":0.001}
{"Action":"run","Package":"example.com/foo","Test":"TestHang"}
{"Action":"output","Package":"example.com/foo","Output":"*** Test killed with quit: ran too long (30s).\n"}
{"Action":"fail","Package":"example.com/foo","Elapsed":30.001}"#;
let result = filter_go_test_json(output);
assert!(
result.starts_with("Go test: 1 passed, 1 failed"),
"Expected 'Go test: 1 passed, 1 failed', got: {}",
result
);
assert!(
!result.contains("No tests found"),
"Must not say 'No tests found', got: {}",
result
);
assert!(
result.contains("Test killed with quit"),
"Should show timeout message, got: {}",
result
);
}
#[test]
fn test_filter_go_test_surfaces_cgo_build_error_inline() {
// A cgo build failure (missing C header) must show the compiler error
// line inline — this is the one actionable fact. With no tee pointer,
// the agent has no firehose to fall back to, so the signal must be here.
let output = r##"{"Action":"start","Package":"example.com/sniff"}
{"ImportPath":"example.com/sniff","Action":"build-output","Output":"# example.com/sniff\n"}
{"ImportPath":"example.com/sniff","Action":"build-output","Output":"./capture.go:7:11: fatal error: pcap.h: No such file or directory\n"}
{"ImportPath":"example.com/sniff","Action":"build-fail"}
{"Package":"example.com/sniff","Action":"fail","FailedBuild":"example.com/sniff"}"##;
let result = filter_go_test_json(output);
assert!(
result.contains("[build failed]"),
"Expected build-failed marker, got: {}",
result
);
assert!(
result.contains("pcap.h: No such file or directory"),
"Compiler error line must survive inline, got: {}",
result
);
// The "# package" header is noise and should be dropped.
assert!(
!result.contains("# example.com/sniff"),
"Package header should be stripped, got: {}",
result
);
}
#[test]
fn test_filter_go_build_success() {
let output = "";
let result = filter_go_build(output);
assert!(result.contains("Go build"));
assert!(result.contains("Success"));
}
#[test]
fn test_filter_go_build_errors() {
let output = r#"# example.com/foo
main.go:10:5: undefined: missingFunc
main.go:15:2: cannot use x (type int) as type string"#;
let result = filter_go_build(output);
assert!(result.contains("2 errors"));
assert!(result.contains("undefined: missingFunc"));
assert!(result.contains("cannot use x"));
}
#[test]
fn test_filter_go_build_ignores_download_lines_with_error_in_package_names() {
let output = r#"go: downloading github.com/go-errors/errors v1.5.1
go: finding module for package example.com/foo
go: extracting github.com/pkg/errors v0.9.1
go: downloading github.com/pkg/errors v0.9.1
go: downloading github.com/hashicorp/go-multierror v1.1.1
go: downloading golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2"#;
let result = filter_go_build(output);
assert_eq!(result, "Go build: Success");
}
#[test]
fn test_is_go_build_error_line_recognizes_real_compiler_errors() {
assert!(is_go_build_error_line("undefined: missingFunc"));
assert!(is_go_build_error_line("cannot find package \"foo/bar\""));
assert!(is_go_build_error_line(
"found packages a (a.go) and b (b.go) in /tmp/rtk-go-build-probe-mix"
));
assert!(is_go_build_error_line(