patchcov 0.4.0

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
//! The per-line coverage model that every parser produces.
//!
//! A [`CoverageReport`] is a map of repo-relative file paths to their
//! [`FileCoverage`], where each file records the hit count of every
//! *executable* line. Non-executable lines (blank, comment, declaration-only)
//! are simply absent — [`CoverageReport::hits`] returns `None` for them, which
//! callers use to exclude them from coverage denominators.

use std::collections::BTreeMap;
use std::path::Path;

/// Per-line hit counts for a single source file.
///
/// Only executable lines are present in `lines`; a line absent from the map is
/// not instrumented (blank, comment, etc.) and must not be counted towards
/// coverage totals.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileCoverage {
    /// Repo-relative path of the source file.
    pub path: String,
    /// Map of 1-based line number to hit count.
    pub lines: BTreeMap<u32, u64>,
    /// Opt-in lcov branch outcomes, keyed by line, block and branch identity.
    pub branches: BTreeMap<(u32, String, String), bool>,
    /// Opt-in Cobertura missed counts; aggregate counts cannot identify branches.
    pub missed_branches: BTreeMap<u32, u64>,
}

impl FileCoverage {
    /// Creates an empty file coverage for `path`.
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            lines: BTreeMap::new(),
            branches: BTreeMap::new(),
            missed_branches: BTreeMap::new(),
        }
    }

    /// Records `hits` for `line`. Repeated records for the same line take the
    /// maximum, so a line covered by any region counts as covered.
    pub fn record(&mut self, line: u32, hits: u64) {
        self.lines
            .entry(line)
            .and_modify(|h| *h = (*h).max(hits))
            .or_insert(hits);
    }

    /// Merges line hits and branch evidence without scoring until all shards arrive.
    fn merge(&mut self, other: Self) {
        for (line, hits) in other.lines {
            self.record(line, hits);
        }
        for (key, covered) in other.branches {
            self.branches
                .entry(key)
                .and_modify(|v| *v |= covered)
                .or_insert(covered);
        }
        for (line, missed) in other.missed_branches {
            self.missed_branches
                .entry(line)
                .and_modify(|v| *v = (*v).max(missed))
                .or_insert(missed);
        }
    }

    /// Number of executable lines.
    pub fn total_lines(&self) -> u64 {
        self.lines.len() as u64
    }

    /// Number of executable lines hit at least once.
    pub fn covered_lines(&self) -> u64 {
        self.lines.values().filter(|&&h| h > 0).count() as u64
    }

    /// Line coverage percentage, or `None` when the file has no executable lines.
    pub fn percent(&self) -> Option<f64> {
        let total = self.total_lines();
        if total == 0 {
            None
        } else {
            Some(self.covered_lines() as f64 / total as f64 * 100.0)
        }
    }
}

/// A whole coverage report: repo-relative file path → [`FileCoverage`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CoverageReport {
    /// Per-file coverage, keyed by repo-relative path.
    pub files: BTreeMap<String, FileCoverage>,
}

impl CoverageReport {
    /// Creates an empty report.
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts or merges a file's coverage into the report.
    ///
    /// If the path already exists, line hit counts are merged (taking the max
    /// per line), which keeps the model robust against reports that split one
    /// file across multiple records.
    pub fn insert(&mut self, file: FileCoverage) {
        match self.files.get_mut(&file.path) {
            Some(existing) => {
                existing.merge(file);
            }
            None => {
                self.files.insert(file.path.clone(), file);
            }
        }
    }

    /// Merges `other` into this report: the files are unioned and a line present
    /// in both takes the larger hit count.
    ///
    /// This is the rule for combining the reports of a sharded coverage run. It
    /// is a union, so a line only one report instrumented keeps that report's
    /// count rather than being scored against the other. Hit counts are maxed,
    /// not summed: coverage is a covered-or-not question and nothing in the
    /// line-coverage output reads the count itself.
    pub fn merge(&mut self, other: Self) {
        for file in other.files.into_values() {
            self.insert(file);
        }
    }

    /// Hit count for `path`:`line`, or `None` when the line is not instrumented
    /// (or the file is absent from the report).
    pub fn hits(&self, path: &str, line: u32) -> Option<u64> {
        self.files
            .get(path)
            .and_then(|f| f.lines.get(&line).copied())
    }

    /// Scores any executable line with missed branches as uncovered.
    /// Call only after merging shards; applying this before merging loses outcomes.
    pub fn apply_branch_coverage(&mut self) {
        for file in self.files.values_mut() {
            for (&(line, _, _), &covered) in &file.branches {
                if !covered {
                    if let Some(hits) = file.lines.get_mut(&line) {
                        *hits = 0;
                    }
                }
            }
            for (&line, &missed) in &file.missed_branches {
                if missed > 0 {
                    if let Some(hits) = file.lines.get_mut(&line) {
                        *hits = 0;
                    }
                }
            }
        }
    }

    /// Total executable lines across all files.
    pub fn total_lines(&self) -> u64 {
        self.files.values().map(FileCoverage::total_lines).sum()
    }

    /// Total covered lines across all files.
    pub fn covered_lines(&self) -> u64 {
        self.files.values().map(FileCoverage::covered_lines).sum()
    }

    /// Project-wide line coverage percentage, or `None` when there are no
    /// executable lines.
    pub fn percent(&self) -> Option<f64> {
        let total = self.total_lines();
        if total == 0 {
            None
        } else {
            Some(self.covered_lines() as f64 / total as f64 * 100.0)
        }
    }

    /// Normalises every file path to be repo-relative.
    ///
    /// Coverage tools usually emit absolute paths (lcov `SF:`, llvm-cov
    /// `filename`). Stripping `prefix` mirrors the CI `jq ltrimstr($ws)` step so
    /// the paths line up with the repo-relative paths git diffs report. Paths
    /// that do not start with `prefix` are left unchanged (already relative, or
    /// outside the tree). Leading `./` and `/` are also trimmed.
    pub fn strip_prefix(&mut self, prefix: &Path) {
        let prefix_str = prefix.to_string_lossy();
        let prefix_slash = format!("{}/", prefix_str.trim_end_matches('/'));
        let mut remapped: BTreeMap<String, FileCoverage> = BTreeMap::new();
        for (_, mut file) in std::mem::take(&mut self.files) {
            let normalized = normalize_path(&file.path, &prefix_slash);
            file.path.clone_from(&normalized);
            // Merge in case two source paths normalise to the same repo path.
            match remapped.get_mut(&normalized) {
                Some(existing) => {
                    existing.merge(file);
                }
                None => {
                    remapped.insert(normalized, file);
                }
            }
        }
        self.files = remapped;
    }

    /// Drops every file whose path does not satisfy `keep`.
    ///
    /// Used to apply `--ignore-filename-regex`: because it is called *after*
    /// [`strip_prefix`](Self::strip_prefix), the predicate sees repo-relative
    /// paths — the same space git diffs report in — so head and baseline
    /// reports are filtered identically before any delta is computed.
    ///
    /// Returns the files that were dropped, so the caller can report what the
    /// filter removed rather than leave a reader to infer it from a smaller total.
    pub fn retain_paths<F>(&mut self, keep: F) -> Vec<FileCoverage>
    where
        F: Fn(&str) -> bool,
    {
        let (kept, dropped): (BTreeMap<_, _>, BTreeMap<_, _>) = std::mem::take(&mut self.files)
            .into_iter()
            .partition(|(path, _)| keep(path));
        self.files = kept;
        dropped.into_values().collect()
    }

    /// Drops every line for which `keep` returns `false`, then drops any file
    /// left with no executable lines.
    ///
    /// The line-level twin of [`retain_paths`](Self::retain_paths), used to
    /// apply `ignore` source markers. Like the path filter it runs *after*
    /// [`strip_prefix`](Self::strip_prefix), so the predicate sees repo-relative
    /// paths, and it is applied to head and baseline independently — each from
    /// its own revision's source, since a region moves between revisions.
    ///
    /// Emptied files are removed rather than kept at zero lines: a
    /// [`FileCoverage`] with no lines has `percent() == None`, which
    /// `FileDelta::delta` reads as a fall to zero — so a fully-ignored file
    /// would render as a *total loss of coverage*, the exact opposite of what
    /// ignoring it means.
    pub fn retain_lines<F>(&mut self, keep: F)
    where
        F: Fn(&str, u32) -> bool,
    {
        for (path, file) in &mut self.files {
            file.lines.retain(|&line, _| keep(path, line));
            file.branches
                .retain(|(line, _, _), _| file.lines.contains_key(line));
            file.missed_branches
                .retain(|line, _| file.lines.contains_key(line));
        }
        self.files.retain(|_, file| file.total_lines() > 0);
    }
}

/// Strips `prefix_slash` (a trailing-slash directory prefix) from `path`, then
/// trims any leading `./` or `/`.
fn normalize_path(path: &str, prefix_slash: &str) -> String {
    let stripped = path.strip_prefix(prefix_slash).unwrap_or(path);
    stripped
        .trim_start_matches("./")
        .trim_start_matches('/')
        .to_string()
}

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

    #[test]
    fn record_takes_max_hits() {
        let mut f = FileCoverage::new("src/a.rs");
        f.record(1, 0);
        f.record(1, 3);
        f.record(1, 1);
        assert_eq!(f.lines.get(&1), Some(&3));
    }

    #[test]
    fn percent_counts_only_executable_lines() {
        let mut f = FileCoverage::new("src/a.rs");
        f.record(1, 1);
        f.record(2, 0);
        f.record(3, 5);
        // 2 of 3 executable lines covered.
        assert_eq!(f.total_lines(), 3);
        assert_eq!(f.covered_lines(), 2);
        assert!((f.percent().unwrap() - 66.666_666).abs() < 1e-3);
    }

    #[test]
    fn empty_file_has_no_percent() {
        let f = FileCoverage::new("src/empty.rs");
        assert_eq!(f.percent(), None);
    }

    #[test]
    fn hits_distinguishes_uncovered_from_non_executable() {
        let mut report = CoverageReport::new();
        let mut f = FileCoverage::new("src/a.rs");
        f.record(10, 0); // executable but uncovered
        report.insert(f);
        assert_eq!(report.hits("src/a.rs", 10), Some(0)); // uncovered
        assert_eq!(report.hits("src/a.rs", 11), None); // not instrumented
        assert_eq!(report.hits("src/missing.rs", 1), None);
    }

    #[test]
    fn insert_merges_duplicate_paths() {
        let mut report = CoverageReport::new();
        let mut a = FileCoverage::new("src/a.rs");
        a.record(1, 0);
        let mut b = FileCoverage::new("src/a.rs");
        b.record(1, 2);
        b.record(2, 1);
        report.insert(a);
        report.insert(b);
        assert_eq!(report.files.len(), 1);
        assert_eq!(report.hits("src/a.rs", 1), Some(2));
        assert_eq!(report.hits("src/a.rs", 2), Some(1));
    }

    #[test]
    fn merge_unions_files_and_takes_the_max_per_line() {
        let mut shard_a = CoverageReport::new();
        let mut a = FileCoverage::new("src/shared.rs");
        a.record(1, 3);
        a.record(2, 0);
        shard_a.insert(a);
        let mut only_a = FileCoverage::new("src/only_a.rs");
        only_a.record(1, 1);
        shard_a.insert(only_a);

        let mut shard_b = CoverageReport::new();
        let mut b = FileCoverage::new("src/shared.rs");
        b.record(1, 0);
        b.record(2, 7);
        b.record(3, 0);
        shard_b.insert(b);
        let mut only_b = FileCoverage::new("src/only_b.rs");
        only_b.record(1, 0);
        shard_b.insert(only_b);

        shard_a.merge(shard_b);

        assert_eq!(shard_a.files.len(), 3);
        // Line 1 was hit only in shard A, line 2 only in shard B: both count as covered.
        assert_eq!(shard_a.hits("src/shared.rs", 1), Some(3));
        assert_eq!(shard_a.hits("src/shared.rs", 2), Some(7));
        // A line only one shard instrumented keeps that shard's count.
        assert_eq!(shard_a.hits("src/shared.rs", 3), Some(0));
        assert_eq!(shard_a.hits("src/only_a.rs", 1), Some(1));
        assert_eq!(shard_a.hits("src/only_b.rs", 1), Some(0));
    }

    #[test]
    fn merge_is_order_independent() {
        let report = |lines: &[(u32, u64)]| {
            let mut r = CoverageReport::new();
            let mut f = FileCoverage::new("src/a.rs");
            for &(line, hits) in lines {
                f.record(line, hits);
            }
            r.insert(f);
            r
        };
        let mut ab = report(&[(1, 1), (2, 0)]);
        ab.merge(report(&[(1, 0), (2, 4)]));
        let mut ba = report(&[(1, 0), (2, 4)]);
        ba.merge(report(&[(1, 1), (2, 0)]));
        assert_eq!(ab, ba);
    }

    #[test]
    fn project_percent_aggregates_files() {
        let mut report = CoverageReport::new();
        let mut a = FileCoverage::new("src/a.rs");
        a.record(1, 1);
        a.record(2, 1);
        let mut b = FileCoverage::new("src/b.rs");
        b.record(1, 0);
        b.record(2, 0);
        report.insert(a);
        report.insert(b);
        assert_eq!(report.total_lines(), 4);
        assert_eq!(report.covered_lines(), 2);
        assert_eq!(report.percent(), Some(50.0));
    }

    #[test]
    fn strip_prefix_makes_paths_repo_relative() {
        let mut report = CoverageReport::new();
        let mut f = FileCoverage::new("/home/runner/work/patchcov/patchcov/src/a.rs");
        f.record(1, 1);
        report.insert(f);
        report.strip_prefix(Path::new("/home/runner/work/patchcov/patchcov"));
        assert!(report.files.contains_key("src/a.rs"));
    }

    #[test]
    fn strip_prefix_merges_colliding_paths() {
        // Two distinct source paths that normalise to the same repo path.
        let mut report = CoverageReport::new();
        let mut a = FileCoverage::new("/root/src/a.rs");
        a.record(1, 0);
        let mut b = FileCoverage::new("/root/./src/a.rs");
        b.record(2, 1);
        report.insert(a);
        report.insert(b);
        assert_eq!(report.files.len(), 2);
        report.strip_prefix(Path::new("/root"));
        assert_eq!(report.files.len(), 1);
        assert_eq!(report.hits("src/a.rs", 1), Some(0));
        assert_eq!(report.hits("src/a.rs", 2), Some(1));
    }

    #[test]
    fn strip_prefix_leaves_relative_paths() {
        let mut report = CoverageReport::new();
        let mut f = FileCoverage::new("./src/a.rs");
        f.record(1, 1);
        report.insert(f);
        report.strip_prefix(Path::new("/some/other/root"));
        assert!(report.files.contains_key("src/a.rs"));
    }

    #[test]
    fn retain_lines_drops_only_the_named_lines() {
        let mut report = CoverageReport::new();
        let mut f = FileCoverage::new("src/a.rs");
        f.record(1, 1);
        f.record(2, 0);
        f.record(3, 5);
        report.insert(f);
        report.retain_lines(|path, line| !(path == "src/a.rs" && line == 2));
        assert_eq!(report.hits("src/a.rs", 1), Some(1));
        assert_eq!(report.hits("src/a.rs", 2), None);
        assert_eq!(report.hits("src/a.rs", 3), Some(5));
        assert_eq!(report.total_lines(), 2);
    }

    /// A file whose every line is ignored must leave the report entirely. Kept
    /// at zero lines its `percent()` is `None`, which `FileDelta::delta` reads
    /// as a fall to zero — an ignored file would render as a total loss of
    /// coverage.
    #[test]
    fn retain_lines_removes_files_left_empty() {
        let mut report = CoverageReport::new();
        for path in ["src/a.rs", "src/gated.rs"] {
            let mut f = FileCoverage::new(path);
            f.record(1, 1);
            report.insert(f);
        }
        report.retain_lines(|path, _| path != "src/gated.rs");
        assert!(report.files.contains_key("src/a.rs"));
        assert!(
            !report.files.contains_key("src/gated.rs"),
            "a file with no lines left must be dropped, not kept at 0%"
        );
    }

    #[test]
    fn retain_paths_drops_non_matching_files() {
        let mut report = CoverageReport::new();
        for path in ["src/a.rs", "src/gpu/mlx.rs", "src/b.rs"] {
            let mut f = FileCoverage::new(path);
            f.record(1, 1);
            report.insert(f);
        }
        let dropped = report.retain_paths(|path| !path.contains("gpu/"));
        assert!(report.files.contains_key("src/a.rs"));
        assert!(report.files.contains_key("src/b.rs"));
        assert!(!report.files.contains_key("src/gpu/mlx.rs"));
        assert_eq!(dropped.len(), 1);
        assert_eq!(dropped[0].path, "src/gpu/mlx.rs");
        assert_eq!(
            dropped[0].lines.len(),
            1,
            "the dropped file keeps its lines"
        );
    }
    #[test]
    fn branch_evidence_survives_aliases_merges_and_line_filters() {
        let mut a = crate::lcov::parse_with_branches("SF:/root/a.rs\nDA:1,1\nDA:2,1\nBRDA:1,0,0,1\nBRDA:1,0,1,0\nBRDA:2,0,0,0\nend_of_record").unwrap();
        let b = crate::lcov::parse_with_branches(
            "SF:/root/./a.rs\nDA:1,2\nBRDA:1,0,0,0\nBRDA:1,0,1,1\nend_of_record",
        )
        .unwrap();
        a.merge(b);
        a.strip_prefix(Path::new("/root"));
        a.retain_lines(|_, line| line != 2);
        assert_eq!(a.files["a.rs"].branches.len(), 2);
        a.apply_branch_coverage();
        assert_eq!(a.hits("a.rs", 1), Some(2));
        assert_eq!(a.hits("a.rs", 2), None);
    }

    #[test]
    fn mapped_aliases_keep_partial_branch_evidence() {
        let mut report = crate::lcov::parse_with_branches(
            "SF:pkg/a.rs\nDA:1,1\nBRDA:1,0,0,0\nend_of_record\nSF:a.rs\nDA:1,2\nend_of_record",
        )
        .unwrap();
        report
            .map_paths(&[crate::paths::PathMapping {
                from: "pkg".into(),
                to: String::new(),
            }])
            .unwrap();
        report.apply_branch_coverage();
        assert_eq!(report.hits("a.rs", 1), Some(0));
    }
}