cargo-feature-combinations 0.2.1

run cargo commands for all feature combinations
Documentation
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
//! Diagnostics-only output mode.
//!
//! When `--diagnostics-only` (or `--dedupe`) is active, cargo is invoked with
//! `--message-format=json-diagnostic-rendered-ansi` so that its stdout carries
//! one JSON object per line. This module parses those lines, filters for
//! compiler diagnostics, and prints only their rendered text — suppressing all
//! compilation-progress noise.

use std::collections::HashSet;
use std::io::{self, BufRead, Write};
use std::process;
use termcolor::StandardStream;

/// Cargo argument to request JSON diagnostics with embedded ANSI color codes.
pub(crate) const MESSAGE_FORMAT: &str = "--message-format=json-diagnostic-rendered-ansi";

/// A cargo JSON message emitted with `--message-format=json`.
///
/// Only the fields needed for diagnostics-only output are deserialized.
#[derive(serde::Deserialize)]
pub(crate) struct CargoMessage {
    pub reason: String,
    #[serde(default)]
    pub message: Option<Diagnostic>,
}

/// A rustc diagnostic embedded in a [`CargoMessage`].
#[derive(serde::Deserialize)]
pub(crate) struct Diagnostic {
    #[serde(default)]
    pub rendered: Option<String>,
    pub level: String,
}

/// Diagnostic counts returned by [`process_lines`].
struct DiagnosticCounts {
    warnings: usize,
    errors: usize,
    suppressed: usize,
}

/// Process a stream of cargo JSON lines, filtering for diagnostics.
///
/// This is the core logic shared by [`process_output`] and tests. It reads
/// lines from `reader`, writes filtered output to `writer`, and returns
/// diagnostic counts.
///
/// - `compiler-message` lines with level `"warning"` or `"error"` are counted
///   and their `rendered` text is written to `writer`.
/// - Non-JSON lines (e.g. test runner output) are passed through to `writer`.
/// - All other JSON messages (artifacts, build-finished) are silently skipped.
/// - When `dedupe` is true:
///   - Re-emissions of the same diagnostic within this invocation are folded
///     into the first copy: not counted, not written, and not tallied as
///     `suppressed`.
///   - Diagnostics already present in `seen` from an earlier invocation are
///     counted and tallied as `suppressed`, but not written.
///
/// `seen` is shared across feature-combination invocations. The per-run set
/// keeps duplicate cargo target emissions from inflating the per-combination
/// warning/error totals or the duplicate-diagnostic note.
fn process_lines(
    reader: impl BufRead,
    writer: &mut impl Write,
    dedupe: bool,
    seen: &mut HashSet<String>,
) -> DiagnosticCounts {
    let mut warnings: usize = 0;
    let mut errors: usize = 0;
    let mut suppressed: usize = 0;
    let mut seen_this_run: Option<HashSet<String>> = dedupe.then(HashSet::new);

    for line in reader.lines() {
        let Ok(line) = line else { break };
        match serde_json::from_str::<CargoMessage>(&line) {
            Ok(msg) if msg.reason == "compiler-message" => {
                let Some(diag) = msg.message else { continue };

                if let (Some(seen_this_run), Some(rendered)) =
                    (seen_this_run.as_mut(), diag.rendered.as_ref())
                    && !seen_this_run.insert(rendered.clone())
                {
                    continue;
                }

                match diag.level.as_str() {
                    "warning" => warnings += 1,
                    "error" => errors += 1,
                    _ => {}
                }

                if let Some(ref rendered) = diag.rendered {
                    if dedupe && !seen.insert(rendered.clone()) {
                        suppressed += 1;
                    } else {
                        let _ = writer.write_all(rendered.as_bytes());
                    }
                }
            }
            Ok(_) => {
                // Skip non-diagnostic JSON (artifacts, build-finished, etc.)
            }
            Err(_) => {
                // Non-JSON line (e.g. test runner output) -- pass through
                let _ = writeln!(writer, "{line}");
            }
        }
    }

    DiagnosticCounts {
        warnings,
        errors,
        suppressed,
    }
}

/// Process cargo's JSON stdout in diagnostics-only mode.
///
/// Reads JSON lines from the child's stdout, prints rendered diagnostics, and
/// drains stderr in a background thread to prevent pipe deadlocks.
///
/// When `dedupe` is `true`, diagnostics are deduplicated by exact rendered
/// text. Duplicate target emissions within this cargo invocation are folded,
/// while diagnostics already present in `seen` from earlier invocations are
/// counted as suppressed but not printed.
pub(crate) fn process_output(
    child: &mut process::Child,
    summary_only: bool,
    dedupe: bool,
    seen: &mut HashSet<String>,
    stdout: &mut StandardStream,
) -> io::Result<crate::runner::ProcessResult> {
    let mut output_buf = Vec::<u8>::new();
    let proc_stderr = child.stderr.take();
    let proc_stdout = child.stdout.take();

    let mut counts = DiagnosticCounts {
        warnings: 0,
        errors: 0,
        suppressed: 0,
    };

    std::thread::scope(|scope| {
        // Drain stderr in background to prevent deadlock.
        // Capture it in case we need to dump on cargo-level failure.
        let stderr_handle = scope.spawn(move || -> io::Result<Vec<u8>> {
            let mut stderr_buf = Vec::new();
            if let Some(stderr) = proc_stderr {
                io::copy(
                    &mut io::BufReader::new(stderr),
                    &mut io::Cursor::new(&mut stderr_buf),
                )?;
            }
            Ok(stderr_buf)
        });

        // Process stdout JSON lines on the main thread.
        if let Some(proc_stdout) = proc_stdout {
            let reader = io::BufReader::new(proc_stdout);
            if summary_only {
                // Buffer everything for potential --fail-fast dump.
                counts = process_lines(reader, &mut output_buf, dedupe, seen);
            } else {
                // Stream diagnostics directly to the terminal.
                counts = process_lines(reader, stdout, dedupe, seen);
                let _ = stdout.flush();
            }
        }

        // Join stderr thread and check for cargo-level failures.
        // If cargo itself failed (e.g. bad Cargo.toml syntax) without emitting
        // any JSON diagnostics, forward the stderr so the user sees the error.
        if let Ok(Ok(stderr_buf)) = stderr_handle.join()
            && counts.errors == 0
            && !stderr_buf.is_empty()
        {
            output_buf.extend(&stderr_buf);
        }

        io::Result::Ok(())
    })?;

    Ok(crate::runner::ProcessResult {
        num_warnings: counts.warnings,
        num_errors: counts.errors,
        num_suppressed: counts.suppressed,
        output: output_buf,
    })
}

#[cfg(test)]
mod test {
    use super::{DiagnosticCounts, process_lines};
    use indoc::indoc;
    use similar_asserts::assert_eq as sim_assert_eq;
    use std::collections::HashSet;

    /// Build a single JSON line for a `compiler-message` with the given level and rendered text.
    #[allow(
        clippy::expect_used,
        reason = "test helper — serialization of a static shape cannot fail"
    )]
    fn diag_json(level: &str, rendered: &str) -> String {
        serde_json::to_string(&serde_json::json!({
            "reason": "compiler-message",
            "message": {
                "rendered": rendered,
                "level": level,
            }
        }))
        .expect("serializing diagnostic JSON")
    }

    /// Build a single JSON line for a non-diagnostic cargo message.
    #[allow(
        clippy::expect_used,
        reason = "test helper — serialization of a static shape cannot fail"
    )]
    fn artifact_json() -> String {
        serde_json::to_string(&serde_json::json!({
            "reason": "compiler-artifact",
            "package_id": "foo",
            "target": { "kind": ["lib"], "name": "foo" }
        }))
        .expect("serializing artifact JSON")
    }

    /// Helper: run `process_lines` on a string and return the counts + written output.
    fn run_lines(
        input: &str,
        dedupe: bool,
        seen: &mut HashSet<String>,
    ) -> (DiagnosticCounts, String) {
        let reader = std::io::BufReader::new(input.as_bytes());
        let mut writer = Vec::new();
        let counts = process_lines(reader, &mut writer, dedupe, seen);
        let written = String::from_utf8(writer).unwrap_or_default();
        (counts, written)
    }

    #[test]
    fn counts_warnings_and_errors() {
        let input = include_str!("../test-data/diagnostics_only_json_output.txt");
        let mut seen = HashSet::new();
        let (counts, _) = run_lines(input, false, &mut seen);
        sim_assert_eq!(counts.warnings, 2);
        sim_assert_eq!(counts.errors, 1);
        sim_assert_eq!(counts.suppressed, 0);
    }

    #[test]
    fn rendered_diagnostics_are_written() {
        let input = include_str!("../test-data/diagnostics_only_json_output.txt");
        let mut seen = HashSet::new();
        let (_, written) = run_lines(input, false, &mut seen);
        assert!(written.contains("unused variable"));
        assert!(written.contains("unused import"));
        assert!(written.contains("cannot find value"));
    }

    #[test]
    fn non_diagnostic_json_is_skipped() {
        let input = include_str!("../test-data/diagnostics_only_json_output.txt");
        let mut seen = HashSet::new();
        let (_, written) = run_lines(input, false, &mut seen);
        assert!(!written.contains("compiler-artifact"));
        assert!(!written.contains("build-finished"));
    }

    #[test]
    fn non_json_lines_are_passed_through() {
        let input = indoc! {"
            running 5 tests
            test foo::bar ... ok
            test result: ok
        "};
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(input, false, &mut seen);
        assert!(written.contains("running 5 tests"));
        assert!(written.contains("test foo::bar ... ok"));
        assert!(written.contains("test result: ok"));
        sim_assert_eq!(counts.warnings, 0);
        sim_assert_eq!(counts.errors, 0);
    }

    #[test]
    fn mixed_json_and_non_json_lines() {
        let input = format!(
            "{}\nrunning 1 test\n{}\ntest bar ... ok\n",
            diag_json("warning", "warning: foo\n"),
            artifact_json(),
        );
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(&input, false, &mut seen);
        sim_assert_eq!(counts.warnings, 1);
        assert!(written.contains("warning: foo"));
        assert!(written.contains("running 1 test"));
        assert!(written.contains("test bar ... ok"));
        assert!(!written.contains("compiler-artifact"));
    }

    #[test]
    fn duplicate_rendered_text_is_preserved_without_dedupe() {
        let line = diag_json("warning", "warning: duplicate\n");
        let input = format!("{line}\n{line}\n");
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(&input, false, &mut seen);
        sim_assert_eq!(counts.warnings, 2);
        sim_assert_eq!(counts.suppressed, 0);
        sim_assert_eq!(written.matches("warning: duplicate").count(), 2);
    }

    #[test]
    fn dedupe_folds_duplicate_rendered_text_within_one_invocation() {
        // Cargo may emit the same lint once per compiled target in a single
        // invocation. Count and print only one copy; the rest are cargo target
        // fan-out, not additional user diagnostics.
        let line = diag_json("warning", "warning: duplicate\n");
        let input = format!("{line}\n{line}\n{line}\n");
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(&input, true, &mut seen);
        sim_assert_eq!(counts.warnings, 1);
        sim_assert_eq!(counts.suppressed, 0);
        sim_assert_eq!(written.matches("warning: duplicate").count(), 1);
    }

    #[test]
    fn repeated_two_target_diagnostic_reports_zero_then_one_suppressed() {
        // Regression test for --all-targets-style output: a lint emitted twice
        // in each invocation reports no suppressed diagnostics on the first
        // feature combination and one on later combinations.
        let line = diag_json("error", "error: too many lines\n");
        let one_invocation = format!("{line}\n{line}\n");
        let mut seen = HashSet::new();

        let (c1, o1) = run_lines(&one_invocation, true, &mut seen);
        sim_assert_eq!(c1.errors, 1);
        sim_assert_eq!(c1.suppressed, 0);
        sim_assert_eq!(o1.matches("too many lines").count(), 1);

        let (c2, o2) = run_lines(&one_invocation, true, &mut seen);
        sim_assert_eq!(c2.errors, 1);
        sim_assert_eq!(c2.suppressed, 1);
        assert!(!o2.contains("too many lines"));
    }

    #[test]
    fn dedupe_preserves_distinct_diagnostics() {
        let input = format!(
            "{}\n{}\n",
            diag_json("warning", "warning: first\n"),
            diag_json("warning", "warning: second\n"),
        );
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(&input, true, &mut seen);
        sim_assert_eq!(counts.warnings, 2);
        sim_assert_eq!(counts.suppressed, 0);
        assert!(written.contains("warning: first"));
        assert!(written.contains("warning: second"));
    }

    #[test]
    fn dedupe_works_across_multiple_calls() {
        let input = diag_json("warning", "warning: shared\n");
        let mut seen = HashSet::new();

        // First "feature combination"
        let (c1, o1) = run_lines(&input, true, &mut seen);
        sim_assert_eq!(c1.warnings, 1);
        sim_assert_eq!(c1.suppressed, 0);
        assert!(o1.contains("warning: shared"));

        // Second "feature combination" — same diagnostic is suppressed
        let (c2, o2) = run_lines(&input, true, &mut seen);
        sim_assert_eq!(c2.warnings, 1);
        sim_assert_eq!(c2.suppressed, 1);
        assert!(!o2.contains("warning: shared"));
    }

    #[test]
    fn empty_input_produces_zero_counts() {
        let mut seen = HashSet::new();
        let (counts, written) = run_lines("", false, &mut seen);
        sim_assert_eq!(counts.warnings, 0);
        sim_assert_eq!(counts.errors, 0);
        sim_assert_eq!(counts.suppressed, 0);
        assert!(written.is_empty());
    }

    #[test]
    fn cargo_level_error_lines_are_not_silently_swallowed() {
        let input = indoc! {r"
            error: failed to parse manifest at `/tmp/foo/Cargo.toml`

            Caused by:
              duplicate key `dependencies` in table `package`
        "};
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(input, false, &mut seen);
        sim_assert_eq!(counts.warnings, 0);
        sim_assert_eq!(counts.errors, 0);
        assert!(written.contains("failed to parse manifest"));
        assert!(written.contains("duplicate key"));
    }

    #[test]
    fn rendered_text_with_special_characters_survives_roundtrip() {
        let rendered = indoc! {"
            error[E0308]: mismatched types
             --> src/lib.rs:1:1
              |
            1 | fn foo() -> &'static str { 42 }
              |              expected `&str`, found `i32`

        "};
        let input = diag_json("error", rendered);
        let mut seen = HashSet::new();
        let (counts, written) = run_lines(&input, false, &mut seen);
        sim_assert_eq!(counts.errors, 1);
        assert!(written.contains("mismatched types"));
        assert!(written.contains("expected `&str`, found `i32`"));
    }
}