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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! Integration tests for diff/patch coverage attribution against real git diffs.
//!
//! Each test builds a temporary git repository, commits a base and a head
//! revision, computes the `DiffModel` from `git2`, pairs it with a hand-built
//! per-line coverage report, and asserts the attribution. Covers the four
//! scenarios the feature must handle: a new file, a modified file with mixed
//! coverage, a line shift on otherwise-unchanged content, and a rename.

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::Result;
use git2::{Repository, Signature};
use tempfile::TempDir;

use patchcov::{analyze, CoverageReport, DiffModel, DiffScope, FileCoverage};

/// A temporary git repo whose commits each define the full file set (files
/// omitted from a commit are removed), so renames and deletions work.
struct TestRepo {
    _temp_dir: TempDir,
    repo_path: PathBuf,
    repo: Repository,
    commits: Vec<git2::Oid>,
}

impl TestRepo {
    fn new() -> Result<Self> {
        let tmp_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        fs::create_dir_all(&tmp_root)?;
        let temp_dir = tempfile::tempdir_in(&tmp_root)?;
        let repo_path = temp_dir.path().to_path_buf();
        let repo = Repository::init(&repo_path)?;
        let mut config = repo.config()?;
        config.set_str("user.name", "Test User")?;
        config.set_str("user.email", "test@example.com")?;
        Ok(Self {
            _temp_dir: temp_dir,
            repo_path,
            repo,
            commits: Vec::new(),
        })
    }

    /// Commits exactly `files` (path, content); any previously committed file
    /// not listed is removed in this commit.
    fn commit(&mut self, message: &str, files: &[(&str, &str)]) -> Result<git2::Oid> {
        // Materialise the working tree to match `files` exactly.
        let mut index = self.repo.index()?;
        index.clear()?;
        for (name, content) in files {
            let path = self.repo_path.join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&path, content)?;
            index.add_path(Path::new(name))?;
        }
        index.write()?;

        let signature = Signature::now("Test User", "test@example.com")?;
        let tree = self.repo.find_tree(index.write_tree()?)?;
        let parent = self.commits.last().map(|id| self.repo.find_commit(*id));
        let parent = match parent {
            Some(p) => Some(p?),
            None => None,
        };
        let parents: Vec<&git2::Commit> = parent.as_ref().into_iter().collect();
        let id = self.repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &parents,
        )?;
        self.commits.push(id);
        Ok(id)
    }

    fn base_sha(&self) -> String {
        self.commits[0].to_string()
    }

    fn diff(&self) -> Result<DiffModel> {
        DiffModel::between(&self.repo, &self.base_sha(), Some("HEAD"))
    }
}

/// Builds a coverage report from `(path, &[(line, hits)])` tuples.
fn cov(files: &[(&str, &[(u32, u64)])]) -> CoverageReport {
    let mut report = CoverageReport::new();
    for (path, lines) in files {
        let mut f = FileCoverage::new(*path);
        for &(n, h) in *lines {
            f.record(n, h);
        }
        report.insert(f);
    }
    report
}

#[test]
fn new_file_patch_coverage() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("a.rs", "fn a() {}\n")])?;
    repo.commit(
        "add b",
        &[("a.rs", "fn a() {}\n"), ("b.rs", "one\ntwo\nthree\n")],
    )?;

    let diff = repo.diff()?;
    let bdiff = diff.files.get("b.rs").expect("b.rs in diff");
    assert!(bdiff.is_new);
    assert_eq!(
        bdiff.added.iter().copied().collect::<Vec<_>>(),
        vec![1, 2, 3]
    );

    // Head report: line 1 & 3 covered, line 2 uncovered.
    let head = cov(&[("b.rs", &[(1, 1), (2, 0), (3, 4)])]);
    let result = analyze(&head, &diff, None, DiffScope::DiffOnly);
    assert_eq!(result.patch.covered, 2);
    assert_eq!(result.patch.uncovered, 1);
    assert_eq!(result.uncovered_new_lines, vec![("b.rs".to_string(), 2)]);
    Ok(())
}

#[test]
fn modified_file_mixed_coverage() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("m.rs", "a\nb\nc\n")])?;
    // Insert X, Y between b and c → new lines 3 and 4.
    repo.commit("modify", &[("m.rs", "a\nb\nX\nY\nc\n")])?;

    let diff = repo.diff()?;
    let mdiff = diff.files.get("m.rs").expect("m.rs in diff");
    assert!(!mdiff.is_new);
    assert_eq!(mdiff.added.iter().copied().collect::<Vec<_>>(), vec![3, 4]);

    // New line 3 covered, new line 4 uncovered.
    let head = cov(&[("m.rs", &[(1, 1), (2, 1), (3, 1), (4, 0), (5, 1)])]);
    let result = analyze(&head, &diff, None, DiffScope::DiffOnly);
    assert_eq!(result.patch.covered, 1);
    assert_eq!(result.patch.uncovered, 1);
    assert_eq!(result.uncovered_new_lines, vec![("m.rs".to_string(), 4)]);
    Ok(())
}

#[test]
fn line_shift_detects_indirect_change() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("s.rs", "l1\nl2\nl3\nl4\nl5\n")])?;
    // Insert two lines after l1: old l3 (line 3) shifts to new line 5.
    repo.commit("shift", &[("s.rs", "l1\nNEW1\nNEW2\nl2\nl3\nl4\nl5\n")])?;

    let diff = repo.diff()?;
    let sdiff = diff.files.get("s.rs").expect("s.rs in diff");
    // The two inserted lines are the added lines.
    assert_eq!(sdiff.added.iter().copied().collect::<Vec<_>>(), vec![2, 3]);
    // Unchanged content line l3 maps old line 3 → new line 5.
    assert_eq!(sdiff.map_base_to_head(3), Some(5));

    // Baseline: l3 covered. Head: same line (now line 5) uncovered.
    let baseline = cov(&[("s.rs", &[(3, 2)])]);
    let head = cov(&[("s.rs", &[(2, 1), (3, 1), (5, 0)])]);
    let result = analyze(&head, &diff, Some(&baseline), DiffScope::DiffOnly);

    assert_eq!(result.indirect.len(), 1, "expected one indirect flip");
    let change = &result.indirect[0];
    assert_eq!(change.path, "s.rs");
    assert_eq!(change.base_line, 3);
    assert_eq!(change.head_line, 5);
    assert!(!change.became_covered, "l3 lost coverage");
    Ok(())
}

#[test]
fn rename_does_not_show_false_lost_coverage() -> Result<()> {
    let mut repo = TestRepo::new()?;
    let body = "fn f() {\n    let a = 1;\n    let b = 2;\n    a + b\n}\n";
    repo.commit("base", &[("old.rs", body)])?;
    // Rename old.rs → new.rs with identical content.
    repo.commit("rename", &[("new.rs", body)])?;

    let diff = repo.diff()?;
    let rdiff = diff.files.get("new.rs").expect("new.rs in diff");
    assert!(rdiff.is_rename, "rename should be detected");
    assert_eq!(rdiff.old_path.as_deref(), Some("old.rs"));
    assert!(rdiff.added.is_empty(), "no lines added by a pure rename");

    // Same coverage before (old path) and after (new path) ⇒ no flips.
    let baseline = cov(&[("old.rs", &[(2, 1), (3, 1), (4, 1)])]);
    let head = cov(&[("new.rs", &[(2, 1), (3, 1), (4, 1)])]);
    let result = analyze(&head, &diff, Some(&baseline), DiffScope::DiffOnly);
    assert_eq!(result.patch.total(), 0, "a pure rename adds no lines");
    assert!(
        result.indirect.is_empty(),
        "identical content must not look like lost coverage"
    );
    Ok(())
}

/// Exercises real producer reports through the command's config and path pipeline.
fn producer_fixture(
    fixture: &str,
    git_path: &str,
    from: &str,
    to: &str,
    covered: u64,
    total: u64,
) -> Result<()> {
    use clap::Parser;
    use patchcov::cli::{Cli, Commands};

    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("base.txt", "base\n")])?;
    let source = "line\n".repeat(40);
    repo.commit("add source", &[("base.txt", "base\n"), (git_path, &source)])?;
    let config = repo.repo_path.join(".patchcov");
    fs::create_dir(&config)?;
    fs::write(config.join("config.yaml"), "{}\n")?;
    let report = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/non-rust")
        .join(fixture);
    let base = repo.base_sha();
    let command = Cli::try_parse_from([
        "patchcov",
        "diff",
        "--report",
        report.to_str().unwrap(),
        "--base-ref",
        &base,
        "--config-dir",
        config.to_str().unwrap(),
        "-o",
        "json",
    ])?;
    let Commands::Diff(mut cmd) = command.command else {
        unreachable!("parsed a diff command")
    };
    // Overall coverage can exist while a path mismatch leaves the patch empty,
    // which is an error unless the mismatch is explicitly allowed.
    assert!(cmd.run(Some(&repo.repo_path)).is_err(), "{fixture}");
    cmd.allow_path_mismatch = true;
    assert_eq!(
        cmd.run(Some(&repo.repo_path))?.patch_percent,
        None,
        "{fixture}"
    );
    cmd.allow_path_mismatch = false;
    fs::write(
        config.join("config.yaml"),
        format!("diff:\n  path-mappings:\n    - from: '{from}'\n      to: '{to}'\n"),
    )?;
    let result = cmd.run(Some(&repo.repo_path))?;
    assert_eq!(
        result.patch_percent,
        Some(covered as f64 / total as f64 * 100.0),
        "{fixture}"
    );
    let json: serde_json::Value = serde_json::from_str(&result.rendered)?;
    assert_eq!(json["patch_coverage"]["total"], total, "{fixture}");
    assert_eq!(json["patch_coverage"]["covered"], covered, "{fixture}");
    assert_eq!(
        json["patch_coverage"]["files"][0]["path"], git_path,
        "{fixture}"
    );
    Ok(())
}

#[test]
fn windows_runner_root_patch_attribution() -> Result<()> {
    producer_fixture("windows.lcov", "src/calc.cs", r"C:\agent\project", "", 1, 2)
}

#[test]
fn nyc_monorepo_patch_attribution() -> Result<()> {
    producer_fixture(
        "nyc.lcov",
        "packages/web/src/calc.js",
        "src",
        "packages/web/src",
        2,
        3,
    )
}

#[test]
fn coverage_py_source_root_patch_attribution() -> Result<()> {
    producer_fixture(
        "coverage-py.xml",
        "services/python/src/calc.py",
        "",
        "services/python",
        4,
        5,
    )
}

#[test]
fn gcovr_source_root_patch_attribution() -> Result<()> {
    producer_fixture("gcovr.xml", "native/example.cpp", "", "native", 6, 7)
}

#[test]
fn coverlet_source_root_patch_attribution() -> Result<()> {
    producer_fixture(
        "coverlet.xml",
        "src/dotnet/AbstractClass.cs",
        "",
        "src/dotnet",
        4,
        8,
    )
}

#[test]
fn dart_runner_root_patch_attribution() -> Result<()> {
    producer_fixture(
        "dart.lcov",
        "packages/mobile/lib/calc.dart",
        "/private/tmp/2188-producers/dart",
        "packages/mobile",
        1,
        2,
    )
}

#[test]
fn jacoco_source_root_mapping_attributes_patch() -> Result<()> {
    use patchcov::paths::PathMapping;
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("base.txt", "base\n")])?;
    repo.commit(
        "add java",
        &[(
            "services/api/src/main/java/com/example/App.java",
            "one\ntwo\n",
        )],
    )?;
    let mut head = patchcov::parse(
        r#"<report name="app"><package name="com/example"><sourcefile name="App.java"><line nr="1" mi="0" ci="2"/><line nr="2" mi="1" ci="0"/></sourcefile></package></report>"#,
        None,
    )?;
    head.map_paths(&[PathMapping {
        from: String::new(),
        to: "services/api/src/main/java".into(),
    }])?;
    let result = analyze(&head, &repo.diff()?, None, DiffScope::DiffOnly);
    assert_eq!(result.patch.covered, 1);
    assert_eq!(result.patch.uncovered, 1);
    assert_eq!(
        result.uncovered_new_lines,
        vec![("services/api/src/main/java/com/example/App.java".into(), 2)]
    );
    Ok(())
}

#[test]
fn unmeasured_presence_handles_renames_deletions_and_empty_entries() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit(
        "base",
        &[("old.rs", "one\ntwo\n"), ("deleted.rs", "gone\n")],
    )?;
    repo.commit(
        "head",
        &[
            ("new.rs", "one\ntwo\n"),
            ("README.md", "docs\n"),
            ("src/a.rs", "code\n"),
        ],
    )?;
    let diff = repo.diff()?;
    assert!(diff.files["deleted.rs"].is_deleted);
    assert!(diff.files["new.rs"].is_rename);
    let mut head = CoverageReport::new();
    head.files
        .insert("src/a.rs".into(), FileCoverage::new("src/a.rs"));
    let mut baseline = CoverageReport::new();
    baseline
        .files
        .insert("old.rs".into(), FileCoverage::new("old.rs"));
    let result = analyze(&head, &diff, Some(&baseline), DiffScope::DiffOnly);
    assert_eq!(result.unmeasured_files, ["README.md"]);
    let result = analyze(&head, &diff, None, DiffScope::All);
    assert_eq!(result.unmeasured_files, ["README.md", "new.rs"]);
    Ok(())
}

#[test]
fn ignored_old_rename_name_does_not_trigger_unmeasured_gate() -> Result<()> {
    use clap::Parser;
    use patchcov::cli::{Cli, Commands};
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("old.rs", "one\ntwo\n")])?;
    repo.commit("rename", &[("new.rs", "one\ntwo\n")])?;
    let report = repo.repo_path.join("head.lcov");
    fs::write(&report, "SF:old.rs\nDA:1,1\nend_of_record\n")?;
    let cli = Cli::try_parse_from([
        "patchcov",
        "diff",
        "--report",
        report.to_str().unwrap(),
        "--base-ref",
        &repo.base_sha(),
        "--fail-on-unmeasured",
        "**/*.rs",
        "--ignore-filename-regex",
        "^old\\.rs$",
        // The stale report names `old.rs`, which the rename left untracked.
        "--allow-path-mismatch",
        "--output",
        "json",
    ])?;
    let Commands::Diff(cmd) = cli.command else {
        panic!("expected diff command")
    };
    let outcome = cmd.run(Some(&repo.repo_path))?;
    assert!(outcome.unmeasured_failures.is_empty());
    let value: serde_json::Value = serde_json::from_str(&outcome.rendered)?;
    assert_eq!(value["unmeasured_files"], serde_json::json!([]));
    Ok(())
}

#[test]
fn foreign_runner_paths_fail_by_default_and_can_be_allowed() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("a.rs", "one\n")])?;
    repo.commit("head", &[("a.rs", "one\ntwo\nthree\nfour\nfive\n")])?;
    let report = repo.repo_path.join("foreign.lcov");
    fs::write(
        &report,
        "SF:/home/runner/work/proj/proj/a.rs\nDA:2,1\nDA:3,0\nDA:4,0\nDA:5,0\nend_of_record\n",
    )?;
    let run = |extra: &[&str]| {
        std::process::Command::new(env!("CARGO_BIN_EXE_patchcov"))
            .arg("-C")
            .arg(&repo.repo_path)
            .arg("diff")
            .arg("--report")
            .arg(&report)
            .arg("--base-ref")
            .arg(repo.base_sha())
            .args(["-o", "json"])
            .args(extra)
            .output()
            .unwrap()
    };
    // The default is an error, even with a gate, and the message names the way out.
    let output = run(&["--fail-under-patch", "80"]);
    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr)?;
    for text in [
        "none of its",
        "home/runner/work/proj/proj/a.rs",
        "--strip-prefix",
        "diff.path-mappings",
        "--allow-path-mismatch",
    ] {
        assert!(stderr.contains(text), "{stderr}");
    }
    // The opt-out restores the warning, and the run passes.
    let output = run(&["--allow-path-mismatch", "--fail-under-patch", "80"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr)?;
    for text in ["warning:", "foreign.lcov", "none of its"] {
        assert!(stderr.contains(text), "{stderr}");
    }
    // The deprecated flag is still accepted (it is now the default) but says so.
    let output = run(&["--fail-on-path-mismatch"]);
    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr)?;
    assert!(
        stderr.contains("--fail-on-path-mismatch is deprecated and has no effect"),
        "{stderr}"
    );
    assert!(stderr.contains("none of its"), "{stderr}");
    // Normalizing the paths fixes it without any opt-out.
    let output = run(&["--strip-prefix", "/home/runner/work/proj/proj"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stderr.is_empty());
    let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
    assert_eq!(json["patch_coverage"]["percent"], 25.0);
    assert_eq!(json["patch_coverage"]["covered"], 1);
    assert_eq!(json["patch_coverage"]["total"], 4);
    let config = repo.repo_path.join(".patchcov");
    fs::create_dir(&config)?;
    fs::write(
        config.join("config.yaml"),
        "diff:\n  path-mappings:\n    - from: /home/runner/work/proj/proj\n      to: ''\n",
    )?;
    let output = run(&[]);
    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    // The config opt-out alone downgrades the error to a warning.
    fs::write(
        config.join("config.yaml"),
        "diff:\n  allow-path-mismatch: true\n",
    )?;
    let output = run(&["--fail-under-patch", "80"]);
    assert!(output.status.success());
    assert!(String::from_utf8(output.stderr)?.contains("warning:"));
    Ok(())
}

#[test]
fn report_mixing_tracked_and_external_paths_passes_by_default() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.commit("base", &[("a.rs", "one\n")])?;
    repo.commit("head", &[("a.rs", "one\ntwo\nthree\n")])?;
    let report = repo.repo_path.join("mixed.lcov");
    fs::write(
        &report,
        "SF:a.rs\nDA:2,1\nDA:3,1\nend_of_record\nSF:/sdk/runtime/vendor.rs\nDA:1,0\nend_of_record\n",
    )?;
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_patchcov"))
        .arg("-C")
        .arg(&repo.repo_path)
        .arg("diff")
        .arg("--report")
        .arg(&report)
        .arg("--base-ref")
        .arg(repo.base_sha())
        .args(["--fail-under-patch", "100"])
        .output()?;
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stderr.is_empty());
    Ok(())
}

/// With no `--base-ref`, the real binary finds a base even when the repository's
/// default branch is `master`: the patch is what `HEAD` added past it.
#[test]
fn default_base_resolves_a_master_default_branch() -> Result<()> {
    let mut repo = TestRepo::new()?;
    // Commit on `work`, never the host's `init.defaultBranch`, so `master` is the
    // only default-branch candidate and it stays at the base.
    repo.repo.set_head("refs/heads/work")?;
    let base = repo.commit("base", &[("a.rs", "one\n")])?;
    repo.repo
        .reference("refs/heads/master", base, true, "default branch")?;
    repo.commit("head", &[("a.rs", "one\ntwo\nthree\n")])?;
    let report = repo.repo_path.join("head.lcov");
    fs::write(&report, "SF:a.rs\nDA:2,1\nDA:3,0\nend_of_record\n")?;
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_patchcov"))
        .arg("-C")
        .arg(&repo.repo_path)
        .args(["diff", "-o", "json", "--report"])
        .arg(&report)
        .output()?;
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
    assert_eq!(json["patch_coverage"]["covered"], 1);
    assert_eq!(json["patch_coverage"]["total"], 2);
    Ok(())
}