Skip to main content

testing_conventions/
patch_coverage.rs

1//! Diff-scoped coverage floor.
2//!
3//! Enforces the README Coverage rule over the lines a diff touches: where
4//! [`crate::coverage`] measures the *whole* suite against the configured floor,
5//! the `measure*` functions here measure that same floor over only the
6//! lines `<base>...HEAD` added or modified — `covered ÷ total-changed-executable`,
7//! against the thresholds `unit coverage` enforces whole-tree. `unit coverage
8//! --base` routes here, so a diff that clears the configured floor passes even with
9//! an uncovered changed line, and one below it fails no matter how small.
10//!
11//! Two inputs are combined:
12//!   - the **diff** — [`changed_lines`] runs `git diff --unified=0 <base>...HEAD`
13//!     and returns the new-side line numbers each file gained. This diff machinery
14//!     is language-agnostic, shared by all three arms.
15//!   - the **coverage** — per the language. Python ([`measure`]) reads coverage.py's
16//!     per-file lines and branch arcs ([`crate::coverage::measure_patch_report`]),
17//!     restricting the `percent_covered` ratio to the changed lines
18//!     ([`evaluate_patch`]). TypeScript ([`measure_typescript`]) reduces vitest's v8
19//!     export to the four per-metric counts
20//!     ([`crate::coverage::measure_patch_typescript_detail`]) and Rust
21//!     ([`measure_rust`]) reduces `cargo llvm-cov`'s export to the per-region counts
22//!     ([`crate::coverage::measure_patch_rust_detail`]); each metric's ratio is then
23//!     restricted to the changed lines ([`evaluate_patch_typescript`] /
24//!     [`evaluate_patch_rust`]). Either way, non-executable changed lines (comments,
25//!     blanks) and `coverage`-exempt files have nothing to cover and drop out of the
26//!     ratio.
27//!
28//! Relationship to the commit-scoped co-change rule ([`crate::co_change`]):
29//! co-change enforces that a changed source and its colocated *test* move
30//! together; the diff-scoped floor enforces that the changed *lines* are actually
31//! exercised. They are complementary, not overlapping — co-change can pass (the
32//! test file changed) while the floor fails (the change isn't covered), and
33//! vice versa.
34
35use std::collections::{BTreeMap, BTreeSet};
36use std::path::Path;
37use std::process::Command;
38
39use anyhow::{bail, Context, Result};
40
41use crate::coverage::{
42    self, FileCoverage, Outcome, RustThresholds, Thresholds, TypeScriptThresholds,
43};
44
45/// TypeScript source extensions the diff-scoped floor scopes to — the set
46/// `coverage`'s `TS_INCLUDE` measures. A `.d.ts` declaration ends in `.ts` but
47/// carries no runtime code; vitest excludes it from the report, so its changed
48/// lines find nothing to cover and are skipped without a special case here.
49const TS_EXTENSIONS: [&str; 4] = [".ts", ".tsx", ".mts", ".cts"];
50
51/// Diff-scoped Python coverage floor: measure `thresholds` over the
52/// `<base>...HEAD` changed `.py` lines instead of the whole tree. `omit` is the
53/// `coverage`-rule exemptions, as in [`crate::coverage::measure`] — an exempt file
54/// is omitted from the run, so its changed lines drop out of the ratio.
55///
56/// Scopes to `.py` sources and returns early — with no coverage run — when the diff
57/// touches none, so a PR that changes only docs or other languages doesn't pay for a
58/// measurement (and is vacuously covered). Requires coverage.py + pytest + git; an
59/// unresolvable `base` surfaces as an error rather than a silent pass.
60pub fn measure(
61    root: &Path,
62    base: &str,
63    thresholds: Thresholds,
64    omit: &[String],
65    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
66) -> Result<Outcome> {
67    let mut changed = changed_lines(root, base)?;
68    changed.retain(|path, _| path.ends_with(".py"));
69    lift_exempt_lines(&mut changed, exempt_lines);
70    if changed.is_empty() {
71        return Ok(Outcome::Pass);
72    }
73    let report = coverage::measure_patch_report(root, omit)?;
74    let files = relative_keys(report.files, root);
75    Ok(evaluate_patch(&changed, &files, thresholds))
76}
77
78/// Drop the line-scoped `coverage` exemptions from a `--base` diff's changed-line
79/// set, so a changed line that is line-exempt is lifted from the diff floor — the
80/// counterpart to a whole-file exemption dropping the file. The over-exemption guard is
81/// the whole-tree floor's job ([`measure_line_exempt`], the `unit coverage` job the
82/// reusable workflow runs alongside `--base`); the diff job can't classify a line its
83/// diff didn't touch, so here the exempt lines are simply removed.
84fn lift_exempt_lines(
85    changed: &mut BTreeMap<String, BTreeSet<u64>>,
86    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
87) {
88    for (file, exempt) in exempt_lines {
89        if let Some(lines) = changed.get_mut(file) {
90            lines.retain(|&line| !u32::try_from(line).is_ok_and(|line| exempt.contains(&line)));
91        }
92    }
93}
94
95/// Pure: the configured floor measured over the changed lines. Reproduces
96/// coverage.py's `percent_covered` — (executed lines + taken branch arcs) ÷
97/// (executable lines + all branch arcs) — restricted to the lines the diff touched,
98/// so the same number `unit coverage` enforces whole-tree is judged on the diff.
99///
100/// A changed line absent from `files` (a comment or blank, a test file, or a
101/// `coverage`-exempt file omitted from the run) has nothing to cover and is skipped;
102/// when nothing executable changed, the diff is vacuously covered (`Pass`). With
103/// `branch`, a branch arc counts toward the ratio when its source line is in the diff
104/// — taken arcs as covered, untaken as missed — exactly as the whole-tree total folds
105/// branches in. No small-diff carve-out: a tiny diff below the floor fails like any
106/// other.
107fn evaluate_patch(
108    changed: &BTreeMap<String, BTreeSet<u64>>,
109    files: &BTreeMap<String, FileCoverage>,
110    thresholds: Thresholds,
111) -> Outcome {
112    let (covered, total) = python_ratio(changed, files, thresholds.branch);
113    if total == 0 {
114        return Outcome::Pass;
115    }
116    let actual = 100.0 * covered as f64 / total as f64;
117    // A hair of tolerance so a percent that rounds to the floor isn't failed by float
118    // noise (matches the whole-tree `coverage::evaluate`).
119    if actual + 1e-9 >= f64::from(thresholds.fail_under) {
120        Outcome::Pass
121    } else {
122        Outcome::Fail(format!(
123            "changed-line coverage {actual:.2}% is below the required {}%",
124            thresholds.fail_under
125        ))
126    }
127}
128
129/// Pure: coverage.py's `percent_covered` numerator/denominator restricted to the lines
130/// in `selected` — (executed lines + taken branch arcs) over (executable lines + all
131/// branch arcs), counting only the selected lines and the arcs whose source is selected.
132/// Shared by the diff-scoped floor ([`evaluate_patch`], where `selected` is the changed
133/// lines) and the line-scoped exemption floor ([`measure_line_exempt`], where it's the
134/// measured lines minus the exempt ones). Over *every* measured line it reproduces the
135/// whole-tree total exactly.
136fn python_ratio(
137    selected: &BTreeMap<String, BTreeSet<u64>>,
138    files: &BTreeMap<String, FileCoverage>,
139    branch: bool,
140) -> (u64, u64) {
141    let mut covered: u64 = 0;
142    let mut total: u64 = 0;
143    for (file, lines) in selected {
144        let Some(cov) = files.get(file) else {
145            continue;
146        };
147        let executed: BTreeSet<u64> = cov.executed_lines.iter().copied().collect();
148        let missing: BTreeSet<u64> = cov.missing_lines.iter().copied().collect();
149        for &line in lines {
150            if executed.contains(&line) {
151                covered += 1;
152                total += 1;
153            } else if missing.contains(&line) {
154                total += 1;
155            }
156        }
157        if branch {
158            for arc in &cov.executed_branches {
159                if arc_source_in(arc, lines) {
160                    covered += 1;
161                    total += 1;
162                }
163            }
164            for arc in &cov.missing_branches {
165                if arc_source_in(arc, lines) {
166                    total += 1;
167                }
168            }
169        }
170    }
171    (covered, total)
172}
173
174/// Whether a branch arc's source line (the first of its `[src, dst]` pair; `dst` may
175/// be a negative exit, which is irrelevant) falls in `lines`.
176fn arc_source_in(arc: &[i64], lines: &BTreeSet<u64>) -> bool {
177    arc.first()
178        .and_then(|&src| u64::try_from(src).ok())
179        .is_some_and(|src| lines.contains(&src))
180}
181
182/// Diff-scoped TypeScript coverage floor: the four vitest metrics measured
183/// over the `<base>...HEAD` changed `.ts`/`.tsx`/`.mts`/`.cts` lines instead of the
184/// whole tree. `exclude` is the `coverage`-rule exemptions, as in
185/// [`crate::coverage::measure_typescript`] — an excluded file is left out of the
186/// run, so its changed lines drop out of the ratios.
187///
188/// Scopes to TypeScript sources and returns early — with no coverage run — when the
189/// diff touches none, so a PR that changes only docs or other languages doesn't pay
190/// for a measurement (and is vacuously covered). Requires vitest + git; an
191/// unresolvable `base` surfaces as an error rather than a silent pass.
192pub fn measure_typescript(
193    root: &Path,
194    base: &str,
195    thresholds: TypeScriptThresholds,
196    exclude: &[String],
197    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
198) -> Result<Outcome> {
199    let mut changed = changed_lines(root, base)?;
200    changed.retain(|path, _| TS_EXTENSIONS.iter().any(|ext| path.ends_with(ext)));
201    lift_exempt_lines(&mut changed, exempt_lines);
202    if changed.is_empty() {
203        return Ok(Outcome::Pass);
204    }
205    let detail = relative_keys(
206        coverage::measure_patch_typescript_detail(root, exclude)?,
207        root,
208    );
209    Ok(evaluate_patch_typescript(&changed, &detail, thresholds))
210}
211
212/// Pure: the four vitest floors measured over the changed lines. Each metric's
213/// ratio is restricted to the lines the diff touched, so the same numbers
214/// `unit coverage` enforces whole-tree are judged on the diff:
215///   - **statements**: a `statementMap` entry counts when any line in its
216///     `start..=end` is a changed line; covered when its flag is set.
217///   - **lines**: a changed line counts when ≥1 statement *starts* on it; covered
218///     when ≥1 statement starting on it is covered.
219///   - **branches**: a branch arm counts when its `source_line` is a changed line;
220///     covered when its flag is set.
221///   - **functions**: a function counts when its `decl_line` is a changed line;
222///     covered when its flag is set.
223///
224/// A changed file absent from `detail` (a test file, a declaration file, or a
225/// `coverage`-exempt file left out of the run) has nothing to cover and is skipped.
226/// Each metric's percent is `100 * covered / total`, or `100` when its denominator
227/// is empty — a diff-scoped empty denominator is **vacuously satisfied**, not the
228/// "measured no code" failure the whole-tree [`coverage::evaluate_typescript`]
229/// returns (a diff may legitimately touch no branches or functions). The fail
230/// message lists every metric below its floor, matching
231/// [`coverage::evaluate_typescript`]'s. No small-diff carve-out: a tiny diff below
232/// the floor fails like any other.
233fn evaluate_patch_typescript(
234    changed: &BTreeMap<String, BTreeSet<u64>>,
235    detail: &BTreeMap<String, coverage::TsPatchCoverage>,
236    thresholds: TypeScriptThresholds,
237) -> Outcome {
238    let (mut s_cov, mut s_tot) = (0u64, 0u64);
239    let (mut l_cov, mut l_tot) = (0u64, 0u64);
240    let (mut b_cov, mut b_tot) = (0u64, 0u64);
241    let (mut f_cov, mut f_tot) = (0u64, 0u64);
242
243    for (file, lines) in changed {
244        let Some(cov) = detail.get(file) else {
245            continue;
246        };
247
248        // Statements: count one whenever any line it spans was changed.
249        for &(start, end, covered) in &cov.statements {
250            if (start..=end).any(|line| lines.contains(&line)) {
251                s_tot += 1;
252                if covered {
253                    s_cov += 1;
254                }
255            }
256        }
257
258        // Lines: a changed line on which ≥1 statement *starts* counts; covered when
259        // ≥1 statement starting on it is covered.
260        for &line in lines {
261            let mut starts_here = false;
262            let mut covered_here = false;
263            for &(start, _end, covered) in &cov.statements {
264                if start == line {
265                    starts_here = true;
266                    covered_here |= covered;
267                }
268            }
269            if starts_here {
270                l_tot += 1;
271                if covered_here {
272                    l_cov += 1;
273                }
274            }
275        }
276
277        // Branch arms: count one whenever its source line was changed.
278        for &(source_line, covered) in &cov.branch_arms {
279            if lines.contains(&source_line) {
280                b_tot += 1;
281                if covered {
282                    b_cov += 1;
283                }
284            }
285        }
286
287        // Functions: count one whenever its declaration line was changed.
288        for &(decl_line, covered) in &cov.functions {
289            if lines.contains(&decl_line) {
290                f_tot += 1;
291                if covered {
292                    f_cov += 1;
293                }
294            }
295        }
296    }
297
298    // An empty denominator is vacuously full (100%) — a diff may touch no branch or
299    // function, which is satisfied, not the whole-tree "measured no code" failure.
300    let pct = |covered: u64, total: u64| {
301        if total == 0 {
302            100.0
303        } else {
304            100.0 * covered as f64 / total as f64
305        }
306    };
307    let checks = [
308        ("lines", pct(l_cov, l_tot), thresholds.lines),
309        ("branches", pct(b_cov, b_tot), thresholds.branches),
310        ("functions", pct(f_cov, f_tot), thresholds.functions),
311        ("statements", pct(s_cov, s_tot), thresholds.statements),
312    ];
313    let mut shortfalls = Vec::new();
314    for (name, actual, required) in checks {
315        // A hair of tolerance so a percent that rounds to the floor isn't failed by
316        // float noise (matches the whole-tree `coverage::evaluate_typescript`).
317        if actual + 1e-9 < f64::from(required) {
318            shortfalls.push(format!("{name} {actual:.2}% < {required}%"));
319        }
320    }
321    if shortfalls.is_empty() {
322        Outcome::Pass
323    } else {
324        Outcome::Fail(format!(
325            "coverage below thresholds: {}",
326            shortfalls.join(", ")
327        ))
328    }
329}
330
331/// Diff-scoped Rust coverage floor: the `cargo llvm-cov` regions/lines
332/// metrics measured over the `<base>...HEAD` changed `.rs` lines instead of the
333/// whole tree. `ignore` is the `coverage`-rule exemptions, as in
334/// [`crate::coverage::measure_rust`] — an exempt file is dropped from the run, so
335/// its changed lines drop out of the ratios.
336///
337/// Scopes to `.rs` sources and returns early — with no coverage run — when the diff
338/// touches none, so a PR that changes only docs or other languages doesn't pay for a
339/// measurement (and is vacuously covered). Requires `cargo-llvm-cov` + git; an
340/// unresolvable `base` surfaces as an error rather than a silent pass.
341pub fn measure_rust(
342    root: &Path,
343    base: &str,
344    thresholds: RustThresholds,
345    ignore: &[String],
346    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
347    features: &[String],
348) -> Result<Outcome> {
349    let mut changed = changed_lines(root, base)?;
350    changed.retain(|path, _| path.ends_with(".rs"));
351    lift_exempt_lines(&mut changed, exempt_lines);
352    if changed.is_empty() {
353        return Ok(Outcome::Pass);
354    }
355    let detail = relative_keys(
356        coverage::measure_patch_rust_detail(root, ignore, features)?,
357        root,
358    );
359    Ok(evaluate_patch_rust(&changed, &detail, thresholds))
360}
361
362/// Pure: the two `cargo llvm-cov` floors (regions, lines) measured over the changed
363/// lines. Each metric's ratio is restricted to the lines the diff touched, so the
364/// same numbers `unit coverage` enforces whole-tree are judged on the diff:
365///   - **regions**: a code region counts when any line in its `start..=end` is a
366///     changed line; covered when its flag is set.
367///   - **lines**: a changed line counts when ≥1 region covers it (`start <= line <=
368///     end`); covered when ≥1 covering region has its flag set.
369///
370/// A changed file absent from `detail` (a test-only file or a `coverage`-exempt file
371/// dropped from the run) has nothing to cover and is skipped. Each metric's percent
372/// is `100 * covered / total`, or `100` when its denominator is empty — a
373/// diff-scoped empty denominator is **vacuously satisfied**, not the "measured no
374/// code" failure the whole-tree [`coverage::evaluate_rust`] returns (a diff may
375/// legitimately touch no measured region). The fail message lists every metric below
376/// its floor, matching [`coverage::evaluate_rust`]'s. No small-diff carve-out: a tiny
377/// diff below the floor fails like any other.
378fn evaluate_patch_rust(
379    changed: &BTreeMap<String, BTreeSet<u64>>,
380    detail: &BTreeMap<String, coverage::RustPatchCoverage>,
381    thresholds: RustThresholds,
382) -> Outcome {
383    let (mut r_cov, mut r_tot) = (0u64, 0u64);
384    let (mut l_cov, mut l_tot) = (0u64, 0u64);
385
386    for (file, lines) in changed {
387        let Some(cov) = detail.get(file) else {
388            continue;
389        };
390
391        // Regions: count one whenever any line it spans was changed.
392        for &(start, end, covered) in &cov.regions {
393            if (start..=end).any(|line| lines.contains(&line)) {
394                r_tot += 1;
395                if covered {
396                    r_cov += 1;
397                }
398            }
399        }
400
401        // Lines: a changed line covered by ≥1 region counts; covered when ≥1 region
402        // covering it has its flag set.
403        for &line in lines {
404            let mut measured = false;
405            let mut covered_here = false;
406            for &(start, end, covered) in &cov.regions {
407                if start <= line && line <= end {
408                    measured = true;
409                    covered_here |= covered;
410                }
411            }
412            if measured {
413                l_tot += 1;
414                if covered_here {
415                    l_cov += 1;
416                }
417            }
418        }
419    }
420
421    // An empty denominator is vacuously full (100%) — a diff may touch no measured
422    // region, which is satisfied, not the whole-tree "measured no code" failure.
423    let pct = |covered: u64, total: u64| {
424        if total == 0 {
425            100.0
426        } else {
427            100.0 * covered as f64 / total as f64
428        }
429    };
430    // `regions` is opt-in: skip the region check unless a config set a floor,
431    // matching the whole-tree `coverage::evaluate_rust`.
432    let mut checks: Vec<(&str, f64, u8)> = Vec::new();
433    if let Some(regions) = thresholds.regions {
434        checks.push(("regions", pct(r_cov, r_tot), regions));
435    }
436    checks.push(("lines", pct(l_cov, l_tot), thresholds.lines));
437    let mut shortfalls = Vec::new();
438    for (name, actual, required) in checks {
439        // A hair of tolerance so a percent that rounds to the floor isn't failed by
440        // float noise (matches the whole-tree `coverage::evaluate_rust`).
441        if actual + 1e-9 < f64::from(required) {
442            shortfalls.push(format!("{name} {actual:.2}% < {required}%"));
443        }
444    }
445    if shortfalls.is_empty() {
446        Outcome::Pass
447    } else {
448        Outcome::Fail(format!(
449            "coverage below thresholds: {}",
450            shortfalls.join(", ")
451        ))
452    }
453}
454
455/// The new-side lines each file gained in `repo`'s `<base>...HEAD` diff, keyed by
456/// `repo`-relative path. The diff machinery shared by the TS / Rust twins.
457///
458/// `<base>...HEAD` is the merge-base diff — the changes this branch introduced
459/// (what a PR shows). `--unified=0` drops context lines so every `+` line is a
460/// real addition; `--no-renames` keeps a rename a delete + an add (the added side
461/// is held to coverage); `--relative` reports paths relative to `repo`. Returns an
462/// error if `git diff` fails (e.g. `base` names no resolvable ref).
463pub fn changed_lines(repo: &Path, base: &str) -> Result<BTreeMap<String, BTreeSet<u64>>> {
464    let range = format!("{base}...HEAD");
465    let output = Command::new("git")
466        .current_dir(repo)
467        .args([
468            "diff",
469            "--no-color",
470            "--no-renames",
471            "--unified=0",
472            "--relative",
473            &range,
474        ])
475        .output()
476        .with_context(|| format!("running `git diff` in `{}`", repo.display()))?;
477    if !output.status.success() {
478        bail!(
479            "`git diff {range}` failed in `{}`: {}",
480            repo.display(),
481            String::from_utf8_lossy(&output.stderr).trim()
482        );
483    }
484    Ok(parse_unified_diff(&String::from_utf8_lossy(&output.stdout)))
485}
486
487/// Pure: parse `git diff --unified=0` output into the new-side lines each file
488/// gained. Tracks the current file from each `+++` header and the new-side line
489/// counter from each `@@ … +c,d @@` hunk header, then records every following `+`
490/// line (a deletion `-` consumes no new-side number). A deleted file
491/// (`+++ /dev/null`) yields no entry.
492fn parse_unified_diff(diff: &str) -> BTreeMap<String, BTreeSet<u64>> {
493    let mut changed: BTreeMap<String, BTreeSet<u64>> = BTreeMap::new();
494    let mut current: Option<String> = None;
495    let mut next_line: u64 = 0;
496    for line in diff.lines() {
497        if let Some(header) = line.strip_prefix("+++ ") {
498            current = new_side_path(header);
499        } else if line.starts_with("@@") {
500            if let Some(start) = hunk_new_start(line) {
501                next_line = start;
502            }
503        } else if line.starts_with('+') {
504            // An added new-side line — the `+++` header is handled above, so this
505            // is diff body. Record it against the current file and advance.
506            if let Some(file) = &current {
507                changed.entry(file.clone()).or_default().insert(next_line);
508            }
509            next_line += 1;
510        }
511        // `-` (deleted) and metadata lines consume no new-side line and are skipped.
512    }
513    changed
514}
515
516/// The `repo`-relative new-side path from a `+++` diff header, or `None` for a
517/// deletion (`+++ /dev/null`). Strips git's `b/` prefix and a trailing tab.
518fn new_side_path(header: &str) -> Option<String> {
519    let path = header
520        .split('\t')
521        .next()
522        .unwrap_or(header)
523        .trim_end_matches('\r');
524    if path == "/dev/null" {
525        return None;
526    }
527    let path = path.strip_prefix("b/").unwrap_or(path);
528    Some(path.replace('\\', "/"))
529}
530
531/// The new-side start line from a hunk header `@@ -a,b +c,d @@ …` — the `c`. With
532/// `--unified=0` the added lines that follow are numbered consecutively from it.
533fn hunk_new_start(header: &str) -> Option<u64> {
534    let plus = header.split_whitespace().find(|t| t.starts_with('+'))?;
535    let digits = plus.trim_start_matches('+');
536    digits.split(',').next().unwrap_or(digits).parse().ok()
537}
538
539/// Re-key a report's per-file map to `root`-relative `/`-joined paths so they match
540/// the diff's paths. coverage.py reports paths relative to where it ran (here
541/// `root`) and vitest reports absolute paths; an absolute path is stripped to
542/// `root`, a relative one left as-is.
543fn relative_keys<V>(files: BTreeMap<String, V>, root: &Path) -> BTreeMap<String, V> {
544    files
545        .into_iter()
546        .map(|(key, value)| {
547            let path = Path::new(&key);
548            let rel = path
549                .strip_prefix(root)
550                .unwrap_or(path)
551                .to_string_lossy()
552                .replace('\\', "/");
553            (rel, value)
554        })
555        .collect()
556}
557
558// Line-scoped coverage exemptions.
559//
560// A `coverage` exemption with a `lines` list excuses only those lines from the floor,
561// not the whole file. No coverage tool excludes individual line *numbers* from the
562// outside (coverage.py / v8 / llvm-cov all do it through source pragmas, which this
563// tool can't write), so the floor is recomputed from the same per-file detail the
564// diff-scoped floor reads — the measured lines minus the exempt ones. A determinism
565// guard (the counterpart to the stale-path rule) keeps the list honest: every listed
566// line must be genuinely uncovered, and an unlisted uncovered line still fails.
567
568/// Diff-free Python coverage floor with line-scoped exemptions: measure
569/// `thresholds` over every measured line *except* the `exempt_lines`. `omit` is the
570/// whole-file `coverage` exemptions, as in [`crate::coverage::measure`]. Requires
571/// coverage.py + pytest. The line-exempt path runs only when `exempt_lines` is
572/// non-empty; otherwise the caller takes the unchanged tool-total path.
573pub fn measure_line_exempt(
574    root: &Path,
575    thresholds: Thresholds,
576    omit: &[String],
577    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
578) -> Result<Outcome> {
579    let report = coverage::measure_report(root, omit)?;
580    let files = relative_keys(report.files, root);
581    let detail: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = files
582        .iter()
583        .map(|(file, cov)| (file.clone(), python_measured_missed(cov, thresholds.branch)))
584        .collect();
585    let line_set = apply_line_exemptions(&detail, exempt_lines)?;
586    let (covered, total) = python_ratio(&line_set, &files, thresholds.branch);
587    Ok(floor_outcome(covered, total, thresholds.fail_under))
588}
589
590/// TypeScript twin of [`measure_line_exempt`]: the four vitest metrics measured
591/// over every measured line except the `exempt_lines`. `exclude` is the whole-file
592/// `coverage` exemptions, as in [`crate::coverage::measure_typescript`]. Requires
593/// vitest + `@vitest/coverage-v8`.
594pub fn measure_line_exempt_typescript(
595    root: &Path,
596    thresholds: TypeScriptThresholds,
597    exclude: &[String],
598    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
599) -> Result<Outcome> {
600    let detail = relative_keys(
601        coverage::measure_patch_typescript_detail(root, exclude)?,
602        root,
603    );
604    let measured_missed: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = detail
605        .iter()
606        .map(|(file, cov)| (file.clone(), ts_measured_missed(cov)))
607        .collect();
608    let line_set = apply_line_exemptions(&measured_missed, exempt_lines)?;
609    Ok(evaluate_patch_typescript(&line_set, &detail, thresholds))
610}
611
612/// Rust twin of [`measure_line_exempt`]: the `cargo llvm-cov` regions/lines
613/// metrics measured over every measured line except the `exempt_lines`. `ignore` is the
614/// whole-file `coverage` exemptions, as in [`crate::coverage::measure_rust`]. Requires
615/// `cargo-llvm-cov`.
616pub fn measure_line_exempt_rust(
617    root: &Path,
618    thresholds: RustThresholds,
619    ignore: &[String],
620    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
621    features: &[String],
622) -> Result<Outcome> {
623    let detail = relative_keys(
624        coverage::measure_patch_rust_detail(root, ignore, features)?,
625        root,
626    );
627    let measured_missed: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = detail
628        .iter()
629        .map(|(file, cov)| (file.clone(), rust_measured_missed(cov, thresholds)))
630        .collect();
631    let line_set = apply_line_exemptions(&measured_missed, exempt_lines)?;
632    Ok(evaluate_patch_rust(&line_set, &detail, thresholds))
633}
634
635/// The whole-tree floor verdict for a recomputed `covered`/`total`, with the same
636/// message and float tolerance as the tool-total [`crate::coverage::evaluate`] — a
637/// from-detail total with the exempt lines removed is judged exactly as the tool's own.
638fn floor_outcome(covered: u64, total: u64, fail_under: u8) -> Outcome {
639    if total == 0 {
640        return Outcome::Pass;
641    }
642    let actual = 100.0 * covered as f64 / total as f64;
643    if actual + 1e-9 >= f64::from(fail_under) {
644        Outcome::Pass
645    } else {
646        Outcome::Fail(format!(
647            "coverage {actual:.2}% is below the required {fail_under}%"
648        ))
649    }
650}
651
652/// The `(measured, missed)` lines for one Python file. `measured` is every executable
653/// line (executed or missing); `missed` is what the floor counts against you — the
654/// uncovered lines, plus (under branch coverage) any line that is the source of an
655/// untaken branch arc.
656fn python_measured_missed(cov: &FileCoverage, branch: bool) -> (BTreeSet<u64>, BTreeSet<u64>) {
657    let executed: BTreeSet<u64> = cov.executed_lines.iter().copied().collect();
658    let missing: BTreeSet<u64> = cov.missing_lines.iter().copied().collect();
659    let measured: BTreeSet<u64> = executed.union(&missing).copied().collect();
660    let mut missed = missing;
661    if branch {
662        for arc in &cov.missing_branches {
663            if let Some(src) = arc.first().and_then(|&s| u64::try_from(s).ok()) {
664                if measured.contains(&src) {
665                    missed.insert(src);
666                }
667            }
668        }
669    }
670    (measured, missed)
671}
672
673/// The `(measured, missed)` lines for one TypeScript file. A unit is anchored on the
674/// lines it spans — statements over `start..=end`, branch arms and function decls on
675/// their line — and `missed` is that set restricted to the uncovered units, so a line
676/// carrying any uncovered unit is exemptable.
677fn ts_measured_missed(cov: &coverage::TsPatchCoverage) -> (BTreeSet<u64>, BTreeSet<u64>) {
678    let mut measured = BTreeSet::new();
679    let mut missed = BTreeSet::new();
680    // Each unit contributes its line(s): a statement spans `start..=end`, a branch arm
681    // and a function declaration sit on a single line. A line is `missed` when any unit
682    // on it is uncovered.
683    let units = cov
684        .statements
685        .iter()
686        .flat_map(|&(start, end, covered)| (start..=end).map(move |line| (line, covered)))
687        .chain(cov.branch_arms.iter().copied())
688        .chain(cov.functions.iter().copied());
689    for (line, covered) in units {
690        measured.insert(line);
691        if !covered {
692            missed.insert(line);
693        }
694    }
695    (measured, missed)
696}
697
698/// The `(measured, missed)` lines for one Rust file. `measured` is every line a code
699/// region spans; `missed` honors the enforced metrics — with `regions` on, any line in
700/// an uncovered region; with lines-only (`regions = None`), a line covered by regions
701/// but by no *covered* one.
702fn rust_measured_missed(
703    cov: &coverage::RustPatchCoverage,
704    thresholds: RustThresholds,
705) -> (BTreeSet<u64>, BTreeSet<u64>) {
706    let mut measured = BTreeSet::new();
707    for &(start, end, _covered) in &cov.regions {
708        for line in start..=end {
709            measured.insert(line);
710        }
711    }
712    let mut missed = BTreeSet::new();
713    for &line in &measured {
714        let mut covered_here = false;
715        let mut uncovered_region = false;
716        for &(start, end, covered) in &cov.regions {
717            if start <= line && line <= end {
718                if covered {
719                    covered_here = true;
720                } else {
721                    uncovered_region = true;
722                }
723            }
724        }
725        let is_missed = if thresholds.regions.is_some() {
726            uncovered_region
727        } else {
728            !covered_here
729        };
730        if is_missed {
731            missed.insert(line);
732        }
733    }
734    (measured, missed)
735}
736
737/// The per-file line set the floor is measured over — every measured line minus the
738/// exempt ones — after the determinism guard. Each exempt line must be in its
739/// file's `missed` set (genuinely failing); a listed line that is covered, or carries
740/// no measured code, is a hard error so the exemption can't excuse working code.
741fn apply_line_exemptions(
742    detail: &BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)>,
743    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
744) -> Result<BTreeMap<String, BTreeSet<u64>>> {
745    let mut over: Vec<String> = Vec::new();
746    for (file, lines) in exempt_lines {
747        let missed = detail.get(file).map(|(_, missed)| missed);
748        for &line in lines {
749            let failing = missed.is_some_and(|missed| missed.contains(&u64::from(line)));
750            if !failing {
751                over.push(format!("\n  {file}:{line}"));
752            }
753        }
754    }
755    if !over.is_empty() {
756        bail!(
757            "a line-scoped coverage exemption may only list uncovered lines, but these are \
758             covered or carry no measured code:{}",
759            over.concat()
760        );
761    }
762    let mut line_set = BTreeMap::new();
763    for (file, (measured, _)) in detail {
764        let exempt = exempt_lines.get(file);
765        let kept: BTreeSet<u64> = measured
766            .iter()
767            .copied()
768            .filter(|&line| {
769                !exempt.is_some_and(|exempt| {
770                    u32::try_from(line).is_ok_and(|line| exempt.contains(&line))
771                })
772            })
773            .collect();
774        line_set.insert(file.clone(), kept);
775    }
776    Ok(line_set)
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782
783    fn changed(entries: &[(&str, &[u64])]) -> BTreeMap<String, BTreeSet<u64>> {
784        entries
785            .iter()
786            .map(|(path, lines)| (path.to_string(), lines.iter().copied().collect()))
787            .collect()
788    }
789
790    #[test]
791    fn parses_added_lines_from_a_hunk() {
792        // `+4,2` → two added lines numbered from 4; the function context after the
793        // second `@@` is ignored.
794        let diff = "diff --git a/widget.py b/widget.py\n\
795                    index abc..def 100644\n\
796                    --- a/widget.py\n\
797                    +++ b/widget.py\n\
798                    @@ -3,0 +4,2 @@ def f(x):\n\
799                    +    if x == 99:\n\
800                    +        return 7\n";
801        assert_eq!(parse_unified_diff(diff), changed(&[("widget.py", &[4, 5])]));
802    }
803
804    #[test]
805    fn parses_a_new_file_as_added_from_line_one() {
806        let diff = "diff --git a/lonely.py b/lonely.py\n\
807                    new file mode 100644\n\
808                    index 0000000..bbb\n\
809                    --- /dev/null\n\
810                    +++ b/lonely.py\n\
811                    @@ -0,0 +1,2 @@\n\
812                    +def lonely():\n\
813                    +    return 41\n";
814        assert_eq!(parse_unified_diff(diff), changed(&[("lonely.py", &[1, 2])]));
815    }
816
817    #[test]
818    fn a_deletion_only_hunk_records_no_added_lines() {
819        // `+3,0` adds nothing; the `-` lines consume no new-side number.
820        let diff = "diff --git a/widget.py b/widget.py\n\
821                    index abc..def 100644\n\
822                    --- a/widget.py\n\
823                    +++ b/widget.py\n\
824                    @@ -4,2 +3,0 @@ def f(x):\n\
825                    -    dead = 1\n\
826                    -    return dead\n";
827        assert!(parse_unified_diff(diff).is_empty());
828    }
829
830    #[test]
831    fn a_deleted_file_yields_no_entry() {
832        let diff = "diff --git a/gone.py b/gone.py\n\
833                    deleted file mode 100644\n\
834                    index abc..0000000\n\
835                    --- a/gone.py\n\
836                    +++ /dev/null\n\
837                    @@ -1,2 +0,0 @@\n\
838                    -def gone():\n\
839                    -    return 0\n";
840        assert!(parse_unified_diff(diff).is_empty());
841    }
842
843    #[test]
844    fn parses_multiple_files_and_a_single_line_hunk() {
845        // `+2` (no count) is one line at line 2; a nested path is kept verbatim.
846        let diff = "diff --git a/a.py b/a.py\n\
847                    --- a/a.py\n\
848                    +++ b/a.py\n\
849                    @@ -1,0 +2 @@ def a():\n\
850                    +    x = 1\n\
851                    diff --git a/pkg/b.py b/pkg/b.py\n\
852                    --- a/pkg/b.py\n\
853                    +++ b/pkg/b.py\n\
854                    @@ -10,0 +11,1 @@\n\
855                    +    y = 2\n";
856        assert_eq!(
857            parse_unified_diff(diff),
858            changed(&[("a.py", &[2]), ("pkg/b.py", &[11])])
859        );
860    }
861
862    fn cov(
863        executed: &[u64],
864        missing: &[u64],
865        executed_branches: &[[i64; 2]],
866        missing_branches: &[[i64; 2]],
867    ) -> FileCoverage {
868        FileCoverage {
869            executed_lines: executed.to_vec(),
870            missing_lines: missing.to_vec(),
871            excluded_lines: Vec::new(),
872            executed_branches: executed_branches.iter().map(|b| b.to_vec()).collect(),
873            missing_branches: missing_branches.iter().map(|b| b.to_vec()).collect(),
874        }
875    }
876
877    const FLOOR_85: Thresholds = Thresholds {
878        fail_under: 85,
879        branch: true,
880    };
881
882    #[test]
883    fn patch_a_fully_covered_diff_passes() {
884        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[], &[], &[]))]);
885        assert_eq!(
886            evaluate_patch(&changed(&[("w.py", &[1, 2, 3])]), &files, FLOOR_85),
887            Outcome::Pass
888        );
889    }
890
891    #[test]
892    fn patch_below_floor_fails_and_names_the_percent() {
893        // 3 of 4 changed executable lines covered → 75% < 85.
894        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[4], &[], &[]))]);
895        let out = evaluate_patch(&changed(&[("w.py", &[1, 2, 3, 4])]), &files, FLOOR_85);
896        assert!(
897            matches!(&out, Outcome::Fail(m) if m.contains("75.00%")),
898            "got: {out:?}"
899        );
900    }
901
902    #[test]
903    fn patch_the_same_diff_clears_a_lower_floor() {
904        // 75% passes a 70 floor despite the uncovered line.
905        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[4], &[], &[]))]);
906        let floor_70 = Thresholds {
907            fail_under: 70,
908            branch: true,
909        };
910        assert_eq!(
911            evaluate_patch(&changed(&[("w.py", &[1, 2, 3, 4])]), &files, floor_70),
912            Outcome::Pass
913        );
914    }
915
916    #[test]
917    fn patch_counts_branch_arcs_whose_source_is_a_changed_line() {
918        // Lines 1,2 executed (2 covered) + a taken arc out of line 2 (covered) and an
919        // untaken arc out of line 2 (missed): 3 covered of 4 → 75% < 85.
920        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[[2, 3]], &[[2, 4]]))]);
921        let out = evaluate_patch(&changed(&[("w.py", &[1, 2])]), &files, FLOOR_85);
922        assert!(
923            matches!(&out, Outcome::Fail(m) if m.contains("75.00%")),
924            "got: {out:?}"
925        );
926    }
927
928    #[test]
929    fn patch_branches_off_ignores_arcs() {
930        // Same data, branch disabled: only the two executed lines count → 100%.
931        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[[2, 3]], &[[2, 4]]))]);
932        let no_branch = Thresholds {
933            fail_under: 85,
934            branch: false,
935        };
936        assert_eq!(
937            evaluate_patch(&changed(&[("w.py", &[1, 2])]), &files, no_branch),
938            Outcome::Pass
939        );
940    }
941
942    #[test]
943    fn patch_a_changed_file_absent_from_coverage_is_skipped() {
944        // A test file (never measured) contributes nothing; with no other executable
945        // changed line the diff is vacuously covered.
946        let files = BTreeMap::from([("w.py".to_string(), cov(&[1], &[], &[], &[]))]);
947        assert_eq!(
948            evaluate_patch(&changed(&[("w_test.py", &[1, 2])]), &files, FLOOR_85),
949            Outcome::Pass
950        );
951    }
952
953    #[test]
954    fn patch_a_diff_with_no_executable_changed_lines_passes() {
955        // Changed lines are comments/blanks (in neither executed nor missing) → vacuous.
956        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[], &[]))]);
957        assert_eq!(
958            evaluate_patch(&changed(&[("w.py", &[9, 10])]), &files, FLOOR_85),
959            Outcome::Pass
960        );
961    }
962
963    use coverage::TsPatchCoverage;
964
965    fn ts_detail(entries: &[(&str, TsPatchCoverage)]) -> BTreeMap<String, TsPatchCoverage> {
966        entries
967            .iter()
968            .map(|(path, cov)| (path.to_string(), cov.clone()))
969            .collect()
970    }
971
972    const TS_FLOOR_80: TypeScriptThresholds = TypeScriptThresholds {
973        lines: 80,
974        branches: 80,
975        functions: 80,
976        statements: 80,
977    };
978
979    #[test]
980    fn ts_patch_a_fully_covered_diff_passes() {
981        // Two statements on lines 1-2, both starting on their line and both covered;
982        // a covered function on line 1; a taken branch arm off line 2 → 100% all four.
983        let detail = ts_detail(&[(
984            "w.ts",
985            TsPatchCoverage {
986                statements: vec![(1, 1, true), (2, 2, true)],
987                branch_arms: vec![(2, true)],
988                functions: vec![(1, true)],
989            },
990        )]);
991        assert_eq!(
992            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2])]), &detail, TS_FLOOR_80),
993            Outcome::Pass
994        );
995    }
996
997    #[test]
998    fn ts_patch_below_floor_fails_and_names_the_metric() {
999        // Four changed lines each carry one statement; three covered, one not →
1000        // statements (and lines) 75% < 80, named; branches/functions are empty
1001        // (vacuously 100) and not named.
1002        let detail = ts_detail(&[(
1003            "w.ts",
1004            TsPatchCoverage {
1005                statements: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
1006                branch_arms: vec![],
1007                functions: vec![],
1008            },
1009        )]);
1010        let out =
1011            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2, 3, 4])]), &detail, TS_FLOOR_80);
1012        assert!(
1013            matches!(&out, Outcome::Fail(m)
1014                if m.contains("statements 75.00% < 80%")
1015                    && m.contains("lines 75.00% < 80%")
1016                    && !m.contains("branches")
1017                    && !m.contains("functions")),
1018            "got: {out:?}"
1019        );
1020    }
1021
1022    #[test]
1023    fn ts_patch_the_same_diff_clears_a_lower_floor() {
1024        // The 75% diff passes a 70 floor despite the uncovered line.
1025        let detail = ts_detail(&[(
1026            "w.ts",
1027            TsPatchCoverage {
1028                statements: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
1029                branch_arms: vec![],
1030                functions: vec![],
1031            },
1032        )]);
1033        let floor_70 = TypeScriptThresholds {
1034            lines: 70,
1035            branches: 70,
1036            functions: 70,
1037            statements: 70,
1038        };
1039        assert_eq!(
1040            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2, 3, 4])]), &detail, floor_70),
1041            Outcome::Pass
1042        );
1043    }
1044
1045    #[test]
1046    fn ts_patch_an_untaken_branch_arm_on_a_changed_line_fails_branches() {
1047        // Line 3's statement ran (covered) but one of its two branch arms never did:
1048        // branches 50% < 80, named; lines/statements are 100 (the statement is covered).
1049        let detail = ts_detail(&[(
1050            "w.ts",
1051            TsPatchCoverage {
1052                statements: vec![(3, 3, true)],
1053                branch_arms: vec![(3, true), (3, false)],
1054                functions: vec![],
1055            },
1056        )]);
1057        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[3])]), &detail, TS_FLOOR_80);
1058        assert!(
1059            matches!(&out, Outcome::Fail(m)
1060                if m.contains("branches 50.00% < 80%")
1061                    && !m.contains("lines")
1062                    && !m.contains("statements")),
1063            "got: {out:?}"
1064        );
1065    }
1066
1067    #[test]
1068    fn ts_patch_an_uncovered_function_decl_on_a_changed_line_fails_functions() {
1069        // A function declared on changed line 9 was never called → functions 0% < 80.
1070        let detail = ts_detail(&[(
1071            "w.ts",
1072            TsPatchCoverage {
1073                statements: vec![],
1074                branch_arms: vec![],
1075                functions: vec![(9, false)],
1076            },
1077        )]);
1078        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[9])]), &detail, TS_FLOOR_80);
1079        assert!(
1080            matches!(&out, Outcome::Fail(m) if m.contains("functions 0.00% < 80%")),
1081            "got: {out:?}"
1082        );
1083    }
1084
1085    #[test]
1086    fn ts_patch_a_changed_file_absent_from_coverage_is_skipped() {
1087        // A test file (never measured) contributes nothing; with no other changed
1088        // executable line the diff is vacuously covered.
1089        let detail = ts_detail(&[(
1090            "w.ts",
1091            TsPatchCoverage {
1092                statements: vec![(1, 1, true)],
1093                branch_arms: vec![],
1094                functions: vec![],
1095            },
1096        )]);
1097        assert_eq!(
1098            evaluate_patch_typescript(&changed(&[("w.test.ts", &[1, 2])]), &detail, TS_FLOOR_80),
1099            Outcome::Pass
1100        );
1101    }
1102
1103    #[test]
1104    fn ts_patch_a_comment_only_diff_passes() {
1105        // The changed lines carry no statement/branch/function (a comment or blank) →
1106        // every denominator empty → vacuously covered.
1107        let detail = ts_detail(&[(
1108            "w.ts",
1109            TsPatchCoverage {
1110                statements: vec![(1, 1, true), (2, 2, true)],
1111                branch_arms: vec![(2, true)],
1112                functions: vec![(1, true)],
1113            },
1114        )]);
1115        assert_eq!(
1116            evaluate_patch_typescript(&changed(&[("w.ts", &[9, 10])]), &detail, TS_FLOOR_80),
1117            Outcome::Pass
1118        );
1119    }
1120
1121    #[test]
1122    fn ts_patch_an_empty_diff_passes() {
1123        // No changed lines at all → vacuously covered at any floor.
1124        assert_eq!(
1125            evaluate_patch_typescript(&changed(&[]), &BTreeMap::new(), TS_FLOOR_80),
1126            Outcome::Pass
1127        );
1128    }
1129
1130    #[test]
1131    fn ts_patch_a_multiline_statement_counts_when_any_of_its_lines_changed() {
1132        // A statement spanning lines 3-5 that never ran; only line 4 is in the diff →
1133        // it still counts (and is uncovered) → statements 0% < 80. No statement
1134        // *starts* on line 4, so lines has an empty denominator (vacuously 100).
1135        let detail = ts_detail(&[(
1136            "w.ts",
1137            TsPatchCoverage {
1138                statements: vec![(3, 5, false)],
1139                branch_arms: vec![],
1140                functions: vec![],
1141            },
1142        )]);
1143        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[4])]), &detail, TS_FLOOR_80);
1144        assert!(
1145            matches!(&out, Outcome::Fail(m)
1146                if m.contains("statements 0.00% < 80%") && !m.contains("lines")),
1147            "got: {out:?}"
1148        );
1149    }
1150
1151    use coverage::RustPatchCoverage;
1152
1153    fn rust_detail(entries: &[(&str, RustPatchCoverage)]) -> BTreeMap<String, RustPatchCoverage> {
1154        entries
1155            .iter()
1156            .map(|(path, cov)| (path.to_string(), cov.clone()))
1157            .collect()
1158    }
1159
1160    const RUST_FLOOR_80: RustThresholds = RustThresholds {
1161        regions: Some(80),
1162        lines: 80,
1163        functions: None,
1164        branch: None,
1165    };
1166
1167    #[test]
1168    fn rust_patch_a_fully_covered_diff_passes() {
1169        // Two single-line code regions on lines 1-2, both covered → regions and lines
1170        // both 100%.
1171        let detail = rust_detail(&[(
1172            "w.rs",
1173            RustPatchCoverage {
1174                regions: vec![(1, 1, true), (2, 2, true)],
1175            },
1176        )]);
1177        assert_eq!(
1178            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2])]), &detail, RUST_FLOOR_80),
1179            Outcome::Pass
1180        );
1181    }
1182
1183    #[test]
1184    fn rust_patch_below_floor_fails_and_names_the_metrics() {
1185        // Four single-line regions on lines 1-4; three covered, one not → regions (and
1186        // lines) 75% < 80, both named.
1187        let detail = rust_detail(&[(
1188            "w.rs",
1189            RustPatchCoverage {
1190                regions: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
1191            },
1192        )]);
1193        let out = evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, RUST_FLOOR_80);
1194        assert!(
1195            matches!(&out, Outcome::Fail(m)
1196                if m.contains("regions 75.00% < 80%")
1197                    && m.contains("lines 75.00% < 80%")),
1198            "got: {out:?}"
1199        );
1200    }
1201
1202    #[test]
1203    fn rust_patch_the_same_diff_clears_a_lower_floor() {
1204        // The 75% diff passes a 70 floor despite the uncovered region.
1205        let detail = rust_detail(&[(
1206            "w.rs",
1207            RustPatchCoverage {
1208                regions: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
1209            },
1210        )]);
1211        let floor_70 = RustThresholds {
1212            regions: Some(70),
1213            lines: 70,
1214            functions: None,
1215            branch: None,
1216        };
1217        assert_eq!(
1218            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, floor_70),
1219            Outcome::Pass
1220        );
1221    }
1222
1223    #[test]
1224    fn rust_patch_skips_the_region_check_when_regions_is_opt_out() {
1225        // The zero-config default sets `regions: None`, so the diff-scoped floor
1226        // enforces lines only: a diff whose changed lines are all covered passes even
1227        // though one of its regions is uncovered (lines 1-4 are each covered by ≥1
1228        // region, but region 4 is not).
1229        let detail = rust_detail(&[(
1230            "w.rs",
1231            RustPatchCoverage {
1232                regions: vec![(1, 4, true), (4, 4, false)],
1233            },
1234        )]);
1235        let lines_only = RustThresholds {
1236            regions: None,
1237            lines: 100,
1238            functions: None,
1239            branch: None,
1240        };
1241        assert_eq!(
1242            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, lines_only),
1243            Outcome::Pass
1244        );
1245    }
1246
1247    #[test]
1248    fn rust_patch_an_uncovered_region_on_a_changed_line_fails_both_metrics() {
1249        // A single uncovered region on changed line 5 → regions 0% and lines 0%, both
1250        // below the floor.
1251        let detail = rust_detail(&[(
1252            "w.rs",
1253            RustPatchCoverage {
1254                regions: vec![(5, 5, false)],
1255            },
1256        )]);
1257        let out = evaluate_patch_rust(&changed(&[("w.rs", &[5])]), &detail, RUST_FLOOR_80);
1258        assert!(
1259            matches!(&out, Outcome::Fail(m)
1260                if m.contains("regions 0.00% < 80%") && m.contains("lines 0.00% < 80%")),
1261            "got: {out:?}"
1262        );
1263    }
1264
1265    #[test]
1266    fn rust_patch_a_changed_file_absent_from_coverage_is_skipped() {
1267        // A test-only file (never measured) contributes nothing; with no other changed
1268        // measured line the diff is vacuously covered.
1269        let detail = rust_detail(&[(
1270            "w.rs",
1271            RustPatchCoverage {
1272                regions: vec![(1, 1, true)],
1273            },
1274        )]);
1275        assert_eq!(
1276            evaluate_patch_rust(&changed(&[("other.rs", &[1, 2])]), &detail, RUST_FLOOR_80),
1277            Outcome::Pass
1278        );
1279    }
1280
1281    #[test]
1282    fn rust_patch_a_comment_only_diff_passes() {
1283        // The changed lines (9-10) carry no region (a comment or blank) → both
1284        // denominators empty → vacuously covered.
1285        let detail = rust_detail(&[(
1286            "w.rs",
1287            RustPatchCoverage {
1288                regions: vec![(1, 1, true), (2, 2, true)],
1289            },
1290        )]);
1291        assert_eq!(
1292            evaluate_patch_rust(&changed(&[("w.rs", &[9, 10])]), &detail, RUST_FLOOR_80),
1293            Outcome::Pass
1294        );
1295    }
1296
1297    #[test]
1298    fn rust_patch_an_empty_diff_passes() {
1299        // No changed lines at all → vacuously covered at any floor.
1300        assert_eq!(
1301            evaluate_patch_rust(&changed(&[]), &BTreeMap::new(), RUST_FLOOR_80),
1302            Outcome::Pass
1303        );
1304    }
1305
1306    #[test]
1307    fn rust_patch_a_multiline_region_counts_when_any_of_its_lines_changed() {
1308        // A region spanning lines 3-5 that never ran; only line 4 is in the diff → it
1309        // still counts for both metrics (the region spans line 4, so line 4 is a
1310        // measured-but-uncovered line) → regions 0% and lines 0% < 80.
1311        let detail = rust_detail(&[(
1312            "w.rs",
1313            RustPatchCoverage {
1314                regions: vec![(3, 5, false)],
1315            },
1316        )]);
1317        let out = evaluate_patch_rust(&changed(&[("w.rs", &[4])]), &detail, RUST_FLOOR_80);
1318        assert!(
1319            matches!(&out, Outcome::Fail(m)
1320                if m.contains("regions 0.00% < 80%") && m.contains("lines 0.00% < 80%")),
1321            "got: {out:?}"
1322        );
1323    }
1324
1325    #[test]
1326    fn rust_patch_a_line_covered_by_any_region_is_covered() {
1327        // Two overlapping regions span changed line 4 — one uncovered, one covered.
1328        // For the lines metric the line is covered (≥1 covering region's flag is set);
1329        // for regions, one of the two counts as covered → regions 50% (< 80, fails) but
1330        // lines 100% (≥ 80, not named).
1331        let detail = rust_detail(&[(
1332            "w.rs",
1333            RustPatchCoverage {
1334                regions: vec![(4, 4, false), (4, 6, true)],
1335            },
1336        )]);
1337        let out = evaluate_patch_rust(&changed(&[("w.rs", &[4])]), &detail, RUST_FLOOR_80);
1338        assert!(
1339            matches!(&out, Outcome::Fail(m)
1340                if m.contains("regions 50.00% < 80%") && !m.contains("lines")),
1341            "got: {out:?}"
1342        );
1343    }
1344
1345    fn exempt(entries: &[(&str, &[u32])]) -> BTreeMap<String, BTreeSet<u32>> {
1346        entries
1347            .iter()
1348            .map(|(path, lines)| (path.to_string(), lines.iter().copied().collect()))
1349            .collect()
1350    }
1351
1352    #[test]
1353    fn python_measured_missed_reads_lines_and_branch_sources() {
1354        // shim.py's shape: line 1 executed (the `def`), lines 2-4 the never-run body,
1355        // a missing branch out of line 2. measured = every executable line; missed =
1356        // the uncovered lines plus the branch source.
1357        let full = cov(&[1], &[2, 3, 4], &[], &[[2, 3], [2, 4]]);
1358        let (measured, missed) = python_measured_missed(&full, true);
1359        assert_eq!(measured, [1, 2, 3, 4].into_iter().collect());
1360        assert_eq!(missed, [2, 3, 4].into_iter().collect());
1361        // With branch coverage off, a partial-branch source isn't a miss on its own.
1362        let partial = cov(&[5], &[], &[], &[[5, 6]]);
1363        let (_, missed_no_branch) = python_measured_missed(&partial, false);
1364        assert!(missed_no_branch.is_empty());
1365        let (_, missed_branch) = python_measured_missed(&partial, true);
1366        assert_eq!(missed_branch, [5].into_iter().collect());
1367    }
1368
1369    #[test]
1370    fn ts_measured_missed_anchors_units_on_their_lines() {
1371        // A covered statement on line 1, an uncovered one spanning 3-4, an uncovered
1372        // branch arm on 1, an uncovered function decl on 6.
1373        let cov = coverage::TsPatchCoverage {
1374            statements: vec![(1, 1, true), (3, 4, false)],
1375            branch_arms: vec![(1, false)],
1376            functions: vec![(6, false)],
1377        };
1378        let (measured, missed) = ts_measured_missed(&cov);
1379        assert_eq!(measured, [1, 3, 4, 6].into_iter().collect());
1380        // Line 1 is missed via its uncovered branch arm even though its statement ran.
1381        assert_eq!(missed, [1, 3, 4, 6].into_iter().collect());
1382    }
1383
1384    #[test]
1385    fn rust_measured_missed_honors_the_enforced_metrics() {
1386        // An uncovered region on lines 5-6 and a covered one on line 1.
1387        let cov = coverage::RustPatchCoverage {
1388            regions: vec![(1, 1, true), (5, 6, false)],
1389        };
1390        let with_regions = RustThresholds {
1391            regions: Some(100),
1392            lines: 100,
1393            functions: None,
1394            branch: None,
1395        };
1396        let (measured, missed) = rust_measured_missed(&cov, with_regions);
1397        assert_eq!(measured, [1, 5, 6].into_iter().collect());
1398        assert_eq!(missed, [5, 6].into_iter().collect());
1399        // Lines-only: a line covered by ≥1 covered region isn't a miss; an uncovered
1400        // region with no covering one still is.
1401        let lines_only = RustThresholds {
1402            regions: None,
1403            lines: 100,
1404            functions: None,
1405            branch: None,
1406        };
1407        let (_, missed_lines) = rust_measured_missed(&cov, lines_only);
1408        assert_eq!(missed_lines, [5, 6].into_iter().collect());
1409    }
1410
1411    #[test]
1412    fn apply_line_exemptions_drops_listed_misses_from_the_line_set() {
1413        // shim measured {1,2,3,4}, missed {2,3,4}; exempting 2-4 leaves {1}.
1414        let detail = BTreeMap::from([(
1415            "shim.py".to_string(),
1416            (
1417                [1u64, 2, 3, 4].into_iter().collect::<BTreeSet<u64>>(),
1418                [2u64, 3, 4].into_iter().collect::<BTreeSet<u64>>(),
1419            ),
1420        )]);
1421        let line_set = apply_line_exemptions(&detail, &exempt(&[("shim.py", &[2, 3, 4])])).unwrap();
1422        assert_eq!(line_set["shim.py"], [1].into_iter().collect());
1423    }
1424
1425    #[test]
1426    fn apply_line_exemptions_rejects_a_covered_listed_line() {
1427        // Line 1 is measured but not missed (it's covered) — over-exemption is an error.
1428        let detail = BTreeMap::from([(
1429            "shim.py".to_string(),
1430            (
1431                [1u64, 2].into_iter().collect::<BTreeSet<u64>>(),
1432                [2u64].into_iter().collect::<BTreeSet<u64>>(),
1433            ),
1434        )]);
1435        let err = apply_line_exemptions(&detail, &exempt(&[("shim.py", &[1, 2])])).unwrap_err();
1436        assert!(
1437            err.to_string().contains("uncovered lines") && err.to_string().contains("shim.py:1"),
1438            "got: {err}"
1439        );
1440    }
1441
1442    #[test]
1443    fn apply_line_exemptions_rejects_an_unmeasured_listed_line() {
1444        // A line not measured at all (a comment) can't be exempted either.
1445        let detail = BTreeMap::from([(
1446            "w.py".to_string(),
1447            (
1448                [2u64].into_iter().collect::<BTreeSet<u64>>(),
1449                [2u64].into_iter().collect::<BTreeSet<u64>>(),
1450            ),
1451        )]);
1452        let err = apply_line_exemptions(&detail, &exempt(&[("w.py", &[9])])).unwrap_err();
1453        assert!(err.to_string().contains("w.py:9"), "got: {err}");
1454    }
1455
1456    #[test]
1457    fn floor_outcome_matches_the_whole_tree_message() {
1458        assert_eq!(floor_outcome(7, 7, 100), Outcome::Pass);
1459        let out = floor_outcome(7, 8, 100);
1460        assert!(
1461            matches!(&out, Outcome::Fail(m) if m == "coverage 87.50% is below the required 100%"),
1462            "got: {out:?}"
1463        );
1464        // An all-exempt file leaves nothing to measure — vacuously a pass.
1465        assert_eq!(floor_outcome(0, 0, 100), Outcome::Pass);
1466    }
1467
1468    #[test]
1469    fn lift_exempt_lines_removes_exempt_lines_from_the_diff() {
1470        // The `--base` path drops a changed line that is line-exempt (lines 2-3 here),
1471        // leaving the rest of the diff to be judged; an exemption for an untouched file
1472        // is a no-op.
1473        let mut changed = changed(&[("shim.py", &[1, 2, 3, 4]), ("core.py", &[5])]);
1474        lift_exempt_lines(
1475            &mut changed,
1476            &exempt(&[("shim.py", &[2, 3]), ("gone.py", &[9])]),
1477        );
1478        assert_eq!(changed["shim.py"], [1, 4].into_iter().collect());
1479        assert_eq!(changed["core.py"], [5].into_iter().collect());
1480    }
1481}