Skip to main content

aft_base/compress/
cargo.rs

1use crate::compress::caps::{cap_classified_blocks, ClassifiedBlock, DropClass};
2use crate::compress::generic::GenericCompressor;
3use crate::compress::line_cut::ensure_final_lines;
4use crate::compress::{CompressionResult, Compressor};
5
6pub struct CargoCompressor;
7
8impl Compressor for CargoCompressor {
9    fn matches(&self, command: &str) -> bool {
10        command
11            .split_whitespace()
12            .next()
13            .is_some_and(|head| head == "cargo")
14    }
15
16    fn compress_with_exit_code(
17        &self,
18        command: &str,
19        output: &str,
20        exit_code: Option<i64>,
21    ) -> CompressionResult {
22        if let Some(raw) = short_output_passthrough(output) {
23            return raw;
24        }
25        match cargo_subcommand(command).as_deref() {
26            Some("build" | "check" | "clippy") => compress_build_like(output),
27            Some("test") => compress_test(output, exit_code),
28            _ => GenericCompressor::compress_output(output).into(),
29        }
30    }
31
32    fn matches_output(&self, output: &str) -> bool {
33        output.lines().any(is_cargo_test_signature_line)
34    }
35
36    fn compress_output_match_with_exit_code(
37        &self,
38        output: &str,
39        exit_code: Option<i64>,
40    ) -> CompressionResult {
41        if let Some(raw) = short_output_passthrough(output) {
42            return raw;
43        }
44        compress_test(output, exit_code)
45    }
46}
47
48/// Output this short goes back exactly as the command printed it. A summary
49/// saves almost nothing at this size, and every line it leaves out is one the
50/// reader may need. 1 KiB is the size below which `git status` output is
51/// already passed through raw (`git::STATUS_SHORT_LIMIT`), and the byte window
52/// `line_cut::ensure_final_lines` keeps verbatim at the end of any output.
53const SHORT_OUTPUT_BYTES: usize = 1024;
54
55fn short_output_passthrough(output: &str) -> Option<CompressionResult> {
56    (output.len() <= SHORT_OUTPUT_BYTES).then(|| CompressionResult::new(output.to_string()))
57}
58
59fn is_cargo_test_signature_line(line: &str) -> bool {
60    line.starts_with("test result:")
61        || line.starts_with("failures:")
62        || (line.starts_with("---- ") && line.ends_with(" stdout ----"))
63}
64
65fn cargo_subcommand(command: &str) -> Option<String> {
66    let mut tokens = command.split_whitespace();
67    while let Some(token) = tokens.next() {
68        if token == "cargo" {
69            break;
70        }
71    }
72    while let Some(token) = tokens.next() {
73        if crate::compress::is_shell_boundary(token) {
74            return None;
75        }
76        if matches!(
77            token,
78            "-Z" | "--config"
79                | "--color"
80                | "--manifest-path"
81                | "--target-dir"
82                | "--lockfile-path"
83                | "-C"
84        ) {
85            if tokens.next().is_none_or(crate::compress::is_shell_boundary) {
86                return None;
87            }
88        } else if !token.starts_with('-') && !token.starts_with('+') {
89            return Some(token.to_string());
90        }
91    }
92    None
93}
94
95fn compress_build_like(output: &str) -> CompressionResult {
96    let lines: Vec<&str> = output.lines().collect();
97    let has_diagnostic = lines
98        .iter()
99        .any(|line| is_warning_or_error(line) || line.trim_start().starts_with("error["));
100
101    if !has_diagnostic {
102        return CompressionResult::new(output.trim_end().to_string());
103    }
104
105    let mut blocks = Vec::new();
106    let mut index = 0usize;
107
108    while index < lines.len() {
109        let line = lines[index];
110        let noise = line.trim().is_empty()
111            || (is_cargo_status_line(line) && !is_final_cargo_summary(line))
112            || is_test_progress_line(line.trim());
113        if noise {
114            index += 1;
115            continue;
116        }
117
118        if is_warning_or_error(line) || line.trim_start().starts_with("error[") {
119            let class = if line.trim_start().starts_with("warning:") {
120                DropClass::Warning
121            } else {
122                DropClass::Error
123            };
124            let start = index;
125            index += 1;
126            // The block owns the diagnostic's own body only. A line that does
127            // not continue it (another tool's verdict in a gate script) is not
128            // the diagnostic's to lose when the block is capped.
129            let mut body = DiagnosticBody::default();
130            while index < lines.len()
131                && !starts_next_build_message(lines[index])
132                && body.continues(lines[index])
133            {
134                index += 1;
135            }
136            blocks.push(ClassifiedBlock::new(class, lines[start..index].join("\n")));
137            continue;
138        }
139
140        // Cargo's final summary and any line cargo did not write itself.
141        blocks.push(ClassifiedBlock::unclassified(line.to_string()));
142        index += 1;
143    }
144
145    let capped = cap_classified_blocks(blocks);
146    CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
147        .map_text(|text| ensure_final_lines(output, text))
148}
149
150fn starts_next_build_message(line: &str) -> bool {
151    is_cargo_status_line(line)
152        || is_warning_or_error(line)
153        || line.trim_start().starts_with("error[")
154        || is_final_cargo_summary(line)
155}
156
157fn is_warning_or_error(line: &str) -> bool {
158    let trimmed = line.trim_start();
159    trimmed.starts_with("warning:") || trimmed.starts_with("error:")
160}
161
162fn is_error_diagnostic(line: &str) -> bool {
163    let trimmed = line.trim_start();
164    trimmed.starts_with("error:") || trimmed.starts_with("error[")
165}
166
167fn is_ignored_progress(line: &str) -> bool {
168    let trimmed = line.trim_start();
169    trimmed == "Updating crates.io index" || is_compiling_line(trimmed)
170}
171
172fn is_compiling_line(trimmed: &str) -> bool {
173    let Some(rest) = trimmed.strip_prefix("Compiling ") else {
174        return false;
175    };
176    let mut parts = rest.split_whitespace();
177    let _crate_name = parts.next();
178    parts.next().is_some_and(|part| {
179        part.strip_prefix('v').is_some_and(|version| {
180            version
181                .chars()
182                .all(|char| char.is_ascii_digit() || char == '.')
183        })
184    })
185}
186
187fn is_final_cargo_summary(line: &str) -> bool {
188    let trimmed = line.trim_start();
189    trimmed.starts_with("Finished ")
190        || trimmed.starts_with("error: could not compile")
191        || trimmed.starts_with("test result:")
192}
193
194/// Cargo status verbs. Cargo right-aligns them in a 12-column field, so a real
195/// status line is indented; an unindented "Running checks" from a script is not
196/// one.
197const CARGO_STATUS_VERBS: &[&str] = &[
198    "Adding",
199    "Blocking",
200    "Building",
201    "Checking",
202    "Compiling",
203    "Doc-tests",
204    "Documenting",
205    "Downloaded",
206    "Downloading",
207    "Executable",
208    "Finished",
209    "Fresh",
210    "Locking",
211    "Running",
212    "Updating",
213];
214
215fn is_cargo_status_line(line: &str) -> bool {
216    if is_ignored_progress(line) {
217        return true;
218    }
219    let trimmed = line.trim_start();
220    line.starts_with(' ')
221        && CARGO_STATUS_VERBS.iter().any(|verb| {
222            trimmed
223                .strip_prefix(verb)
224                .is_some_and(|rest| rest.starts_with(' '))
225        })
226}
227
228/// libtest's per-test progress (`test name ... ok`, `... ignored`,
229/// `... FAILED`) and its slow-test notice. The `test result:` line and the
230/// failure list already account for every one of them.
231fn is_test_progress_line(trimmed: &str) -> bool {
232    trimmed.strip_prefix("test ").is_some_and(|rest| {
233        rest.contains(" ... ") || rest.ends_with(" has been running for over 60 seconds")
234    }) || is_nextest_progress_line(trimmed)
235}
236
237/// cargo nextest's per-test progress for tests that did not fail, which its
238/// `Summary [` line accounts for: `PASS [   0.004s] name`, `SLOW [> 60.000s]
239/// name`, `SKIP [ ] name` and `Starting N tests across M binaries`. `FAIL [`
240/// and `TIMEOUT [` lines are not progress: they name the failures and are kept.
241fn is_nextest_progress_line(trimmed: &str) -> bool {
242    let bracketed = |status: &str| {
243        trimmed
244            .strip_prefix(status)
245            .and_then(|rest| rest.trim_start().strip_prefix('['))
246            .and_then(|rest| rest.split_once(']'))
247            .map(|(inside, _)| inside.trim().trim_start_matches("> "))
248    };
249    let timed = |inside: &str| {
250        inside
251            .strip_suffix('s')
252            .is_some_and(|seconds| seconds.parse::<f64>().is_ok())
253    };
254    bracketed("PASS").is_some_and(timed)
255        || bracketed("SLOW").is_some_and(timed)
256        || bracketed("SKIP").is_some()
257        || trimmed
258            .strip_prefix("Starting ")
259            .is_some_and(|rest| rest.contains(" tests across "))
260}
261
262/// Follows the body of one rustc or clippy diagnostic line by line and says
263/// whether each line still belongs to it. A line belongs only when it has a
264/// shape the compiler prints; indentation alone proves nothing, because a gate
265/// script's indented verdict (`  win-check rc=101`) is just as indented. A
266/// blank line ends the body: rustc separates diagnostics with one and never
267/// puts one inside.
268#[derive(Default)]
269struct DiagnosticBody {
270    /// Column of the `=` of the last `= note:` / `= help:` line. rustc wraps a
271    /// long note onto following lines aligned past that `= label: ` prefix.
272    label_column: Option<usize>,
273}
274
275impl DiagnosticBody {
276    fn continues(&mut self, line: &str) -> bool {
277        let trimmed = line.trim_start();
278        let indent = line.len() - trimmed.len();
279        if trimmed.is_empty() {
280            self.label_column = None;
281            return false;
282        }
283        if is_equals_label(trimmed) {
284            self.label_column = Some(indent);
285            return true;
286        }
287        // `= note: expected type `u32``
288        // `           found reference `&str``
289        if self
290            .label_column
291            .is_some_and(|column| indent > column + "= ".len())
292        {
293            return true;
294        }
295        self.label_column = None;
296        trimmed.starts_with("--> ")
297            || trimmed.starts_with("::: ")
298            || is_diagnostic_gutter(line)
299            || trimmed.starts_with('^')
300            || trimmed == "..."
301            || trimmed.starts_with("help:")
302            || trimmed.starts_with("note:")
303    }
304}
305
306/// `= note: ...`, `= help: ...` and the like: an indented `= ` followed by a
307/// lowercase word and a colon.
308fn is_equals_label(trimmed: &str) -> bool {
309    trimmed
310        .strip_prefix("= ")
311        .and_then(|rest| rest.split_once(':'))
312        .is_some_and(|(word, _)| {
313            !word.is_empty() && word.chars().all(|char| char.is_ascii_lowercase())
314        })
315}
316
317/// The source gutter rustc draws down a diagnostic: `   |` (with carets,
318/// underlines or labels after it), `12 | code`, and a suggestion's diff lines
319/// `12 + code`, `12 - code`, `12 ~ code`. An unnumbered gutter is always
320/// indented; a diff marker always follows a line number.
321fn is_diagnostic_gutter(line: &str) -> bool {
322    let trimmed = line.trim_start();
323    let digits = trimmed.len()
324        - trimmed
325            .trim_start_matches(|char: char| char.is_ascii_digit())
326            .len();
327    let after_number = &trimmed[digits..];
328    let marker_text = after_number.trim_start();
329    let mut marker = marker_text.chars();
330    let Some(symbol) = marker.next() else {
331        return false;
332    };
333    let marker_ends = marker.next().is_none_or(char::is_whitespace);
334    if digits == 0 {
335        return line.starts_with(char::is_whitespace) && symbol == '|' && marker_ends;
336    }
337    after_number.starts_with(char::is_whitespace)
338        && matches!(symbol, '|' | '+' | '-' | '~')
339        && marker_ends
340}
341
342/// Mark the lines of a `cargo test` run that its summary may leave out because
343/// the summary already accounts for them: blank lines, per-test progress,
344/// cargo's status lines and compiler warning blocks. Every other line is
345/// somebody's report (a test's printed output, another check's verdict in a
346/// gate script) and must be kept verbatim and in order.
347fn test_noise_mask(lines: &[&str]) -> Vec<bool> {
348    let mut warning: Option<DiagnosticBody> = None;
349    lines
350        .iter()
351        .map(|line| {
352            let trimmed = line.trim();
353            if trimmed.is_empty() {
354                warning = None;
355                return true;
356            }
357            if trimmed.starts_with("warning:") {
358                warning = Some(DiagnosticBody::default());
359                return true;
360            }
361            if warning.as_mut().is_some_and(|body| body.continues(line)) {
362                return true;
363            }
364            warning = None;
365            is_test_progress_line(trimmed) || is_cargo_status_line(line)
366        })
367        .collect()
368}
369
370fn compress_test(output: &str, exit_code: Option<i64>) -> CompressionResult {
371    let lines: Vec<&str> = output.lines().collect();
372    let noise = test_noise_mask(&lines);
373    let failure_headers = failure_list_headers(&lines);
374    let has_failures = failure_headers.iter().any(|header| *header);
375    let total = cargo_test_total_line(&lines);
376    if !has_failures {
377        let has_error_diagnostic = lines.iter().any(|line| is_error_diagnostic(line));
378        let has_warning_or_error = lines
379            .iter()
380            .any(|line| is_warning_or_error(line) || line.trim_start().starts_with("error["));
381        if has_error_diagnostic
382            || (matches!(exit_code, Some(code) if code != 0) && has_warning_or_error)
383        {
384            return append_cargo_test_total(compress_build_like(output), total.as_deref());
385        }
386
387        let result: Vec<String> = lines
388            .iter()
389            .zip(&noise)
390            .filter(|(line, noise)| {
391                let trimmed = line.trim_start();
392                trimmed.starts_with("running ")
393                    || trimmed.starts_with("test result:")
394                    || is_final_cargo_summary(trimmed)
395                    || !**noise
396            })
397            .map(|(line, _)| (*line).to_string())
398            .collect();
399        return append_cargo_test_total(
400            CompressionResult::new(ensure_final_lines(
401                output,
402                &trim_trailing_lines(&result.join("\n")),
403            )),
404            total.as_deref(),
405        );
406    }
407
408    let mut sections = Vec::new();
409    let mut summary = Vec::new();
410    let mut names = Vec::new();
411    let mut seen_names = std::collections::HashSet::new();
412    let mut in_failure_list = false;
413    let mut warnings = 0;
414    let mut index = 0usize;
415    while index < lines.len() {
416        let line = lines[index];
417        let trimmed = line.trim_start();
418        if failure_headers[index] {
419            in_failure_list = true;
420            index += 1;
421            continue;
422        }
423        if let Some(name) = failure_name(trimmed.trim_end(), in_failure_list) {
424            if seen_names.insert(name) {
425                names.push(name);
426            }
427            if !line.starts_with("---- ") {
428                index += 1;
429                continue;
430            }
431        } else if !trimmed.is_empty() {
432            in_failure_list = false;
433        }
434
435        if line.starts_with("---- ") {
436            let start = index;
437            while index < lines.len() {
438                index += 1;
439                if index < lines.len()
440                    && (lines[index].starts_with("---- ")
441                        || lines[index].trim_start().starts_with("test result:")
442                        || failure_headers[index])
443                {
444                    break;
445                }
446            }
447            sections.push(&lines[start..index]);
448            in_failure_list = false;
449            continue;
450        }
451
452        if trimmed.starts_with("warning:") {
453            warnings += 1;
454        }
455        if trimmed.starts_with("test result:") {
456            // A new test binary may report the same name as an earlier one.
457            seen_names.clear();
458        }
459        if !noise[index] {
460            summary.push(line);
461        }
462        index += 1;
463    }
464
465    let list = format!("failures:\n    {}", names.join("\n    "));
466    let verdict_at = summary
467        .iter()
468        .position(|line| line.trim_start().starts_with("test result:"))
469        .unwrap_or(summary.len());
470    summary.insert(verdict_at, &list);
471    let summary =
472        append_cargo_test_total(CompressionResult::new(summary.join("\n")), total.as_deref());
473    let summary = summary.map_text(|text| ensure_final_lines(output, text));
474    let (details, dropped) = bounded_failure_sections(&sections, summary.text.len());
475    let text = if details.is_empty() {
476        summary.text
477    } else {
478        summary
479            .text
480            .replacen(&list, &format!("{details}\n{list}"), 1)
481    };
482    let mut drops = std::collections::BTreeMap::new();
483    if warnings > 0 {
484        drops.insert(DropClass::Warning, warnings);
485    }
486    if dropped > 0 {
487        drops.insert(DropClass::Failure, dropped);
488    }
489    let mut result = CompressionResult::with_class_drops(text, drops);
490    result.bounded_cargo_test_details = true;
491    result
492}
493
494// Failed completion previews have a 512-byte head and a 1,792-byte tail,
495// not a fixed line cap. Reserve the names and results before spending the tail
496// on panic sections, so compiler warnings cannot displace the explanation.
497test_support_visibility! {
498const FAILURE_SECTION_LINES: usize = 6;
499}
500test_support_visibility! {
501const FAILURE_DETAIL_LINES: usize = 20;
502}
503const FAILURE_DETAIL_BYTES: usize = super::caps::COMPLETION_FAILURE_TAIL_BYTES;
504
505fn bounded_failure_sections(sections: &[&[&str]], summary_bytes: usize) -> (String, usize) {
506    let mut remaining_bytes = FAILURE_DETAIL_BYTES.saturating_sub(summary_bytes + 1);
507    let mut remaining_lines = FAILURE_DETAIL_LINES;
508    let mut kept = Vec::new();
509    let mut dropped = 0;
510    for section in sections {
511        let panic = section.iter().position(|line| line.contains("panicked at"));
512        let start = panic.unwrap_or(1);
513        let body: Vec<&str> = section[start..]
514            .iter()
515            .copied()
516            .filter(|line| {
517                !line.trim().is_empty()
518                    && !line
519                        .trim_start()
520                        .starts_with("note: run with `RUST_BACKTRACE")
521            })
522            .collect();
523        let mut candidate = vec![section[0]];
524        let mut bytes = section[0].len() + 1;
525        // A panic location alone does not explain why the assertion failed.
526        // Keep the header and the first two body lines together, or omit them.
527        let minimum = body.len().min(2);
528        let minimum_bytes = bytes
529            + body[..minimum]
530                .iter()
531                .map(|line| line.len() + 1)
532                .sum::<usize>();
533        if remaining_lines < minimum + 1 || remaining_bytes < minimum_bytes {
534            dropped += 1;
535            continue;
536        }
537        for line in &body {
538            if candidate.len() == FAILURE_SECTION_LINES
539                || candidate.len() == remaining_lines
540                || bytes + line.len() + 1 > remaining_bytes
541            {
542                break;
543            }
544            candidate.push(line);
545            bytes += line.len() + 1;
546        }
547        if candidate.len() < body.len() + 1 {
548            dropped += 1;
549        }
550        remaining_lines -= candidate.len();
551        remaining_bytes -= bytes;
552        kept.extend(candidate);
553    }
554    (kept.join("\n"), dropped)
555}
556
557test_support_visibility! {
558pub(super) fn failure_summary_preserved(raw: &str, compressed: &str) -> bool {
559    let raw_counts = failure_name_counts(raw);
560    let compressed_counts = failure_name_counts(compressed);
561    if raw_counts.is_empty()
562        || raw_counts.iter().any(|(name, views)| {
563            compressed_counts.get(name).map_or(0, |counts| counts[2]) < *views.iter().max().unwrap()
564        })
565    {
566        return false;
567    }
568    let mut saw_result = false;
569    let compressed_lines: std::collections::HashSet<_> =
570        compressed.lines().map(str::trim).collect();
571    for line in raw.lines().map(str::trim) {
572        if line.starts_with("test result:") {
573            saw_result = true;
574            if !compressed_lines.contains(line) {
575                return false;
576            }
577        }
578    }
579    saw_result && compressed_lines.contains("failures:")
580}
581}
582
583// Libtest introduces stdout sections with a header, then repeats the header
584// before an indented name list and its verdict. A test can print the same word;
585// without that surrounding structure it remains ordinary captured output.
586fn failure_list_headers(lines: &[&str]) -> Vec<bool> {
587    lines
588        .iter()
589        .enumerate()
590        .map(|(index, line)| {
591            if line.trim() != "failures:" {
592                return false;
593            }
594            let mut saw_name = false;
595            for next in &lines[index + 1..] {
596                let trimmed = next.trim();
597                if trimmed.is_empty() {
598                    continue;
599                }
600                if !saw_name && trimmed.starts_with("---- ") && trimmed.ends_with(" stdout ----") {
601                    return true;
602                }
603                if next.starts_with(char::is_whitespace) && failure_name(trimmed, true).is_some() {
604                    saw_name = true;
605                    continue;
606                }
607                return saw_name && trimmed.starts_with("test result:");
608            }
609            false
610        })
611        .collect()
612}
613
614fn failure_name_counts(output: &str) -> std::collections::HashMap<&str, [usize; 3]> {
615    let lines: Vec<_> = output.lines().collect();
616    let headers = failure_list_headers(&lines);
617    let mut counts = std::collections::HashMap::<_, [usize; 3]>::new();
618    let mut in_list = false;
619    for (index, line) in lines.iter().enumerate() {
620        let trimmed = line.trim();
621        if headers[index] {
622            in_list = true;
623            continue;
624        }
625        if let Some(name) = failure_name(trimmed, in_list) {
626            let kind = failure_name_kind(trimmed);
627            if kind == 1 {
628                in_list = false;
629            }
630            counts.entry(name).or_default()[kind] += 1;
631        } else if !trimmed.is_empty() {
632            in_list = false;
633        }
634    }
635    counts
636}
637
638// Status, stdout header and final list are three views of each failure,
639// not three occurrences. The summary must list each reported occurrence.
640fn failure_name_kind(line: &str) -> usize {
641    if line.starts_with("test ") || is_nextest_verdict(line) {
642        0
643    } else if line.starts_with("---- ") {
644        1
645    } else {
646        2
647    }
648}
649
650fn append_cargo_test_total(
651    compressed: CompressionResult,
652    total: Option<&str>,
653) -> CompressionResult {
654    match total {
655        Some(total) => compressed.map_text(|text| insert_cargo_test_total(text, total)),
656        None => compressed,
657    }
658}
659
660fn insert_cargo_test_total(output: &str, total: &str) -> String {
661    let mut lines = output.lines().map(str::to_string).collect::<Vec<_>>();
662    let insert_at = lines
663        .iter()
664        .rposition(|line| line.trim_start().starts_with("test result:"))
665        .map_or(lines.len(), |index| index + 1);
666    lines.insert(insert_at, total.to_string());
667    lines.join("\n")
668}
669
670fn cargo_test_total_line(lines: &[&str]) -> Option<String> {
671    let mut passed = 0usize;
672    let mut failed = 0usize;
673    let mut ignored = 0usize;
674    let mut binaries = 0usize;
675    let mut unparsed_binaries = 0usize;
676
677    for line in lines {
678        if !line.trim_start().starts_with("test result:") {
679            continue;
680        }
681        binaries += 1;
682        let counts = ["passed", "failed", "ignored"].map(|label| {
683            line.split(';').find_map(|field| {
684                let mut words = field.split_whitespace().rev();
685                (words.next()? == label).then(|| words.next()?.parse::<usize>().ok())?
686            })
687        });
688        match counts {
689            [Some(binary_passed), Some(binary_failed), Some(binary_ignored)] => {
690                passed = passed.saturating_add(binary_passed);
691                failed = failed.saturating_add(binary_failed);
692                ignored = ignored.saturating_add(binary_ignored);
693            }
694            _ => unparsed_binaries += 1,
695        }
696    }
697
698    if binaries < 2 {
699        return None;
700    }
701
702    let mut total = format!(
703        "cargo test total: {passed} passed, {failed} failed, {ignored} ignored across {binaries} binaries"
704    );
705    let mut incomplete = Vec::new();
706    if lines
707        .iter()
708        .any(|line| line.trim_start().starts_with("error: could not compile"))
709    {
710        incomplete.push("one or more test binaries failed to compile".to_string());
711    }
712    let started_binaries = lines
713        .iter()
714        .filter(|line| {
715            let Some(rest) = line.trim_start().strip_prefix("running ") else {
716                return false;
717            };
718            let mut words = rest.split_whitespace();
719            words
720                .next()
721                .is_some_and(|count| count.parse::<usize>().is_ok())
722                && matches!(words.next(), Some("test" | "tests"))
723        })
724        .count();
725    let cut_off_binaries = started_binaries.saturating_sub(binaries);
726    if cut_off_binaries == 1 {
727        incomplete.push("1 test binary was cut off before reporting a result".to_string());
728    } else if cut_off_binaries > 1 {
729        incomplete.push(format!(
730            "{cut_off_binaries} test binaries were cut off before reporting a result"
731        ));
732    }
733    if unparsed_binaries == 1 {
734        incomplete.push("1 test result could not be parsed".to_string());
735    } else if unparsed_binaries > 1 {
736        incomplete.push(format!(
737            "{unparsed_binaries} test results could not be parsed"
738        ));
739    }
740    if !incomplete.is_empty() {
741        total.push_str(" (incomplete: ");
742        total.push_str(&incomplete.join("; "));
743        total.push(')');
744    }
745    Some(total)
746}
747
748fn trim_trailing_lines(input: &str) -> String {
749    input
750        .lines()
751        .map(str::trim_end)
752        .collect::<Vec<_>>()
753        .join("\n")
754}
755
756/// Lines a byte-capped bash reply must retain even when stderr follows the
757/// test results. Names and totals are never capped; priority protection covers
758/// the first twenty distinct panic locations so backtraces cannot consume the
759/// reply. Already bounded panic sections also retain their message lines.
760pub struct TestVerdict {
761    pub required: Vec<usize>,
762    pub empty_results: Vec<usize>,
763}
764
765pub fn test_verdict(lines: &[&str]) -> Option<TestVerdict> {
766    use std::collections::HashSet;
767
768    if !lines.iter().any(|line| {
769        is_cargo_test_signature_line(line.trim_start()) || is_nextest_verdict(line.trim_start())
770    }) {
771        return None;
772    }
773
774    let mut required = Vec::new();
775    let mut empty_results = Vec::new();
776    let mut names = std::collections::HashMap::<_, [usize; 3]>::new();
777    let mut locations = HashSet::new();
778    let failure_headers = failure_list_headers(lines);
779    let mut in_failure_list = false;
780    for (index, line) in lines.iter().enumerate() {
781        let trimmed = line.trim();
782        if failure_headers[index] {
783            in_failure_list = true;
784            continue;
785        }
786        let failure_name = failure_name(trimmed, in_failure_list);
787        if trimmed.starts_with("---- ") || (!trimmed.is_empty() && failure_name.is_none()) {
788            in_failure_list = false;
789        }
790        let is_name = failure_name.is_some_and(|name| {
791            let counts = names.entry(name).or_default();
792            let previous = *counts.iter().max().unwrap();
793            let kind = failure_name_kind(trimmed);
794            counts[kind] += 1;
795            counts[kind] > previous
796        });
797        let is_panic = (trimmed.starts_with("thread '") && trimmed.contains("panicked at"))
798            || (index > 0 && lines[index - 1].trim_end().ends_with("panicked at"));
799        let is_location = is_panic && locations.len() < 20 && locations.insert(trimmed);
800        if trimmed.starts_with(
801            "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;",
802        ) {
803            empty_results.push(index);
804        } else if is_name
805            || is_location
806            || trimmed.starts_with("test result:")
807            || trimmed.starts_with("cargo test total:")
808            || trimmed.starts_with("Summary [")
809            || trimmed.starts_with("error: test failed, to rerun")
810        {
811            required.push(index);
812        }
813    }
814    if let Some(bounded) = bounded_failure_verdict_lines(lines) {
815        required.extend(bounded);
816        required.sort_unstable();
817        required.dedup();
818    }
819    Some(TestVerdict {
820        required,
821        empty_results,
822    })
823}
824
825fn bounded_failure_verdict_lines(lines: &[&str]) -> Option<Vec<usize>> {
826    let mut required = Vec::new();
827    let mut in_section = false;
828    let mut in_list = false;
829    let mut section_lines = 0;
830    let mut detail_lines = 0;
831    let mut bytes = 0;
832    let failure_headers = failure_list_headers(lines);
833    for (index, line) in lines.iter().enumerate() {
834        let trimmed = line.trim();
835        if line.starts_with("---- ") && line.ends_with(" stdout ----") {
836            in_section = true;
837            in_list = false;
838            section_lines = 0;
839        } else if failure_headers[index] {
840            in_section = false;
841            in_list = true;
842        } else if trimmed.starts_with("test result:")
843            || trimmed.starts_with("cargo test total:")
844            || trimmed.starts_with("error: test failed, to rerun")
845        {
846            in_section = false;
847            in_list = false;
848        } else if in_list && !trimmed.is_empty() && failure_name(trimmed, true).is_none() {
849            in_list = false;
850        }
851        if trimmed.is_empty() {
852            continue;
853        }
854        if in_section {
855            section_lines += 1;
856            detail_lines += 1;
857            if section_lines > FAILURE_SECTION_LINES || detail_lines > FAILURE_DETAIL_LINES {
858                return None;
859            }
860        }
861        if in_section
862            || in_list
863            || trimmed.starts_with("test result:")
864            || trimmed.starts_with("cargo test total:")
865            || trimmed.starts_with("error: test failed, to rerun")
866        {
867            bytes += line.len() + 1;
868            if bytes > FAILURE_DETAIL_BYTES {
869                return None;
870            }
871            required.push(index);
872        }
873    }
874    (detail_lines > 0).then_some(required)
875}
876
877fn is_nextest_verdict(line: &str) -> bool {
878    ["FAIL [", "TIMEOUT [", "Summary ["]
879        .iter()
880        .any(|prefix| line.starts_with(prefix))
881}
882
883fn failure_name(line: &str, in_failure_list: bool) -> Option<&str> {
884    if let Some(name) = line
885        .strip_prefix("test ")
886        .and_then(|line| line.strip_suffix(" ... FAILED"))
887    {
888        return Some(name);
889    }
890    if let Some(name) = line
891        .strip_prefix("---- ")
892        .and_then(|line| line.strip_suffix(" stdout ----"))
893    {
894        return Some(name);
895    }
896    if line.starts_with("FAIL [") || line.starts_with("TIMEOUT [") {
897        return line.split_once(']').map(|(_, name)| name.trim());
898    }
899    // The second libtest `failures:` block lists bare names, one per line.
900    if in_failure_list && !line.is_empty() && !line.contains(char::is_whitespace) {
901        return Some(line);
902    }
903    None
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909    use crate::compress::caps::DropClass;
910    use crate::compress::{
911        builtin_filters, compress_with_registry_exit_code, toml_filter::build_registry,
912    };
913
914    const HOST_SUPERVISOR_FAILURES: &str = include_str!(
915        "../../../aft/tests/integration/fixtures/compress_filters/cargo-test/host-supervisor-two-failures.stdout"
916    );
917
918    #[test]
919    fn cargo_test_printed_failure_header_is_not_a_failure_list() {
920        let raw = format!("{}running 1 test\ntest tests::foo ... FAILED\n\nfailures:\n\n---- tests::foo stdout ----\nthread 'tests::foo' panicked at src/lib.rs:1:1:\nfailures:\nnot_a_test\n\nfailures:\n    tests::foo\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\nerror: test failed, to rerun pass `--lib`\n", "   Compiling fixture v0.1.0\n".repeat(80));
921        let registry = build_registry(builtin_filters::ALL, None, None);
922        let result = compress_with_registry_exit_code("cargo test", &raw, Some(101), &registry);
923        assert!(result.bounded_cargo_test_details);
924        assert!(
925            result.text.contains("failures:\nnot_a_test\n"),
926            "{}",
927            result.text
928        );
929        assert!(!result.text.lines().any(|line| line == "    not_a_test"));
930        assert_eq!(failure_name_counts(&raw).len(), 1);
931        assert_eq!(
932            failure_name_counts(&raw).get("tests::foo"),
933            Some(&[1, 1, 1])
934        );
935        assert_eq!(
936            failure_name_counts(&result.text).get("tests::foo"),
937            Some(&[0, 1, 1])
938        );
939        assert!(failure_summary_preserved(&raw, &result.text));
940    }
941
942    #[test]
943    fn cargo_test_reserves_final_line_before_spending_detail_budget() {
944        let final_line = format!("warning: final status {}", "x".repeat(1100));
945        let raw = format!("{HOST_SUPERVISOR_FAILURES}{final_line}\n");
946        let result = compress_test(&raw, Some(101));
947        assert_eq!(result.text.lines().last(), Some(final_line.as_str()));
948        assert!(
949            result.text.len() <= FAILURE_DETAIL_BYTES,
950            "{} bytes",
951            result.text.len()
952        );
953        assert!(failure_summary_preserved(&raw, &result.text));
954    }
955
956    #[test]
957    fn cargo_test_caps_failure_details_but_keeps_every_failure_name() {
958        let mut output = String::from("running 40 tests\n\nfailures:\n\n");
959        for index in 0..40 {
960            output.push_str(&format!(
961                "---- case_{index} stdout ----\nthread 'case_{index}' panicked at src/lib.rs:{index}:1\nstack line {index}\n\n"
962            ));
963        }
964        output.push_str("failures:\n");
965        for index in 0..40 {
966            output.push_str(&format!("    case_{index}\n"));
967        }
968        output.push_str(
969            "\ntest result: FAILED. 0 passed; 40 failed; 0 ignored; 0 measured; 0 filtered out\n",
970        );
971
972        let result = compress_test(&output, None);
973
974        assert!(
975            result
976                .dropped_by_class
977                .get(&DropClass::Failure)
978                .copied()
979                .unwrap_or(0)
980                > 0
981        );
982        let (details, names) = result.text.split_once("failures:\n").expect("failure list");
983        assert!(details.lines().count() <= FAILURE_DETAIL_LINES + 1);
984        assert!(result.text.len() <= FAILURE_DETAIL_BYTES);
985        assert!(details.contains("---- case_0 stdout ----"));
986        assert!(details.contains("stack line 0"));
987        assert!(!details.contains("---- case_39 stdout ----"));
988        for index in 0..40 {
989            assert!(names
990                .lines()
991                .any(|line| line == format!("    case_{index}")));
992        }
993        assert!(result.had_inner_drop);
994        assert!(!result.offset_hint_eligible);
995    }
996
997    #[test]
998    fn cargo_test_compile_error_preserves_diagnostic_with_unknown_exit() {
999        let output = r#"   Compiling demo v0.1.0 (/tmp/demo)
1000error[E0432]: unresolved import `crate::missing`
1001 --> src/lib.rs:1:5
1002  |
10031 | use crate::missing;
1004  |     ^^^^^^^^^^^^^^ no `missing` in the root
1005
1006error: could not compile `demo` (lib test) due to 1 previous error
1007"#;
1008
1009        let result = compress_test(output, None);
1010
1011        assert!(result.text.contains("error[E0432]"));
1012        assert!(result.text.contains("unresolved import"));
1013        assert!(result.text.contains("error: could not compile"));
1014    }
1015
1016    #[test]
1017    fn cargo_test_sums_results_even_when_output_is_wrapped() {
1018        let output = "runner: cargo test\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\nrunning 1 test\ntest result: FAILED. 1 passed; 1 failed; 2 ignored; 0 measured; 0 filtered out\n";
1019
1020        assert!(CargoCompressor.matches_output(output));
1021        let result = compress_test(output, Some(101));
1022
1023        assert!(result
1024            .text
1025            .contains("cargo test total: 3 passed, 1 failed, 3 ignored across 2 binaries"));
1026    }
1027
1028    #[test]
1029    fn cargo_test_total_marks_binaries_that_failed_to_compile() {
1030        let output = "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\nerror: could not compile `broken` (bin test) due to 1 previous error\n";
1031
1032        let result = compress_test(output, Some(101));
1033
1034        assert!(result
1035            .text
1036            .contains("cargo test total: 3 passed, 0 failed, 1 ignored across 2 binaries"));
1037        assert!(result
1038            .text
1039            .contains("incomplete: one or more test binaries failed to compile"));
1040    }
1041
1042    #[test]
1043    fn cargo_test_total_marks_binaries_without_a_result_as_incomplete() {
1044        let output = "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 1 test\n";
1045
1046        let result = compress_test(output, Some(0));
1047
1048        assert!(result
1049            .text
1050            .contains("cargo test total: 3 passed, 0 failed, 0 ignored across 2 binaries"));
1051        assert!(result
1052            .text
1053            .contains("incomplete: 1 test binary was cut off before reporting a result"));
1054    }
1055
1056    #[test]
1057    fn cargo_verdict_keeps_aggregate_total_for_byte_capped_replies() {
1058        let lines = [
1059            "running 1 test",
1060            "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out",
1061            "cargo test total: 1 passed, 0 failed, 0 ignored across 2 binaries",
1062        ];
1063        let verdict = test_verdict(&lines).expect("cargo test output has a verdict");
1064
1065        assert!(verdict.required.contains(&2));
1066    }
1067
1068    #[test]
1069    fn cargo_verdict_extractor_keeps_nonfinal_rerun_with_unknown_exit() {
1070        let output = format!("running 1 test\n\nfailures:\n\n---- case stdout ----\nthread 'case' panicked at src/lib.rs:1:1:\n\nfailures:\n    case\n\ntest result: FAILED. 0 passed; 1 failed\nerror: test failed, to rerun pass `--lib`\n{}wrapper finished\n", "wrapper progress\n".repeat(200));
1071        let result = compress_test(&output, None);
1072        assert!(result
1073            .text
1074            .contains("error: test failed, to rerun pass `--lib`"));
1075        assert!(result.text.ends_with("wrapper finished"));
1076    }
1077
1078    /// A gate script's output, verbatim: two verdicts from other tools, then
1079    /// four cargo test binaries.
1080    const GATE_SCRIPT_OUTPUT: &str = "fmt-ok\nwin-check rc=0\ntest result: ok. 803 passed; 0 failed; 19 ignored; 0 measured; 8977 filtered out; finished in 23.38s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.12s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.16s\ntest result: ok. 114 passed; 0 failed; 3 ignored; 0 measured; 2476 filtered out; finished in 11.74s\n";
1081
1082    #[test]
1083    fn cargo_test_summary_keeps_gate_script_verdicts_it_does_not_read() {
1084        let result = compress_test(GATE_SCRIPT_OUTPUT, Some(0));
1085
1086        assert_eq!(
1087            result.text,
1088            format!(
1089                "{}\ncargo test total: 919 passed, 0 failed, 22 ignored across 4 binaries",
1090                GATE_SCRIPT_OUTPUT.trim_end()
1091            )
1092        );
1093    }
1094
1095    #[test]
1096    fn cargo_test_summary_keeps_a_failed_verdict_it_does_not_read() {
1097        let output = GATE_SCRIPT_OUTPUT.replace("win-check rc=0", "win-check rc=101");
1098
1099        let result = compress_test(&output, Some(0));
1100
1101        assert!(
1102            result
1103                .text
1104                .starts_with("fmt-ok\nwin-check rc=101\ntest result: ok. 803 passed"),
1105            "{}",
1106            result.text
1107        );
1108    }
1109
1110    #[test]
1111    fn cargo_test_summary_drops_progress_but_keeps_printed_lines_in_order() {
1112        let output = "   Compiling demo v0.1.0 (/tmp/demo)\n    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.50s\n     Running unittests src/lib.rs (target/debug/deps/demo-0123)\n\nrunning 2 tests\ntest a ... ok\nfmt-ok\ntest b ... ok\nwin-check rc=101\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n";
1113
1114        let result = compress_test(output, Some(0));
1115
1116        assert_eq!(
1117            result.text,
1118            "    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.50s\nrunning 2 tests\nfmt-ok\nwin-check rc=101\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"
1119        );
1120    }
1121
1122    #[test]
1123    fn cargo_test_summary_drops_nextest_progress_but_keeps_its_failures() {
1124        let output = "running 1 test\ntest a ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n    Starting 3 tests across 1 binary\n        PASS [   0.004s] demo tests::a\n        SKIP [         ] demo tests::c\n        FAIL [   0.010s] demo tests::b\nPASS [lint] rc=0\n     Summary [   0.020s] 3 tests run: 1 passed, 1 failed, 1 skipped\n";
1125
1126        let result = compress_test(output, Some(0));
1127
1128        assert_eq!(
1129            result.text,
1130            "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n        FAIL [   0.010s] demo tests::b\nPASS [lint] rc=0\n     Summary [   0.020s] 3 tests run: 1 passed, 1 failed, 1 skipped"
1131        );
1132    }
1133
1134    #[test]
1135    fn cargo_test_failure_summary_keeps_lines_it_does_not_read() {
1136        let output = "fmt-ok\nwin-check rc=101\nrunning 2 tests\ntest a ... ok\ntest case ... FAILED\n\nfailures:\n\n---- case stdout ----\nthread 'case' panicked at src/lib.rs:1:1\n\nfailures:\n    case\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\nlint-check rc=0\n";
1137
1138        let result = compress_test(output, Some(101));
1139
1140        assert!(
1141            result
1142                .text
1143                .starts_with("fmt-ok\nwin-check rc=101\nrunning 2 tests\n"),
1144            "{}",
1145            result.text
1146        );
1147        assert!(
1148            result.text.contains("---- case stdout ----"),
1149            "{}",
1150            result.text
1151        );
1152        assert!(
1153            result.text.ends_with("\nlint-check rc=0"),
1154            "{}",
1155            result.text
1156        );
1157        assert!(!result.text.contains("test a ... ok"), "{}", result.text);
1158    }
1159
1160    /// One clippy-style warning carrying every continuation shape rustc and
1161    /// clippy print: locators, gutters, labels under carets and underlines,
1162    /// elided source, `= note:` text wrapped onto an aligned line, `= help:`,
1163    /// a suggestion diff and bare `help:`/`note:` sub-diagnostics. Every line
1164    /// names `w{index}`, so a test can tell whether the whole warning went.
1165    fn full_warning(index: usize) -> String {
1166        let line = index + 1;
1167        format!(
1168            "warning: mismatched value `w{index}`\n\
1169             \x20 --> src/lib.rs:{line}:9\n\
1170             \x20  | w{index}\n\
1171             {line} |     let w{index}: u32 = \"w{index}\";\n\
1172             \x20  |            ---   ^^^^^ expected `u32`, found `&str` for w{index}\n\
1173             \x20  |            |\n\
1174             \x20  |            expected due to this w{index}\n\
1175             ...\n\
1176             \x20  = note: expected type `u32` for w{index}\n\
1177             \x20             found reference `&'static str` for w{index}\n\
1178             \x20  = help: for further information visit https://example.invalid/w{index}\n\
1179             help: try a number for w{index}\n\
1180             \x20  |\n\
1181             {line} -     let w{index}: u32 = \"w{index}\";\n\
1182             {line} +     let w{index}: u32 = 1;\n\
1183             \x20  | w{index}\n\
1184             note: the lint level for w{index} is defined here\n\
1185             \x20 ::: src/main.rs:1:9 w{index}\n"
1186        )
1187    }
1188
1189    /// Eleven full warnings, one over the warning cap, with `separator` and an
1190    /// indented verdict from another tool after the eleventh.
1191    fn capped_warnings_then_indented_verdict(separator: &str) -> String {
1192        let mut output = String::from("    Checking demo v0.1.0 (/tmp/demo)\n");
1193        for index in 0..11 {
1194            if index > 0 {
1195                output.push('\n');
1196            }
1197            output.push_str(&full_warning(index));
1198        }
1199        output.push_str(separator);
1200        output.push_str("  win-check rc=101\n    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.50s\n");
1201        output
1202    }
1203
1204    #[test]
1205    fn build_like_diagnostic_block_owns_every_continuation_shape() {
1206        let output = capped_warnings_then_indented_verdict("\n");
1207
1208        let result = compress_build_like(&output);
1209
1210        assert_eq!(result.dropped_by_class.get(&DropClass::Warning), Some(&1));
1211        // The capped eleventh warning goes whole: none of its lines is left
1212        // behind as a separate line.
1213        assert!(!result.text.contains("w10"), "{}", result.text);
1214        // The kept warnings keep their whole bodies.
1215        for shape in [
1216            "  --> src/lib.rs:10:9",
1217            "10 |     let w9: u32 = \"w9\";",
1218            "expected due to this w9",
1219            "              found reference `&'static str` for w9",
1220            "   = help: for further information visit https://example.invalid/w9",
1221            "10 +     let w9: u32 = 1;",
1222            "  ::: src/main.rs:1:9 w9",
1223        ] {
1224            assert!(result.text.contains(shape), "{shape}: {}", result.text);
1225        }
1226    }
1227
1228    #[test]
1229    fn build_like_summaries_keep_an_indented_verdict_after_a_capped_warning() {
1230        for separator in ["", "\n"] {
1231            let output = capped_warnings_then_indented_verdict(separator);
1232            assert!(output.len() > SHORT_OUTPUT_BYTES);
1233            for command in ["cargo build", "cargo check", "cargo clippy"] {
1234                let result = CargoCompressor.compress_with_exit_code(command, &output, Some(0));
1235
1236                assert!(
1237                    result.text.contains("\n  win-check rc=101\n"),
1238                    "{command} {separator:?}: {}",
1239                    result.text
1240                );
1241                assert!(
1242                    !result.text.contains("w10"),
1243                    "{command} {separator:?}: {}",
1244                    result.text
1245                );
1246            }
1247        }
1248    }
1249
1250    #[test]
1251    fn cargo_test_summary_keeps_an_indented_verdict_after_a_warning() {
1252        for separator in ["", "\n"] {
1253            let output = format!(
1254                "{}{separator}  win-check rc=101\nrunning 1 test\ntest a ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n",
1255                full_warning(0)
1256            );
1257
1258            let result = compress_test(&output, Some(0));
1259
1260            assert_eq!(
1261                result.text,
1262                "  win-check rc=101\nrunning 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out",
1263                "{separator:?}"
1264            );
1265        }
1266    }
1267
1268    #[test]
1269    fn cargo_build_like_summaries_keep_lines_they_do_not_read() {
1270        // Eleven diagnostic warnings and cargo's own `generated 11 warnings`
1271        // line make twelve warning blocks, two over the cap of ten, so the
1272        // last two are dropped. The verdict printed between them belongs to
1273        // neither block and must stay.
1274        let mut output = String::from("fmt-ok\n    Checking demo v0.1.0 (/tmp/demo)\n");
1275        for index in 0..11 {
1276            output.push_str(&format!(
1277                "warning: unused variable: `x{index}`\n --> src/lib.rs:{line}:9\n  |\n{line} |     let x{index} = 1;\n  |         ^^ help: prefix it with an underscore\n  |\n  = note: `#[warn(unused_variables)]` on by default\n\n",
1278                line = index + 1
1279            ));
1280        }
1281        output.push_str("win-check rc=101\nwarning: `demo` (lib) generated 11 warnings\n    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.50s\n");
1282        assert!(output.len() > SHORT_OUTPUT_BYTES);
1283
1284        for command in ["cargo build", "cargo check", "cargo clippy"] {
1285            let result = CargoCompressor.compress_with_exit_code(command, &output, Some(0));
1286
1287            assert!(
1288                result.text.starts_with("fmt-ok\n"),
1289                "{command}: {}",
1290                result.text
1291            );
1292            assert!(
1293                result.text.contains("\nwin-check rc=101\n"),
1294                "{command}: {}",
1295                result.text
1296            );
1297            assert!(
1298                !result.text.contains("Checking demo"),
1299                "{command}: {}",
1300                result.text
1301            );
1302            assert!(
1303                result.text.contains("Finished `dev` profile"),
1304                "{command}: {}",
1305                result.text
1306            );
1307            assert_eq!(result.dropped_by_class.get(&DropClass::Warning), Some(&2));
1308        }
1309    }
1310
1311    #[test]
1312    fn cargo_test_compile_error_summary_keeps_lines_it_does_not_read() {
1313        let output = "fmt-ok\n   Compiling demo v0.1.0 (/tmp/demo)\nerror[E0432]: unresolved import `crate::missing`\n --> src/lib.rs:1:5\n  |\n1 | use crate::missing;\n  |     ^^^^^^^^^^^^^^ no `missing` in the root\n\nwin-check rc=101\nerror: could not compile `demo` (lib test) due to 1 previous error\n";
1314
1315        let result = compress_test(output, Some(101));
1316
1317        assert!(
1318            result.text.starts_with("fmt-ok\nerror[E0432]"),
1319            "{}",
1320            result.text
1321        );
1322        assert!(
1323            result
1324                .text
1325                .contains("no `missing` in the root\nwin-check rc=101\nerror: could not compile"),
1326            "{}",
1327            result.text
1328        );
1329    }
1330
1331    #[test]
1332    fn cargo_nextest_output_keeps_lines_it_does_not_read() {
1333        // `cargo nextest` has no extractor of its own and falls back to
1334        // generic dedup, which must not lose a mixed-in verdict either. Forty
1335        // tests put the fixture past the 1 KiB raw passthrough.
1336        let mut output =
1337            String::from("fmt-ok\nwin-check rc=101\n    Starting 40 tests across 1 binary\n");
1338        for index in 0..40 {
1339            output.push_str(&format!(
1340                "        PASS [   0.004s] demo tests::case_{index}\n"
1341            ));
1342        }
1343        output.push_str("     Summary [   0.010s] 40 tests run: 40 passed, 0 skipped\n");
1344        assert!(output.len() > SHORT_OUTPUT_BYTES);
1345
1346        let result = CargoCompressor.compress_with_exit_code("cargo nextest run", &output, Some(0));
1347
1348        assert_eq!(result.text, output);
1349    }
1350
1351    #[test]
1352    fn cargo_subcommand_returns_none_for_pipe_before_subcommand() {
1353        assert_eq!(cargo_subcommand("cargo --verbose | grep error"), None);
1354    }
1355
1356    #[test]
1357    fn cargo_subcommand_returns_subcommand_when_before_pipe() {
1358        assert_eq!(
1359            cargo_subcommand("cargo test | grep FAIL").as_deref(),
1360            Some("test")
1361        );
1362    }
1363
1364    #[test]
1365    fn cargo_subcommand_unaffected_without_metacharacters() {
1366        assert_eq!(
1367            cargo_subcommand("cargo test --release").as_deref(),
1368            Some("test")
1369        );
1370    }
1371}
1372
1373#[cfg(any(test, feature = "test-support"))]
1374mod audit_regressions {
1375    #[test]
1376    fn cargo_global_options_before_subcommand() {
1377        for command in [
1378            "cargo +nightly test",
1379            "cargo --locked test",
1380            "cargo -Z unstable-options test",
1381            "cargo --config k=v test",
1382            "cargo --config=k=v test",
1383            "cargo --color always test",
1384            "cargo -Zunstable-options test",
1385        ] {
1386            assert_eq!(
1387                super::cargo_subcommand(command).as_deref(),
1388                Some("test"),
1389                "{command}"
1390            );
1391        }
1392    }
1393}