patchcov 0.4.1

Patch coverage for git diffs: attribute lcov, llvm-cov, Cobertura, Go and JaCoCo reports to a diff and gate on it.
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
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
//! The `patchcov` command line.

pub(crate) mod diff;
#[cfg(test)]
mod doc_fields;
pub mod exit;
pub(crate) mod lint_markers;
pub(crate) mod merge;
pub mod warn;

use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};

use self::exit::ErrorReport;

/// Environment variable that sets `--error-format`, when the flag is absent.
pub const ERROR_FORMAT_ENV: &str = "PATCHCOV_ERROR_FORMAT";

/// How a failure and the warnings are printed to stderr.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
pub enum ErrorFormat {
    /// `Error: <message>: <cause>...` and `warning: <message>` on one line each.
    #[default]
    Text,
    /// One line of JSON each, see `docs/reference.md#error-output` and
    /// `docs/reference.md#warnings`.
    Json,
}

/// Patch coverage for git diffs.
#[derive(Parser)]
#[command(name = "patchcov", version, about, long_about = None)]
pub struct Cli {
    /// The subcommand to execute.
    #[command(subcommand)]
    pub command: Commands,

    /// Run as if patchcov was started in `<PATH>` instead of the current
    /// working directory. Mirrors `git -C`.
    #[arg(long = "repo", short = 'C', global = true, value_name = "PATH")]
    pub repo: Option<PathBuf>,

    /// How a failure and the warnings are printed to stderr: `text` (an `Error:`
    /// or `warning:` line) or `json` (one machine-readable object per line).
    ///
    /// Without the flag, `PATCHCOV_ERROR_FORMAT` is used; see
    /// [`Cli::resolve_error_format`].
    #[arg(
        long = "error-format",
        global = true,
        value_enum,
        value_name = "FORMAT"
    )]
    pub error_format: Option<ErrorFormat>,
}

/// Subcommands.
#[derive(Subcommand)]
pub enum Commands {
    /// Analyses diff/patch coverage from a per-line report and a git diff.
    Diff(Box<diff::DiffCommand>),
    /// Checks source coverage markers without generating a coverage report.
    LintMarkers(lint_markers::LintMarkersCommand),
    /// Merges the per-shard reports of a sharded run into one lcov file.
    Merge(merge::MergeCommand),
}

impl Cli {
    /// Parses process arguments, including space-separated negative float
    /// thresholds that clap does not recognize as negative numbers.
    ///
    /// Unlike the derived `Parser::try_parse_from`, this accepts `-inf`, `-nan`
    /// and `-.5` as threshold values so the validator can explain their errors.
    pub fn try_parse_args(args: &[OsString]) -> std::result::Result<Self, clap::Error> {
        let mut normalized = Vec::with_capacity(args.len());
        let mut args = args.iter().peekable();
        // The executable name is never an option.
        normalized.extend(args.next().cloned());
        while let Some(arg) = args.next() {
            if arg == "--" {
                normalized.push(arg.clone());
                normalized.extend(args.cloned());
                break;
            }
            if matches!(
                arg.to_str(),
                Some("--fail-under-patch" | "--fail-under-lines")
            ) && args.peek().is_some_and(|value| {
                value
                    .to_str()
                    .is_some_and(|value| value.starts_with('-') && value.parse::<f64>().is_ok())
            }) {
                let mut joined = arg.clone();
                joined.push("=");
                if let Some(value) = args.next() {
                    joined.push(value);
                }
                normalized.push(joined);
            } else {
                normalized.push(arg.clone());
            }
        }
        Self::try_parse_from(normalized)
    }

    /// The format failures are printed in: the flag, else `env` (the value of
    /// [`ERROR_FORMAT_ENV`]), else text.
    ///
    /// An empty variable counts as unset. One that is neither `text` nor `json` is
    /// ignored with the returned warning rather than failing every command over a
    /// purely diagnostic setting.
    pub fn resolve_error_format(&self, env: Option<&OsStr>) -> (ErrorFormat, Option<String>) {
        if let Some(format) = self.error_format {
            return (format, None);
        }
        let Some(env) = env else {
            return (ErrorFormat::Text, None);
        };
        match env.to_str() {
            Some("" | "text") => (ErrorFormat::Text, None),
            Some("json") => (ErrorFormat::Json, None),
            _ => (
                ErrorFormat::Text,
                Some(format!(
                    "ignoring {ERROR_FORMAT_ENV}={}: expected 'text' or 'json'",
                    env.to_string_lossy()
                )),
            ),
        }
    }

    /// Executes the command.
    ///
    /// `-C/--repo` is resolved here (`None` = current working directory) and
    /// threaded explicitly to the leaf.
    pub fn execute(self) -> Result<()> {
        let repo: Option<&Path> = self.repo.as_deref();
        match self.command {
            Commands::Diff(cmd) => cmd.execute(repo),
            Commands::LintMarkers(cmd) => cmd.execute(repo),
            Commands::Merge(cmd) => cmd.execute(repo),
        }
    }
}

/// The JSON report for a failure of the argument parser, when JSON was asked for.
///
/// Parsing failed, so `--error-format` was never parsed: look for it in `args`
/// (the last occurrence wins, and `--` ends the options) and fall back to `env`,
/// the value of [`ERROR_FORMAT_ENV`]. `None` for `--help` and `--version`, which
/// are not failures, and when the text format is wanted.
pub fn usage_report(
    err: &clap::Error,
    args: &[OsString],
    env: Option<&OsString>,
) -> Option<ErrorReport> {
    if !err.use_stderr() || !json_requested(args, env) {
        return None;
    }
    // The error and its tips, without the usage block and the pointer to `--help`.
    let rendered = err.render().to_string();
    let end = ["\n\nUsage:", "\n\nFor more information"]
        .iter()
        .filter_map(|trailer| rendered.find(trailer))
        .min()
        .unwrap_or(rendered.len());
    let message = rendered[..end].trim();
    Some(ErrorReport::usage(
        message.strip_prefix("error: ").unwrap_or(message),
    ))
}

/// Whether `args` (or, without a flag, `env`) ask for `--error-format json`.
fn json_requested(args: &[OsString], env: Option<&OsString>) -> bool {
    let mut value = env.map(OsString::as_os_str);
    let mut args = args.iter().skip(1).map(OsString::as_os_str);
    while let Some(arg) = args.next() {
        let Some(arg) = arg.to_str() else { continue };
        if arg == "--" {
            break;
        }
        if let Some(inline) = arg.strip_prefix("--error-format=") {
            value = Some(inline.as_ref());
        } else if arg == "--error-format" {
            value = args.next().or(value);
        }
    }
    value == Some("json".as_ref())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    /// The CLI dispatches to `diff`; a missing report makes the
    /// leaf command error, which exercises the dispatch path end-to-end.
    #[test]
    fn dispatches_to_diff() {
        let cmd = Cli {
            command: Commands::Diff(Box::new(diff::DiffCommand {
                report: vec![std::path::PathBuf::from("/nonexistent/report.lcov")],
                report_format: diff::ReportFormat::Auto,
                branch_coverage: false,
                base_ref: Some("HEAD".to_string()),
                head_ref: None,
                baseline_report: None,
                baseline_report_format: diff::ReportFormat::Auto,
                output: diff::OutputFormatArg::Markdown,
                no_explanation: false,
                format: None,
                fail_under_patch: None,
                fail_on_unmeasured: Vec::new(),
                fail_under_lines: None,
                allow_path_mismatch: false,
                fail_on_path_mismatch: false,
                strip_prefix: None,
                ignore_filename_regex: Vec::new(),
                config_dir: None,
                collapse_ranges: false,
                all_files: false,
                artifact_url: None,
                run_url: None,
                base_sha: None,
                head_sha: None,
                commit_url: None,
            })),
            repo: None,
            error_format: None,
        };
        // Reaches the leaf command and fails on the missing report file.
        assert!(cmd.execute().is_err());
    }

    /// The same for `merge`: a missing shard fails the leaf, and the output is
    /// never created.
    #[test]
    fn dispatches_to_merge() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("merged.lcov");
        let cmd = Cli {
            command: Commands::Merge(merge::MergeCommand {
                report: vec![dir.path().join("missing.lcov")],
                report_format: diff::ReportFormat::Auto,
                output: output.clone(),
                strip_prefix: None,
            }),
            repo: None,
            error_format: None,
        };
        assert!(cmd.execute().is_err());
        assert!(!output.exists());
    }

    fn args(list: &[&str]) -> Vec<OsString> {
        std::iter::once("patchcov")
            .chain(list.iter().copied())
            .map(OsString::from)
            .collect()
    }

    #[test]
    fn negative_float_thresholds_have_explanations_in_both_spellings() {
        for flag in ["--fail-under-patch", "--fail-under-lines"] {
            for (value, reason) in [
                ("-inf", "must be a finite number"),
                ("-infinity", "must be a finite number"),
                ("-NaN", "must be a finite number"),
                ("-nan", "must be a finite number"),
                ("-1e999", "must be a finite number"),
                ("-.5", "must not be negative"),
                ("-5", "must not be negative"),
            ] {
                let joined = format!("{flag}={value}");
                for argv in [
                    args(&["diff", "--report", "r.lcov", flag, value]),
                    args(&["diff", "--report", "r.lcov", &joined]),
                ] {
                    let err = Cli::try_parse_args(&argv).err().unwrap();
                    assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
                    let message = err.to_string();
                    assert!(
                        message.contains(&format!("invalid value '{value}'")),
                        "{message}"
                    );
                    assert!(message.contains(flag), "{message}");
                    assert!(message.contains(reason), "{message}");
                }
            }
            for value in ["-0", "-.0", "-0e5"] {
                let cli = Cli::try_parse_args(&args(&["diff", "--report", "r.lcov", flag, value]))
                    .unwrap();
                let Commands::Diff(cmd) = cli.command else {
                    panic!("expected diff")
                };
                let got = if flag == "--fail-under-patch" {
                    cmd.fail_under_patch
                } else {
                    cmd.fail_under_lines
                };
                assert!(got.is_some_and(|v| v == 0.0 && v.is_sign_positive()));
            }
        }
    }

    #[test]
    fn normalization_preserves_missing_values_and_unrelated_arguments() {
        for flag in ["--fail-under-patch", "--fail-under-lines"] {
            for rest in [
                vec!["--fail-on-unmeasured", "src/**"],
                vec!["--head-ref", "main"],
                vec!["--no-explanation"],
                vec!["--fail-under-patch", "80"],
                vec!["--fail-under-lines", "80"],
                vec!["-o", "json"],
                vec![],
            ] {
                let mut argv = args(&["diff", "--report", "r.lcov", flag]);
                argv.extend(rest.into_iter().map(OsString::from));
                let message = Cli::try_parse_args(&argv).err().unwrap().to_string();
                assert!(
                    message.contains(&format!("a value is required for '{flag} <PCT>'")),
                    "{message}"
                );
            }
        }
        for argv in [
            args(&[
                "diff",
                "--report",
                "r.lcov",
                "--",
                "--fail-under-patch",
                "-inf",
            ]),
            args(&[
                "diff",
                "--report",
                "r.lcov",
                "--fail-under-patch",
                "--unknown",
            ]),
            args(&["merge", "--fail-under-patch", "-inf"]),
        ] {
            let expected = Cli::try_parse_from(&argv).err().unwrap();
            let got = Cli::try_parse_args(&argv).err().unwrap();
            assert_eq!(got.kind(), expected.kind());
        }
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStringExt;
            let report = OsString::from_vec(b"report-\xff.lcov".to_vec());
            let mut argv = args(&["diff", "--report"]);
            argv.push(report.clone());
            argv.extend([OsString::from("--fail-under-patch"), OsString::from("-.0")]);
            let cli = Cli::try_parse_args(&argv).unwrap();
            let Commands::Diff(cmd) = cli.command else {
                panic!("expected diff")
            };
            assert_eq!(cmd.report, vec![PathBuf::from(report)]);
        }
    }

    fn cli_with(error_format: Option<ErrorFormat>) -> Cli {
        Cli {
            command: Commands::Merge(merge::MergeCommand {
                report: Vec::new(),
                report_format: diff::ReportFormat::Auto,
                output: PathBuf::from("out.lcov"),
                strip_prefix: None,
            }),
            repo: None,
            error_format,
        }
    }

    #[test]
    fn the_flag_wins_over_the_environment_and_text_is_the_default() {
        let env = |value: &'static str| Some(OsStr::new(value));
        let resolve = |flag, value| cli_with(flag).resolve_error_format(value);
        assert_eq!(resolve(None, None), (ErrorFormat::Text, None));
        assert_eq!(resolve(None, env("json")), (ErrorFormat::Json, None));
        assert_eq!(resolve(None, env("text")), (ErrorFormat::Text, None));
        assert_eq!(resolve(None, env("")), (ErrorFormat::Text, None));
        let flag = Some(ErrorFormat::Text);
        assert_eq!(resolve(flag, env("json")), (ErrorFormat::Text, None));
        let flag = Some(ErrorFormat::Json);
        assert_eq!(resolve(flag, env("text")), (ErrorFormat::Json, None));
        // A bad variable is ignored with a warning, unless the flag makes it moot.
        let (format, warning) = resolve(None, env("xml"));
        assert_eq!(format, ErrorFormat::Text);
        assert!(warning.unwrap().contains("PATCHCOV_ERROR_FORMAT=xml"));
        assert_eq!(resolve(flag, env("xml")), (ErrorFormat::Json, None));
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            let (format, warning) = resolve(None, Some(OsStr::from_bytes(b"\xff")));
            assert_eq!(format, ErrorFormat::Text);
            assert!(warning.is_some());
        }
    }

    #[test]
    fn the_flag_parses_before_or_after_the_subcommand() {
        for argv in [
            ["--error-format", "json", "lint-markers"],
            ["lint-markers", "--error-format", "json"],
        ] {
            let cli = Cli::try_parse_from(std::iter::once("patchcov").chain(argv)).unwrap();
            assert_eq!(cli.error_format, Some(ErrorFormat::Json));
        }
        let cli = Cli::try_parse_from(["patchcov", "lint-markers"]).unwrap();
        assert_eq!(cli.error_format, None);
    }

    #[test]
    fn json_is_found_in_the_arguments_or_the_environment() {
        let json = OsString::from("json");
        let text = OsString::from("text");
        assert!(!json_requested(&args(&["diff"]), None));
        assert!(json_requested(&args(&["--error-format", "json"]), None));
        assert!(json_requested(
            &args(&["diff", "--error-format=json"]),
            None
        ));
        assert!(json_requested(&args(&["diff"]), Some(&json)));
        // The flag wins over the variable, and the last flag wins.
        assert!(!json_requested(
            &args(&["--error-format=text"]),
            Some(&json)
        ));
        assert!(json_requested(
            &args(&["--error-format=text", "--error-format", "json"]),
            None
        ));
        assert!(!json_requested(
            &args(&["--error-format=json", "--error-format=text"]),
            None
        ));
        assert!(!json_requested(&args(&["diff"]), Some(&text)));
        // A flag with no value falls back to the variable; `--` ends the options.
        assert!(json_requested(&args(&["--error-format"]), Some(&json)));
        assert!(!json_requested(&args(&["--", "--error-format=json"]), None));
    }

    #[test]
    fn a_parse_failure_is_reported_when_json_is_asked_for() {
        let argv = args(&["diff", "--error-format=json"]);
        let err = Cli::try_parse_from(&argv).err().unwrap();
        let report = usage_report(&err, &argv, None).unwrap();
        assert_eq!((report.code, report.kind), (2, "usage"));
        assert!(report.message.contains("--report"), "{}", report.message);
        assert!(!report.message.contains("Usage:"), "{}", report.message);
        assert!(!report.message.starts_with("error:"), "{}", report.message);
        assert!(report.chain.is_empty());
        // Not asked for: clap prints it.
        assert!(usage_report(&err, &args(&["diff"]), None).is_none());
    }

    /// clap's tips are part of the message; its usage block is not.
    #[test]
    fn a_parse_failure_keeps_clap_s_tips() {
        let argv = args(&["lint-marker", "--error-format=json"]);
        let err = Cli::try_parse_from(&argv).err().unwrap();
        let report = usage_report(&err, &argv, None).unwrap();
        assert!(
            report.message.contains("lint-markers"),
            "{}",
            report.message
        );
        assert!(report.message.contains("tip:"), "{}", report.message);
        assert!(!report.message.contains("Usage:"), "{}", report.message);
        assert!(!report.message.contains("--help"), "{}", report.message);
    }

    #[test]
    fn help_and_version_are_not_failures() {
        for flag in ["--help", "--version"] {
            let argv = args(&[flag, "--error-format=json"]);
            let err = Cli::try_parse_from(&argv).err().unwrap();
            assert!(usage_report(&err, &argv, None).is_none(), "{flag}");
        }
    }
}