Skip to main content

testing_conventions/
co_change.rs

1//! The commit-scoped `co-change` check (#33): a source file that changed in a
2//! git diff must change its colocated test too.
3//!
4//! Convention: when a source file is **modified** (e.g. a function removed from
5//! `foo.py`) or **deleted** in a commit range, its colocated test — the #15/#18
6//! pairing, `foo.py` → `foo_test.py`, `foo.ts` → `foo.test.ts` — must also be in
7//! that diff. This catches edits and removals that leave the test silently stale.
8//! *Added* source files are not subjects: brand-new code is the coverage floor's
9//! job, not this one. A **deletion** is a subject only if the source *had* a
10//! colocated test in the base tree — a package barrel (`__init__.py`, `index.ts`)
11//! with no sibling test can be deleted without one appearing in the diff, so it is
12//! not flagged and needs no exemption (#252).
13//!
14//! [`stale_sources`] walks `git diff --name-status <base>...HEAD` for a
15//! [`Language`] and returns every changed source file whose colocated test did
16//! not co-change. A file listed in the config `exempt` table (rule `co-change`)
17//! is a deliberate, reason-required omission. Rust has no sibling test file —
18//! units are inline `#[cfg(test)]` in the same `.rs` — so the rule is
19//! Python/TypeScript only (the CLI rejects `--language rust`).
20
21use std::collections::BTreeSet;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24
25use anyhow::{bail, Context, Result};
26
27use crate::colocated_test::Language;
28
29/// Every source file changed in `repo`'s `<base>...HEAD` diff whose colocated
30/// test did not also change — the stale-test risks — sorted for deterministic
31/// output.
32///
33/// A source file is a subject when it was **modified** (and still holds code), or
34/// **deleted** while it *had* a colocated test in the base tree (the test now at
35/// risk of being orphaned); an **added** file is not (new code is the coverage
36/// floor's concern), nor is a deleted barrel that never had a sibling test (#252).
37/// A subject whose `repo`-relative path is in `exempt` is a deliberate omission and
38/// is skipped. Everything else must have its colocated test (`foo.py` →
39/// `foo_test.py`, per `language`) somewhere in the same diff.
40///
41/// Returns an error if `git diff` fails — e.g. `base` names no resolvable ref —
42/// so an un-diffable range surfaces rather than silently passing as "clean".
43pub fn stale_sources(
44    repo: &Path,
45    base: &str,
46    language: Language,
47    exempt: &BTreeSet<String>,
48) -> Result<Vec<PathBuf>> {
49    let entries = changed_entries(repo, base)?;
50    // Every changed path, so a subject's expected test is a set lookup rather
51    // than a second walk of the diff.
52    let changed: BTreeSet<&str> = entries.iter().map(|(_, path)| path.as_str()).collect();
53
54    let mut stale = Vec::new();
55    for (status, rel) in &entries {
56        let path = Path::new(rel);
57        // A test file, a support file (Python `conftest.py`), or anything this
58        // language doesn't track is never a co-change subject.
59        if !language.tracks(path) || language.is_test(path) || language.is_support(path) {
60            continue;
61        }
62        let expected = language
63            .expected_test_path(path)
64            .to_string_lossy()
65            .replace('\\', "/");
66        // Only an edit or a removal can leave a test stale; a brand-new source is
67        // the coverage floor's concern, not this rule's.
68        let is_subject = match status {
69            Status::Modified => {
70                // An empty / comment-only file holds no logic, so editing it needs
71                // no test co-change — consistent with the colocated-test rule.
72                let contents = std::fs::read_to_string(repo.join(path))
73                    .with_context(|| format!("reading changed source `{rel}`"))?;
74                language.has_code(&contents)
75            }
76            // A deletion is a subject only if the source *had* a colocated test in
77            // the base tree — the test now at risk of being orphaned. A source that
78            // never had a sibling test (a package barrel: `__init__.py`, `index.ts`)
79            // can be removed without a test appearing in the diff, so it is not
80            // flagged and needs no exemption to delete it (#252). HEAD can't answer
81            // this — the file is gone — so we ask `base`.
82            Status::Deleted => test_exists_in_base(repo, base, &expected)?,
83            Status::Other => false,
84        };
85        if !is_subject || exempt.contains(rel) {
86            continue;
87        }
88        if !changed.contains(expected.as_str()) {
89            stale.push(path.to_path_buf());
90        }
91    }
92    stale.sort();
93    Ok(stale)
94}
95
96/// The diff status of a changed file, narrowed to what the rule acts on.
97enum Status {
98    /// `M` — content changed; a subject if it still holds code.
99    Modified,
100    /// `D` — removed; a subject only if the source had a colocated test in base
101    /// (its test should go too), never for a barrel that never had one (#252).
102    Deleted,
103    /// `A` (added) and the rest (`T`, …) — not a co-change subject.
104    Other,
105}
106
107impl Status {
108    /// The status from a `git diff --name-status` status field. With
109    /// `--no-renames` it is a single letter, so only the first char matters.
110    fn from_code(code: &str) -> Status {
111        match code.chars().next() {
112            Some('M') => Status::Modified,
113            Some('D') => Status::Deleted,
114            _ => Status::Other,
115        }
116    }
117}
118
119/// `true` when `rel` (a `repo`-relative path) exists as a blob in the `base` tree.
120///
121/// Used to tell a deleted source that once had a colocated test — its test should
122/// be removed too, so a stale leftover is worth flagging — from a barrel that never
123/// had one, which can be deleted without a test co-changing (#252). Runs
124/// `git cat-file -e <base>:./<rel>`: the `./` makes git resolve the path relative to
125/// `repo` (the diff's `--relative` root), matching the paths [`changed_entries`]
126/// returns, rather than the repo's top level. A missing blob exits non-zero (→
127/// `false`); the `base` ref itself already resolved for [`changed_entries`], so a
128/// non-zero exit here means "no such path in base", not a bad ref.
129fn test_exists_in_base(repo: &Path, base: &str, rel: &str) -> Result<bool> {
130    let spec = format!("{base}:./{rel}");
131    let output = Command::new("git")
132        .current_dir(repo)
133        .args(["cat-file", "-e", &spec])
134        .output()
135        .with_context(|| format!("running `git cat-file` in `{}`", repo.display()))?;
136    Ok(output.status.success())
137}
138
139/// The status + `repo`-relative path of every file changed in `<base>...HEAD`,
140/// via `git diff --name-status`.
141///
142/// `<base>...HEAD` is the merge-base diff — the changes this branch introduced
143/// (what a PR shows), not whatever else moved on `base`. Rename detection is off
144/// (`--no-renames`), so a rename shows as a delete + an add (each its own line of
145/// `<status>\t<path>`) and the deleted source is still held to its test;
146/// `--relative` scopes the diff to `repo` and reports paths relative to it.
147fn changed_entries(repo: &Path, base: &str) -> Result<Vec<(Status, String)>> {
148    let range = format!("{base}...HEAD");
149    let output = Command::new("git")
150        .current_dir(repo)
151        .args([
152            "diff",
153            "--name-status",
154            "--no-renames",
155            "--relative",
156            &range,
157        ])
158        .output()
159        .with_context(|| format!("running `git diff` in `{}`", repo.display()))?;
160    if !output.status.success() {
161        bail!(
162            "`git diff {range}` failed in `{}`: {}",
163            repo.display(),
164            String::from_utf8_lossy(&output.stderr).trim()
165        );
166    }
167    let stdout = String::from_utf8_lossy(&output.stdout);
168    let mut entries = Vec::new();
169    for line in stdout.lines() {
170        // `<status>\t<path>` — the status is a single letter with `--no-renames`.
171        if let Some((status, path)) = line.split_once('\t') {
172            let path = path.trim_end_matches('\r').replace('\\', "/");
173            entries.push((Status::from_code(status), path));
174        }
175    }
176    Ok(entries)
177}