Skip to main content

testing_conventions/
lib.rs

1pub mod agents;
2pub mod co_change;
3pub mod colocated_test;
4pub mod config;
5pub mod coverage;
6pub mod e2e;
7pub mod isolation;
8pub mod lint;
9pub mod mutation;
10pub mod packaging;
11pub mod patch_coverage;
12pub mod ts;
13pub mod violation;
14pub mod workflow;
15
16use std::path::{Path, PathBuf};
17
18use clap::{CommandFactory, Parser, Subcommand};
19
20#[derive(Parser, Debug)]
21#[command(
22    name = "testing-conventions",
23    version,
24    about = "Enforce testing conventions in libraries (Python, TypeScript, and Rust).",
25    long_about = None,
26)]
27pub struct Cli {
28    #[command(subcommand)]
29    command: Option<Command>,
30}
31
32#[derive(Subcommand, Debug)]
33enum Command {
34    /// Check the repository against its testing-conventions config.
35    Check,
36    /// Write the testing contract into the repository's agent context file
37    /// (#232): a marker-delimited, hash-versioned block in `AGENTS.md` that a
38    /// coding agent reads before writing code. Idempotent — re-running
39    /// refreshes the owned region and touches nothing outside it.
40    Install {
41        /// The agent context file to manage.
42        #[arg(default_value = "AGENTS.md")]
43        path: PathBuf,
44    },
45    /// Unit-test conventions.
46    Unit {
47        #[command(subcommand)]
48        rule: UnitRule,
49    },
50    /// Integration-test conventions.
51    Integration {
52        #[command(subcommand)]
53        rule: IntegrationRule,
54    },
55    /// Packaging conventions: test files must not ship in the built artifact.
56    Packaging {
57        /// Root of the built artifact to inspect (e.g. an unpacked wheel or `dist/`).
58        path: PathBuf,
59        /// Language convention to enforce (required).
60        #[arg(long, value_enum)]
61        language: colocated_test::Language,
62    },
63    /// Workflow guard (private — hidden from `--help`, #191): every `testing-conventions`
64    /// invocation in a CI workflow must name a subcommand this binary still exposes
65    /// (guards the `@v0` path, #92). Run from our own CI, not a documented consumer command;
66    /// it stays in the binary because the guard needs the in-process command tree.
67    #[command(hide = true)]
68    Workflow {
69        /// Workflow file (or a directory of them) to scan.
70        path: PathBuf,
71    },
72    /// End-to-end-test conventions.
73    E2e {
74        #[command(subcommand)]
75        command: E2eCommand,
76    },
77}
78
79/// Rules enforced on the unit-test suite (the README's "Unit" taxonomy).
80#[derive(Subcommand, Debug)]
81enum UnitRule {
82    /// Check that every source file has a colocated, matching-named unit test
83    /// (tree-wide presence). With `--base`, additionally run the commit-scoped
84    /// `co-change` check over `<base>...HEAD` (#33): a modified or deleted source
85    /// whose colocated test is not in the diff fails. Presence always runs;
86    /// `--base` *adds* the diff-scoped check.
87    ColocatedTest {
88        /// Directory to scan recursively.
89        path: PathBuf,
90        /// Language convention to enforce (required).
91        #[arg(long, value_enum)]
92        language: colocated_test::Language,
93        /// Opt-in commit-scoped co-change check (#33): diff `<base>...HEAD` and
94        /// also flag a modified or deleted source whose colocated test didn't
95        /// co-change. Absent means presence-only — there is no default. Python /
96        /// TypeScript only: `--base --language rust` is rejected (inline
97        /// `#[cfg(test)]` units have no sibling test to go stale).
98        #[arg(long)]
99        base: Option<String>,
100        /// testing-conventions config file providing the `exempt` list. Optional:
101        /// if the file is absent, no files are exempt.
102        #[arg(long, default_value = "testing-conventions.toml")]
103        config: PathBuf,
104    },
105    /// Check that the unit suite meets the configured coverage floor. With
106    /// `--base`, the same configured floor is measured over the `<base>...HEAD`
107    /// diff (the changed lines) instead of the whole tree (#162) — a changed line
108    /// below the floor fails, no matter how small the diff.
109    Coverage {
110        /// Directory whose unit suite is run and measured.
111        path: PathBuf,
112        /// Language convention to enforce (required).
113        #[arg(long, value_enum)]
114        language: colocated_test::Language,
115        /// Opt-in diff-scoped coverage (#162): diff `<base>...HEAD` and measure the
116        /// configured floor over only the changed lines, instead of the whole tree.
117        /// Absent means whole-tree — there is no default. This is the patch-scoped
118        /// check the old `unit patch-coverage` command did, re-homed onto the floor
119        /// it shares.
120        #[arg(long)]
121        base: Option<String>,
122        /// testing-conventions config file with the coverage thresholds and
123        /// `exempt` list. Optional: if the file — or its `[<language>].coverage`
124        /// table — is absent, the language's sane default floor is used and
125        /// nothing is exempt.
126        #[arg(long, default_value = "testing-conventions.toml")]
127        config: PathBuf,
128    },
129    /// Lint unit test files for isolation: mock every collaborator (Python, TypeScript, Rust).
130    Lint {
131        /// Crate root / source dir to scan recursively.
132        path: PathBuf,
133        /// Language convention to enforce (required).
134        #[arg(long, value_enum)]
135        language: isolation::Language,
136        /// testing-conventions config file providing the `exempt` list (waivers).
137        /// Optional: if the file is absent, nothing is waived.
138        #[arg(long, default_value = "testing-conventions.toml")]
139        config: PathBuf,
140    },
141    /// Run mutation testing over the unit suite and fail on any surviving mutant not
142    /// lifted by a `mutation` exemption — the rung above coverage (#201). The gate is
143    /// on by default (no report-only mode). All three languages (Python, TypeScript,
144    /// Rust) are at parity and wired into the reusable workflow as a diff-scoped,
145    /// PR-only job (#204).
146    Mutation {
147        /// Crate whose unit suite is mutated.
148        path: PathBuf,
149        /// Language convention to enforce (required): `python`, `typescript`, or `rust`.
150        #[arg(long, value_enum)]
151        language: colocated_test::Language,
152        /// Opt-in diff-scoping (#201): restrict to mutants on lines a `<base>...HEAD`
153        /// diff added or modified, via cargo-mutants' `--in-diff`. Absent means the
154        /// whole crate (slower).
155        #[arg(long)]
156        base: Option<String>,
157        /// testing-conventions config file providing the `exempt` list. Optional:
158        /// absent means nothing is exempt (every survivor must be killed).
159        #[arg(long, default_value = "testing-conventions.toml")]
160        config: PathBuf,
161        /// Path to the bundled TypeScript mutation adapter (`dist/mutation/main.js`), used
162        /// only by `--language typescript`. The npm launcher appends it; hidden because a
163        /// consumer never sets it by hand.
164        #[arg(long = "ts-mutation-adapter", hide = true)]
165        ts_adapter: Option<PathBuf>,
166    },
167}
168
169/// Languages the integration-test lints support — its own set (Python,
170/// TypeScript, Rust), distinct from the file-pairing `colocated_test::Language`,
171/// so adding Rust here doesn't touch the colocated-test/coverage rules.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
173pub enum IntegrationLintLanguage {
174    /// Python test files (`*_test.py`, `test_*.py`, `conftest.py`).
175    #[value(name = "python")]
176    Python,
177    /// TypeScript test files (`*.test.{ts,tsx,mts,cts}`).
178    #[value(name = "typescript")]
179    TypeScript,
180    /// Rust integration crates under `tests/`.
181    #[value(name = "rust")]
182    Rust,
183}
184
185/// Lints enforced on integration tests (mocking mechanism & style, and more to
186/// come). The README's "Integration" taxonomy.
187#[derive(Subcommand, Debug)]
188enum IntegrationRule {
189    /// Lint integration test files for mocking mechanism & style (Python, TypeScript, Rust).
190    Lint {
191        /// Directory to scan recursively for test files.
192        path: PathBuf,
193        /// Language convention to enforce (required).
194        #[arg(long, value_enum)]
195        language: IntegrationLintLanguage,
196        /// testing-conventions config file providing the `exempt` list (waivers).
197        /// Optional: if the file is absent, nothing is waived.
198        #[arg(long, default_value = "testing-conventions.toml")]
199        config: PathBuf,
200    },
201}
202
203/// E2E attestation commands (#17): record a local e2e run and (later, #68)
204/// verify in CI that the latest code commit is attested.
205#[derive(Subcommand, Debug)]
206enum E2eCommand {
207    /// Run the e2e suite and write a committed attestation naming the current commit.
208    Attest {
209        /// The e2e command to run (e.g. `pnpm run e2e`), executed via the shell.
210        command: String,
211    },
212    /// Verify the committed attestation names the latest code commit (the CI gate).
213    Verify {
214        /// Directory whose committed e2e-attestation.json is verified (default: current directory).
215        #[arg(default_value = ".")]
216        path: PathBuf,
217    },
218}
219
220pub fn run<I, T>(args: I) -> anyhow::Result<i32>
221where
222    I: IntoIterator<Item = T>,
223    T: Into<std::ffi::OsString> + Clone,
224{
225    let cli = Cli::try_parse_from(args)?;
226    match cli.command {
227        // The config-driven `check` umbrella isn't wired yet; the scaffold
228        // proves the wiring while individual rules land under their test-kind
229        // group (e.g. `unit colocated-test`).
230        Some(Command::Check) | None => Ok(0),
231        Some(Command::Unit { rule }) => match rule {
232            UnitRule::ColocatedTest {
233                path,
234                language,
235                base,
236                config,
237            } => run_unit_colocated_test(&path, language, base.as_deref(), &config),
238            UnitRule::Coverage {
239                path,
240                language,
241                base,
242                config,
243            } => run_unit_coverage(&path, language, base.as_deref(), &config),
244            UnitRule::Lint {
245                path,
246                language,
247                config,
248            } => run_unit_lint(&path, language, &config),
249            UnitRule::Mutation {
250                path,
251                language,
252                base,
253                config,
254                ts_adapter,
255            } => run_unit_mutation(
256                &path,
257                language,
258                base.as_deref(),
259                &config,
260                ts_adapter.as_deref(),
261            ),
262        },
263        Some(Command::Integration { rule }) => match rule {
264            IntegrationRule::Lint {
265                path,
266                language,
267                config,
268            } => run_integration_lint(&path, language, &config),
269        },
270        Some(Command::Packaging { path, language }) => run_packaging(&path, language),
271        Some(Command::Workflow { path }) => run_workflow(&path),
272        Some(Command::E2e { command }) => match command {
273            E2eCommand::Attest { command } => run_e2e_attest(&command),
274            E2eCommand::Verify { path } => run_e2e_verify(&path),
275        },
276        Some(Command::Install { path }) => {
277            agents::install(&path)?;
278            Ok(0)
279        }
280    }
281}
282
283/// The binary's own clap command tree — the source of truth for which subcommands
284/// it exposes. The `workflow` guard (#92) checks a workflow's invocations against
285/// it, so a renamed or removed subcommand is caught the moment they diverge.
286pub fn command() -> clap::Command {
287    Cli::command()
288}
289
290/// Run the unit colocated-test check over `root` for `language`. Always runs the
291/// tree-wide **presence** check (every source file has its colocated test; Rust:
292/// an inline `#[cfg(test)]` module). When `base` is `Some`, *additionally* runs the
293/// commit-scoped **co-change** check (#33) over `<base>...HEAD` — a modified or
294/// deleted source whose colocated test didn't co-change — and the run fails if
295/// either check does. Returns `0` only when both pass.
296///
297/// Presence loads the `colocated-test`-rule exemptions and co-change the
298/// `co-change`-rule exemptions from the config at `config_path` (no config file →
299/// no exemptions). `--base` rejects `--language rust`: Rust units are inline
300/// `#[cfg(test)]` in the same file, so a sibling test can't go stale (presence,
301/// without `--base`, still supports Rust).
302fn run_unit_colocated_test(
303    root: &Path,
304    language: colocated_test::Language,
305    base: Option<&str>,
306    config_path: &Path,
307) -> anyhow::Result<i32> {
308    // `--base` carries the co-change check, which rejects Rust the same way the
309    // standalone `unit co-change` did — before any work, so the message matches.
310    if base.is_some() && language == colocated_test::Language::Rust {
311        anyhow::bail!(
312            "`unit colocated-test --base` supports `--language python` / `typescript`; Rust \
313             units are inline `#[cfg(test)]` in the same file, so a sibling test can't go stale"
314        );
315    }
316    let presence_clean = report_colocated_presence(root, language, config_path)?;
317    let co_change_clean = match base {
318        Some(base) => report_co_change(root, base, language, config_path)?,
319        None => true,
320    };
321    Ok(if presence_clean && co_change_clean {
322        0
323    } else {
324        1
325    })
326}
327
328/// The tree-wide colocated-test **presence** check: every source file under `root`
329/// has its colocated unit test (Rust: an inline `#[cfg(test)]` module). Prints each
330/// orphan to stderr and returns `Ok(false)` when any are found, `Ok(true)` when the
331/// tree is clean. The `colocated-test`-rule exemptions from the config at
332/// `config_path` lift a file (no config file → nothing exempt).
333fn report_colocated_presence(
334    root: &Path,
335    language: colocated_test::Language,
336    config_path: &Path,
337) -> anyhow::Result<bool> {
338    let exempt = colocated_test_exemptions(root, language, config_path)?;
339    let orphans = match language {
340        // Rust units are inline `#[cfg(test)]` modules, so "colocated" means a test
341        // module in the same file, not a sibling file (#40).
342        colocated_test::Language::Rust => colocated_test::missing_inline_tests(root, &exempt)?,
343        _ => colocated_test::missing_unit_tests(root, language, &exempt)?,
344    };
345    if orphans.is_empty() {
346        return Ok(true);
347    }
348    let (label, summary) = match language {
349        colocated_test::Language::Rust => (
350            "missing inline `#[cfg(test)]` tests",
351            "source file(s) with testable code but no inline `#[cfg(test)]` module \
352             (add an inline test module, or an `exempt` entry with a reason)",
353        ),
354        _ => (
355            "missing colocated unit test",
356            "source file(s) missing a colocated unit test \
357             (add a colocated test, or an `exempt` entry with a reason)",
358        ),
359    };
360    for orphan in &orphans {
361        eprintln!("{label}: {}", orphan.display());
362    }
363    eprintln!("error: {} {summary}", orphans.len());
364    Ok(false)
365}
366
367/// The `colocated-test`-rule exempt paths for `language`, resolved (and validated)
368/// from the config at `config_path`. A missing config file means no exemptions —
369/// the check still runs, just with nothing exempted.
370fn colocated_test_exemptions(
371    root: &Path,
372    language: colocated_test::Language,
373    config_path: &Path,
374) -> anyhow::Result<std::collections::BTreeSet<String>> {
375    if !config_path.exists() {
376        return Ok(std::collections::BTreeSet::new());
377    }
378    let config = config::load_config(config_path)?;
379    config::resolve_exempt(
380        root,
381        config.exemptions(language),
382        config::Rule::ColocatedTest,
383    )
384}
385
386/// The commit-scoped **co-change** check (#33) over `root`, diffing `<base>...HEAD`:
387/// every modified or deleted source whose colocated test didn't co-change. Prints
388/// each stale source to stderr and returns `Ok(false)` when any are found,
389/// `Ok(true)` when clean.
390///
391/// Loads the `co-change`-rule exemptions from the config at `config_path` (no
392/// config file → no exemptions); an exempt source needn't co-change. The caller
393/// rejects `--language rust` before this runs: Rust units are inline `#[cfg(test)]`
394/// in the same file, so a sibling test can't go stale.
395fn report_co_change(
396    root: &Path,
397    base: &str,
398    language: colocated_test::Language,
399    config_path: &Path,
400) -> anyhow::Result<bool> {
401    let exempt = co_change_exemptions(root, language, config_path)?;
402    let stale = co_change::stale_sources(root, base, language, &exempt)?;
403    if stale.is_empty() {
404        return Ok(true);
405    }
406    for source in &stale {
407        eprintln!(
408            "source changed without its colocated test: {}",
409            source.display()
410        );
411    }
412    eprintln!(
413        "error: {} source file(s) changed without their colocated test co-changing \
414         (update the test, or add an `exempt` entry with a reason)",
415        stale.len()
416    );
417    Ok(false)
418}
419
420/// The `co-change`-rule exempt paths for `language`, resolved (and validated)
421/// from the config at `config_path`. A missing config file means no exemptions —
422/// every changed source must co-change its test.
423fn co_change_exemptions(
424    root: &Path,
425    language: colocated_test::Language,
426    config_path: &Path,
427) -> anyhow::Result<std::collections::BTreeSet<String>> {
428    if !config_path.exists() {
429        return Ok(std::collections::BTreeSet::new());
430    }
431    let config = config::load_config(config_path)?;
432    config::resolve_exempt(root, config.exemptions(language), config::Rule::CoChange)
433}
434
435/// Split a resolved exempt-scope map (#226) into the whole-file paths and the
436/// line-scoped sets — the two shapes the `coverage` / `mutation` measure functions
437/// take. A [`config::LineScope::WholeFile`] becomes a path in the first vec; a
438/// [`config::LineScope::Lines`] a `path → lines` entry in the second map.
439fn split_scopes(
440    scopes: std::collections::BTreeMap<String, config::LineScope>,
441) -> (
442    Vec<String>,
443    std::collections::BTreeMap<String, std::collections::BTreeSet<u32>>,
444) {
445    let mut whole_file = Vec::new();
446    let mut line_scoped = std::collections::BTreeMap::new();
447    for (path, scope) in scopes {
448        match scope {
449            config::LineScope::WholeFile => whole_file.push(path),
450            config::LineScope::Lines(lines) => {
451                line_scoped.insert(path, lines);
452            }
453        }
454    }
455    (whole_file, line_scoped)
456}
457
458/// Run the unit-test coverage check over `root` for `language`, enforcing the
459/// floor from the config at `config_path`. Returns `0` when the floor is met,
460/// `1` otherwise.
461///
462/// With `base` set, the same configured floor is measured over the
463/// `<base>...HEAD` diff (the changed lines) rather than the whole tree (#162),
464/// via the diff-scoped [`patch_coverage::measure`] / `measure_typescript` /
465/// `measure_rust`; without it, the whole-tree [`coverage::measure`] family runs.
466///
467/// Coverage is zero-config by default for Python and TypeScript (#80): a missing
468/// config file — or a config with no `[<language>].coverage` table — falls back to
469/// the language's sane default floor ([`config::PythonCoverage::default`] /
470/// [`config::TypeScriptCoverage::default`]), the same way `unit colocated-test` and
471/// `integration lint` treat an absent config as "nothing exempt". A present
472/// `coverage` table overrides the default; `coverage`-rule exemptions still apply.
473/// Rust (#206) is zero-config too: a missing `[rust].coverage` table falls back to
474/// [`config::RustCoverage::default`] (`lines = 100`, `regions` opt-in, no branch).
475fn run_unit_coverage(
476    root: &Path,
477    language: colocated_test::Language,
478    base: Option<&str>,
479    config_path: &Path,
480) -> anyhow::Result<i32> {
481    let config = if config_path.exists() {
482        config::load_config(config_path)?
483    } else {
484        config::Config::default()
485    };
486    let outcome = match language {
487        colocated_test::Language::Python => {
488            let python = config.python.unwrap_or_default();
489            let coverage = python.coverage.unwrap_or_default();
490            let thresholds = coverage::Thresholds {
491                fail_under: coverage.fail_under,
492                branch: coverage.branch,
493            };
494            let (omit, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
495                root,
496                &python.exempt,
497                config::Rule::Coverage,
498            )?);
499            match base {
500                Some(base) => {
501                    patch_coverage::measure(root, base, thresholds, &omit, &exempt_lines)?
502                }
503                None if exempt_lines.is_empty() => coverage::measure(root, thresholds, &omit)?,
504                None => {
505                    patch_coverage::measure_line_exempt(root, thresholds, &omit, &exempt_lines)?
506                }
507            }
508        }
509        colocated_test::Language::TypeScript => {
510            let typescript = config.typescript.unwrap_or_default();
511            let coverage = typescript.coverage.unwrap_or_default();
512            let thresholds = coverage::TypeScriptThresholds {
513                lines: coverage.lines,
514                branches: coverage.branches,
515                functions: coverage.functions,
516                statements: coverage.statements,
517            };
518            let (exclude, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
519                root,
520                &typescript.exempt,
521                config::Rule::Coverage,
522            )?);
523            match base {
524                Some(base) => patch_coverage::measure_typescript(
525                    root,
526                    base,
527                    thresholds,
528                    &exclude,
529                    &exempt_lines,
530                )?,
531                None if exempt_lines.is_empty() => {
532                    coverage::measure_typescript(root, thresholds, &exclude)?
533                }
534                None => patch_coverage::measure_line_exempt_typescript(
535                    root,
536                    thresholds,
537                    &exclude,
538                    &exempt_lines,
539                )?,
540            }
541        }
542        colocated_test::Language::Rust => {
543            let rust = config.rust.unwrap_or_default();
544            // Zero-config (#206): a missing `[rust].coverage` table falls back to the
545            // default Rust floor (`lines = 100`, with `regions` opt-in and no branch
546            // component) — matching Python/TypeScript — rather than erroring for a
547            // required table. A present table overrides it.
548            let coverage = rust.coverage.unwrap_or_default();
549            let thresholds = coverage::RustThresholds {
550                regions: coverage.regions,
551                lines: coverage.lines,
552                functions: coverage.functions,
553                branch: coverage.branch,
554            };
555            let (ignore, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
556                root,
557                &rust.exempt,
558                config::Rule::Coverage,
559            )?);
560            match base {
561                Some(base) => patch_coverage::measure_rust(
562                    root,
563                    base,
564                    thresholds,
565                    &ignore,
566                    &exempt_lines,
567                    &rust.features,
568                )?,
569                None if exempt_lines.is_empty() => {
570                    coverage::measure_rust(root, thresholds, &ignore, &rust.features)?
571                }
572                None => patch_coverage::measure_line_exempt_rust(
573                    root,
574                    thresholds,
575                    &ignore,
576                    &exempt_lines,
577                    &rust.features,
578                )?,
579            }
580        }
581    };
582    match outcome {
583        coverage::Outcome::Pass => Ok(0),
584        coverage::Outcome::Fail(reason) => {
585            eprintln!("error: coverage check failed — {reason}");
586            Ok(1)
587        }
588    }
589}
590
591/// Run `unit mutation` over `root` (#201, #202): run the per-language engine and fail
592/// on any surviving mutant not lifted by a `mutation` exemption.
593///
594/// The gate is **on by default and binary** — "no *unexplained* surviving mutant":
595/// every survivor must be killed with an assertion, or lifted by a reason-required
596/// `[[<language>.exempt]] rules = ["mutation"]` for an equivalent / deliberately-defensive
597/// mutation. There is no percentage floor (equivalent mutants make one unreachable)
598/// and no report-only mode — the only loosening is a reasoned, per-file exemption.
599/// All three languages are wired: Rust (cargo-mutants), TypeScript (Stryker), and
600/// Python (cosmic-ray). `--base` scopes the run to the diff.
601fn run_unit_mutation(
602    root: &Path,
603    language: colocated_test::Language,
604    base: Option<&str>,
605    config_path: &Path,
606    ts_adapter: Option<&Path>,
607) -> anyhow::Result<i32> {
608    let config = if config_path.exists() {
609        config::load_config(config_path)?
610    } else {
611        config::Config::default()
612    };
613    let survivors = match language {
614        colocated_test::Language::Rust => {
615            let rust = config.rust.unwrap_or_default();
616            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
617                root,
618                &rust.exempt,
619                config::Rule::Mutation,
620            )?);
621            mutation::measure_rust(root, &exempt, &exempt_lines, base, &rust.features)?
622        }
623        colocated_test::Language::TypeScript => {
624            let typescript = config.typescript.unwrap_or_default();
625            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
626                root,
627                &typescript.exempt,
628                config::Rule::Mutation,
629            )?);
630            // The npm launcher appends `--ts-mutation-adapter`; its absence means the binary
631            // was run directly, not through the published CLI.
632            let adapter = ts_adapter.ok_or_else(|| {
633                anyhow::anyhow!(
634                    "the TypeScript mutation adapter path is required: pass \
635                     `--ts-mutation-adapter <path>`. The npm `testing-conventions` CLI appends it \
636                     automatically — run the rule through that CLI, not the raw binary."
637                )
638            })?;
639            mutation::measure_typescript(root, &exempt, &exempt_lines, base, adapter)?
640        }
641        colocated_test::Language::Python => {
642            let python = config.python.unwrap_or_default();
643            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
644                root,
645                &python.exempt,
646                config::Rule::Mutation,
647            )?);
648            mutation::measure_python(root, &exempt, &exempt_lines, base)?
649        }
650    };
651    if survivors.is_empty() {
652        println!("unit mutation: no surviving mutants — every mutation was caught");
653        return Ok(0);
654    }
655
656    eprintln!(
657        "error: {} unexplained surviving mutant(s) — kill each with an assertion, or lift an \
658         equivalent/defensive one with a reason-required `[[<language>.exempt]] rules = [\"mutation\"]`:",
659        survivors.len()
660    );
661    for survivor in &survivors {
662        eprintln!(
663            "  {}:{}: {}",
664            survivor.file, survivor.line, survivor.description
665        );
666    }
667    Ok(1)
668}
669
670/// Run the `unit lint` check over `root` for `language` — the unit-suite
671/// isolation lints (`unmocked-collaborator`, `untyped-mock`, `no-out-of-module-call`,
672/// `no-out-of-module-import`) — printing each violation to stderr as
673/// `path:line: rule — message` and returning `1` when any are found, `0` otherwise.
674fn run_unit_lint(
675    root: &Path,
676    language: isolation::Language,
677    config_path: &Path,
678) -> anyhow::Result<i32> {
679    let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
680        isolation::Language::Rust => (isolation::find_violations(root)?, |c| c.rust_exemptions()),
681        isolation::Language::TypeScript => (ts::find_unit_violations(root)?, |c| {
682            c.exemptions(colocated_test::Language::TypeScript)
683        }),
684        isolation::Language::Python => (lint::find_unit_isolation_violations(root)?, |c| {
685            c.exemptions(colocated_test::Language::Python)
686        }),
687    };
688    let violations = apply_waivers(raw, root, config_path, select)?;
689    if violations.is_empty() {
690        return Ok(0);
691    }
692    for v in &violations {
693        eprintln!(
694            "{}:{}: {} — {}",
695            v.file.display(),
696            v.line,
697            v.rule,
698            v.message
699        );
700    }
701    eprintln!("error: {} isolation violation(s)", violations.len());
702    Ok(1)
703}
704
705/// Run the integration-test lints over `root` for `language`, printing each
706/// violation to stderr as `path:line: rule — message` and returning `1` when any
707/// are found, `0` otherwise.
708fn run_integration_lint(
709    root: &Path,
710    language: IntegrationLintLanguage,
711    config_path: &Path,
712) -> anyhow::Result<i32> {
713    let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
714        IntegrationLintLanguage::Python => (lint::find_violations(root)?, |c| {
715            c.exemptions(colocated_test::Language::Python)
716        }),
717        IntegrationLintLanguage::TypeScript => (ts::find_integration_violations(root)?, |c| {
718            c.exemptions(colocated_test::Language::TypeScript)
719        }),
720        IntegrationLintLanguage::Rust => (isolation::find_integration_violations(root)?, |c| {
721            c.rust_exemptions()
722        }),
723    };
724    let violations = apply_waivers(raw, root, config_path, select)?;
725    if violations.is_empty() {
726        return Ok(0);
727    }
728    for v in &violations {
729        eprintln!(
730            "{}:{}: {} — {}",
731            v.file.display(),
732            v.line,
733            v.rule,
734            v.message
735        );
736    }
737    eprintln!("error: {} lint violation(s)", violations.len());
738    Ok(1)
739}
740
741/// Selects a language's `[[<lang>.exempt]]` table from a loaded config — the one
742/// varying piece between the `unit lint` and `integration lint` waiver paths.
743type ExemptSelect = fn(&config::Config) -> &[config::Exemption];
744
745/// Drop the violations waived by the config's `exempt` list (#32/#102). A
746/// violation is waived when its `rule` is a known [`config::Rule`] and its
747/// `root`-relative path is exempt for that rule. `exemptions` selects the
748/// language's `[[<lang>.exempt]]` table from the loaded config. A missing config
749/// file waives nothing; a reason-less or stale entry errors (via `load_config` /
750/// `resolve_exempt`), so the escape hatch can't silently rot.
751fn apply_waivers(
752    violations: Vec<lint::Violation>,
753    root: &Path,
754    config_path: &Path,
755    exemptions: ExemptSelect,
756) -> anyhow::Result<Vec<lint::Violation>> {
757    use std::collections::hash_map::Entry;
758
759    if !config_path.exists() {
760        return Ok(violations);
761    }
762    let config = config::load_config(config_path)?;
763    let exempt = exemptions(&config);
764    // Resolve each rule's exempt set once (and surface a stale entry as an error).
765    let mut resolved: std::collections::HashMap<config::Rule, std::collections::BTreeSet<String>> =
766        std::collections::HashMap::new();
767    let mut kept = Vec::new();
768    for violation in violations {
769        let waived = match config::Rule::from_id(violation.rule) {
770            Some(rule) => {
771                let exempt_paths = match resolved.entry(rule) {
772                    Entry::Occupied(entry) => entry.into_mut(),
773                    Entry::Vacant(entry) => {
774                        entry.insert(config::resolve_exempt(root, exempt, rule)?)
775                    }
776                };
777                violation
778                    .file
779                    .strip_prefix(root)
780                    .ok()
781                    .map(|rel| rel.to_string_lossy().replace('\\', "/"))
782                    .is_some_and(|rel| exempt_paths.contains(&rel))
783            }
784            None => false,
785        };
786        if !waived {
787            kept.push(violation);
788        }
789    }
790    Ok(kept)
791}
792
793/// Run the packaging check: inspect the built artifact at `artifact` for test
794/// files that must not ship (README "Packaging"), per `language`'s test-file
795/// globs.
796///
797/// `artifact` is either an already-unpacked directory or a packed artifact the
798/// rule unpacks itself — a Python wheel (`.whl`) today; the TypeScript (#73) and
799/// Rust (#74) archives follow. Returns `0` when no test file is present, `1`
800/// otherwise (after printing each offending path, relative to the artifact root).
801fn run_packaging(artifact: &Path, language: colocated_test::Language) -> anyhow::Result<i32> {
802    let globs = match language {
803        colocated_test::Language::Python => vec!["*_test.py".to_string()],
804        colocated_test::Language::TypeScript => vec!["*.test.*".to_string()],
805        // `#[cfg(test)]` units compile out for free; the only thing to keep out of
806        // the `.crate` source tarball is the crate-root integration `tests/` dir.
807        colocated_test::Language::Rust => vec!["tests/".to_string()],
808    };
809    let offenders = packaging::inspect(artifact, &globs)?;
810    if offenders.is_empty() {
811        return Ok(0);
812    }
813    for offender in &offenders {
814        eprintln!("test file in built artifact: {}", offender.display());
815    }
816    eprintln!(
817        "error: {} test file(s) present in the built artifact \
818         (they must be excluded from packaging)",
819        offenders.len()
820    );
821    Ok(1)
822}
823
824/// Run the workflow guard over `path` (a workflow file or directory): flag every
825/// `testing-conventions` invocation that names a subcommand this binary no longer
826/// exposes, printing each as `path:line: rule — message` and returning `1` when any
827/// are found, `0` otherwise.
828fn run_workflow(path: &Path) -> anyhow::Result<i32> {
829    let violations = workflow::check(path, &command())?;
830    if violations.is_empty() {
831        return Ok(0);
832    }
833    for v in &violations {
834        eprintln!(
835            "{}:{}: {} — {}",
836            v.file.display(),
837            v.line,
838            v.rule,
839            v.message
840        );
841    }
842    eprintln!(
843        "error: {} workflow invocation(s) name a subcommand this binary no longer exposes",
844        violations.len()
845    );
846    Ok(1)
847}
848
849/// Run `command` as an e2e suite and write a committed attestation naming the
850/// current commit (#67). Force-runs: the attestation is written regardless of
851/// the command's exit code, so this exits `0` once the attestation is recorded.
852fn run_e2e_attest(command: &str) -> anyhow::Result<i32> {
853    let repo = std::env::current_dir()?;
854    let attestation = e2e::attest(&repo, command)?;
855    println!(
856        "e2e attestation recorded for commit {} (command exited {})",
857        attestation.commit, attestation.exit_code
858    );
859    Ok(0)
860}
861
862/// Verify the committed e2e attestation names the latest code commit (#68) — the
863/// CI side of the nudge. Exits `0` when fresh; otherwise prints the actionable
864/// hint and exits `1`. Never runs e2e, never judges the recorded run.
865///
866/// `path` is the directory whose committed `e2e-attestation.json` is checked
867/// (#281) — the default `.` resolves against the current directory, so a
868/// no-argument call behaves exactly like the pre-#281 `current_dir()` read.
869/// Passing a package subdirectory scopes discovery to it, matching a call made
870/// with that directory as cwd.
871fn run_e2e_verify(path: &Path) -> anyhow::Result<i32> {
872    match e2e::verify(path)? {
873        e2e::Verification::Fresh => Ok(0),
874        e2e::Verification::Missing => {
875            eprintln!(
876                "e2e attestation missing — run `testing-conventions e2e attest '<your e2e command>'`"
877            );
878            Ok(1)
879        }
880        e2e::Verification::Stale { attested, latest } => {
881            eprintln!(
882                "e2e attestation out of date: attested {}, latest code commit {} — \
883                 run `testing-conventions e2e attest '<your e2e command>'`",
884                &attested[..attested.len().min(7)],
885                &latest[..latest.len().min(7)]
886            );
887            Ok(1)
888        }
889    }
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895
896    #[test]
897    fn no_args_returns_ok_zero() {
898        assert_eq!(run(["testing-conventions"]).unwrap(), 0);
899    }
900
901    #[test]
902    fn check_returns_ok_zero() {
903        assert_eq!(run(["testing-conventions", "check"]).unwrap(), 0);
904    }
905
906    #[test]
907    fn unknown_flag_errors() {
908        assert!(run(["testing-conventions", "--bogus"]).is_err());
909    }
910
911    #[test]
912    fn help_flag_returns_clap_display_help() {
913        let err = run(["testing-conventions", "--help"]).expect_err("--help should bubble");
914        let clap_err = err
915            .downcast_ref::<clap::Error>()
916            .expect("error should be a clap::Error");
917        assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayHelp);
918    }
919
920    #[test]
921    fn version_flag_returns_clap_display_version() {
922        let err = run(["testing-conventions", "--version"]).expect_err("--version should bubble");
923        let clap_err = err
924            .downcast_ref::<clap::Error>()
925            .expect("error should be a clap::Error");
926        assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayVersion);
927    }
928}