From da31f4949afb30e6ded41759b10e99435a56d902 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:24 -0800 Subject: [PATCH 1/8] craft-xtask: add the gate's step runner, slot lock and per-step report A library for the apps' cargo xtask binaries. Each app keeps its xtask binary, step list and policy, and calls the library. - runner: run_steps runs the steps in order, stops at the first failure and prints the ok, FAIL and skip summary. root takes the caller's manifest directory and returns an error instead of panicking. The test commands from nextest_or_test and doctest pass --workspace --exclude , so a test build does not rebuild the running xtask executable (storytold/craft-common-actions#185). cargo test is the default; nextest is opt-in with a fallback. A Cancel flag stops the run, and run_cancelable ends the child's process group or tree. - lock (feature): 1 to 64 slots held across processes with file locks in a caller-chosen directory. A slot count outside 1 to 64 is an error on try_acquire, acquire and holders before any file is opened. Owner files are read to at most 4096 bytes, holders lists only slots whose lock is held, and waiting can be canceled. - report (feature): schema 1 JSON with step, command, status and duration_ms per step, written with craft-atomic so a failed write keeps the previous report. It is written while the run holds its slot; a run that does not take its slot writes no report. From DesignCraft xtask/src/main.rs (8b169f8e) and LightCraft xtask/src/ci_lock.rs and ci.rs (25ffe3e5); LightCraft's two lock tests move in. DesignCraft and LightCraft are the planned consumers; no app switches here. --- Cargo.lock | 9 + Cargo.toml | 1 + README.md | 1 + crates/xtask/Cargo.toml | 25 ++ crates/xtask/README.md | 113 +++++ crates/xtask/src/lib.rs | 50 +++ crates/xtask/src/lock.rs | 333 +++++++++++++++ crates/xtask/src/report.rs | 164 ++++++++ crates/xtask/src/runner.rs | 819 +++++++++++++++++++++++++++++++++++++ 9 files changed, 1515 insertions(+) create mode 100644 crates/xtask/Cargo.toml create mode 100644 crates/xtask/README.md create mode 100644 crates/xtask/src/lib.rs create mode 100644 crates/xtask/src/lock.rs create mode 100644 crates/xtask/src/report.rs create mode 100644 crates/xtask/src/runner.rs diff --git a/Cargo.lock b/Cargo.lock index c11a134ae5..ba2b91439c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2839,6 +2839,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xtask" +version = "0.1.0" +dependencies = [ + "craft-atomic", + "serde_json", + "tempfile", +] + [[package]] name = "craft-y4m" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..464b73532e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ kurbo = "0.13" thiserror = "2" craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } diff --git a/README.md b/README.md index c6e95bd4f9..34bba45518 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml new file mode 100644 index 0000000000..6b561b543b --- /dev/null +++ b/crates/xtask/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "craft-xtask" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" + +[lints] +workspace = true + +[features] +default = [] +# One-at-a-time (or N-at-a-time) gate runs per machine, through file locks in a caller-chosen folder. +lock = [] +# The per-step JSON report, replaced atomically. +report = ["dep:serde_json", "dep:craft-atomic"] + +[dependencies] +craft-atomic = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/xtask/README.md b/crates/xtask/README.md new file mode 100644 index 0000000000..75228c3d66 --- /dev/null +++ b/crates/xtask/README.md @@ -0,0 +1,113 @@ +# craft-xtask + +A library for the Craft apps' `cargo xtask` binaries. Each app keeps its own `xtask` binary, command +dispatch, step list, test targets and app-only commands, and calls this crate with its own policy. +The crate is native only and is a dependency of an app's `xtask` package only. + +| Module | Feature | Contents | +|---|---|---| +| `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | +| `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | +| `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | + +No feature is on by default. `report` adds `serde_json` and `craft-atomic`. + +## Use + +```rust,no_run +use std::path::Path; +use craft_xtask::runner::{self, RunOptions, Step, TestMode}; + +fn ci() -> Result<(), String> { + let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; + let mut steps = vec![ + Step::new("fmt", |log| { + let mut c = runner::cargo(&root); + c.args(["fmt", "--all", "--", "--check"]); + runner::run(c, log.command("cargo fmt --all -- --check")) + }), + Step::new("test", |log| { + let (c, label) = runner::nextest_or_test(&root, "xtask", TestMode::CargoTest, &["--lib", "--bins", "--tests"])?; + runner::run(c, log.command(&label)) + }), + ]; + runner::run_steps(&mut steps, &RunOptions::default())?; + Ok(()) +} +``` + +- `root` takes the app's own `CARGO_MANIFEST_DIR` and returns its parent, which must hold a + `Cargo.toml`. It returns an error instead of panicking. +- `nextest_or_test` and `doctest` build `cargo test --workspace --exclude ` (or + `cargo nextest run` with the same arguments). The exclusion keeps the test build from rebuilding the + running `xtask` executable, which Windows does not allow while it runs + ([storytold/craft-common-actions#185](https://github.com/storytold/craft-common-actions/issues/185)). + `TestMode::CargoTest` is the default and probes nothing. `TestMode::PreferNextest` runs nextest when + `cargo nextest --version` succeeds and otherwise runs `cargo test` with a note; the label names the + command that runs. +- Child processes inherit stdin, stdout and stderr. Their output is not decoded or stored. +- With `RunOptions::with_cancel`, a set `Cancel` flag stops the run before the next step, and + `run_cancelable` ends a running child with the processes it started and waits for it. On Unix the + child runs in its own process group, which `kill -s KILL` ends, so a terminal's Ctrl-C reaches only + the xtask and the app's Ctrl-C handler sets the flag. On Windows `taskkill /T /F` ends the tree. + +## Errors + +`runner::Error` is `Config` (a root without `Cargo.toml`, an invalid package name, a slot count +outside 1 to 64), `Step` (the step and the error it returned), `Canceled`, `Lock` (the lock directory +or file could not be opened or locked) or `Report` (the run passed but the report could not be +written). A report that cannot be written after a failed run is printed to stderr, and the run keeps +its `Step` error. + +## Lock + +`RunOptions::with_lock(LockConfig::new(dir, slots, owner_label))` takes one of `slots` lock files in +`dir` before the first step and releases it when `run_steps` returns. The OS releases a lock when its +process ends. A slot count of 0 or more than 64, or a poll interval (`with_poll`, 2 s by default) of zero, is an +error before any file is opened. Next to each +held lock file, an owner file holds the owner label, which waiting runs print; `holders` reads at +most 4096 bytes of each and leaves out an owner file whose slot is free, such as one a killed run left +behind. Where the lock files live, the environment variables that set them, and +whether a run uses a lock at all are the app's choice. + +## Report + +`RunOptions::with_report(path)` writes the report after the run, passed or not, and before the run +releases its lock slot. A run with a lock that does not take it (a configuration or lock error, or a +cancel while waiting) runs no step and writes no report. The report looks like this: + +```json +{ + "schema": 1, + "steps": [ + { "step": "fmt", "command": "cargo fmt --all -- --check", "status": "ok", "duration_ms": 812 }, + { "step": "test", "command": null, "status": "fail", "duration_ms": 4031 }, + { "step": "wasm", "command": null, "status": "skip", "duration_ms": null } + ] +} +``` + +`status` is `ok`, `fail`, `canceled` or `skip`. The file is staged beside `path` and renamed over it, +so a reader never sees a partial report, and a failed write leaves the previous report in place. +Machine, GPU, corpus and skip details stay in the app's own report. + +## Origin + +| Part | Source | +|---|---| +| `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | +| `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | +| `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | + +## Migration + +No app uses this crate yet. + +| App | Status | +|---|---| +| DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | +| LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | + +Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the +review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs new file mode 100644 index 0000000000..2ed8390e00 --- /dev/null +++ b/crates/xtask/src/lib.rs @@ -0,0 +1,50 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Library for the Craft apps' `cargo xtask` binaries. +//! +//! Each app keeps its own `xtask` binary, its command dispatch, its step list and its app-only +//! commands, and calls this crate with its own policy: +//! +//! - [`runner`]: the gate's step runner. [`runner::run_steps`] runs the steps in order, stops at the +//! first failure and prints the `ok`, `FAIL` and `skip` summary. [`runner::root`], +//! [`runner::cargo`], [`runner::run`] and [`runner::nextest_or_test`] build and run the commands. +//! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so +//! that gate runs in several checkouts of one machine take turns. +//! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! +//! ```no_run +//! use std::path::Path; +//! use craft_xtask::runner::{self, RunOptions, Step, TestMode}; +//! +//! fn ci() -> Result<(), runner::Error> { +//! // The app's own manifest directory, never this library's. +//! let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; +//! let mut steps = vec![ +//! Step::new("fmt", |log| { +//! let mut c = runner::cargo(&root); +//! c.args(["fmt", "--all", "--", "--check"]); +//! runner::run(c, log.command("cargo fmt --all -- --check")) +//! }), +//! Step::new("test", |log| { +//! let (c, label) = runner::nextest_or_test(&root, "xtask", TestMode::CargoTest, &["--lib", "--bins", "--tests"])?; +//! runner::run(c, log.command(&label)) +//! }), +//! ]; +//! runner::run_steps(&mut steps, &RunOptions::default()).map(|_| ()) +//! } +//! ``` + +#[cfg(feature = "lock")] +pub mod lock; +#[cfg(feature = "report")] +pub mod report; +pub mod runner; + +/// Keeps the tests that start child processes apart from the tests that check whether a slot is free. +/// A child holds copies of the parent's open files, and so its file locks, until it starts its program. +#[cfg(test)] +pub(crate) fn spawn_guard() -> std::sync::MutexGuard<'static, ()> { + static GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(()); + GUARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/crates/xtask/src/lock.rs b/crates/xtask/src/lock.rs new file mode 100644 index 0000000000..965b71408d --- /dev/null +++ b/crates/xtask/src/lock.rs @@ -0,0 +1,333 @@ +//! A fixed number of gate runs at a time on one machine. +//! +//! A gate run builds the workspace several times with one job per CPU, and several checkouts running +//! it at once slow each other down. [`acquire`] takes one of `slots` lock files in a directory the app +//! chooses (usually a per-user cache directory shared by every checkout) and holds it until the +//! [`Held`] guard is dropped. The operating system releases the lock when the process ends, crashed +//! or not. Runs that use the same directory and slot count share one pool; separate directories are +//! separate pools. Running without a lock is the caller's choice: it passes no [`LockConfig`]. +//! +//! Next to each held lock file, a `.owner` file holds the holder's label, which waiting runs print. + +use std::fs::{File, OpenOptions, TryLockError}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use crate::runner::{Cancel, Error}; + +/// The most slots a [`LockConfig`] can name. +pub const MAX_SLOTS: usize = 64; +/// The longest owner label [`holders`] reads from one owner file. +pub const MAX_OWNER_BYTES: u64 = 4096; +/// How often [`acquire`] tries again by default while every slot is held. +pub const DEFAULT_POLL: Duration = Duration::from_secs(2); +/// The longest [`acquire`] sleeps before it checks for cancellation again. +const CANCEL_CHECK: Duration = Duration::from_millis(50); + +/// Where the lock files are and how many runs may hold one at once. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockConfig { + /// The directory of the lock files. It is created when missing. + pub directory: PathBuf, + /// How many runs may hold a slot at once, from 1 to [`MAX_SLOTS`]. + pub slots: usize, + /// What waiting runs print about this run, for example `pid 123 in /src/app: cargo xtask ci`. + pub owner_label: String, + /// How often [`acquire`] tries again while every slot is held. + pub poll: Duration, +} + +impl LockConfig { + /// `slots` slots in `directory`, labeled `owner_label`, polled every [`DEFAULT_POLL`]. + pub fn new(directory: impl Into, slots: usize, owner_label: impl Into) -> Self { + Self { directory: directory.into(), slots, owner_label: owner_label.into(), poll: DEFAULT_POLL } + } + + /// Sets how often [`acquire`] tries again. + pub fn with_poll(mut self, poll: Duration) -> Self { + self.poll = poll; + self + } + + fn check(&self) -> Result<(), Error> { + if !(1..=MAX_SLOTS).contains(&self.slots) { + return Err(Error::Config(format!("lock: {} slots: the slot count must be from 1 to {MAX_SLOTS}", self.slots))); + } + if self.poll.is_zero() { + return Err(Error::Config("lock: the poll interval must be longer than zero".to_owned())); + } + Ok(()) + } +} + +/// A held slot. Dropping it releases the slot and removes its owner file. +#[derive(Debug)] +pub struct Held { + _file: File, + owner: PathBuf, +} + +impl Drop for Held { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.owner); + } +} + +fn slot_path(dir: &Path, slot: usize) -> PathBuf { + if slot == 0 { dir.join("ci.lock") } else { dir.join(format!("ci-{}.lock", slot + 1)) } +} + +fn owner_path(lock: &Path) -> PathBuf { + lock.with_extension("lock.owner") +} + +/// Takes the first free slot, or returns `None` when every slot is held. +pub fn try_acquire(config: &LockConfig) -> Result, Error> { + config.check()?; + let dir = &config.directory; + std::fs::create_dir_all(dir).map_err(|e| Error::Lock(format!("{}: {e}", dir.display())))?; + for slot in 0..config.slots { + let path = slot_path(dir, slot); + let file = + OpenOptions::new().create(true).truncate(false).write(true).open(&path).map_err(|e| Error::Lock(format!("{}: {e}", path.display())))?; + match file.try_lock() { + Ok(()) => return Ok(Some(Held { _file: file, owner: record_owner(&path, &config.owner_label) })), + Err(TryLockError::WouldBlock) => continue, + Err(TryLockError::Error(e)) => return Err(Error::Lock(format!("{}: {e}", path.display()))), + } + } + Ok(None) +} + +/// Writes the owner file of a slot this run holds. The owner is kept in a separate file because a +/// lock on Windows is mandatory, so other runs could not read the lock file itself. +fn record_owner(lock: &Path, label: &str) -> PathBuf { + let owner_file = owner_path(lock); + // A new file: an entry left under the name (a link planted in a shared lock directory) is removed, + // never written through. + let removed = std::fs::remove_file(&owner_file); + let written = OpenOptions::new().write(true).create_new(true).open(&owner_file).and_then(|mut f| f.write_all(label.as_bytes())); + if let (Err(e), Err(w)) = (&removed, &written) + && e.kind() != std::io::ErrorKind::NotFound + { + eprintln!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display()); + } + owner_file +} + +/// The owner labels of the held slots, as their holders wrote them, each cut to [`MAX_OWNER_BYTES`]. +/// +/// A slot whose lock file is missing or free is left out, also when a run that ended without dropping +/// its [`Held`] guard left its owner file behind. +pub fn holders(config: &LockConfig) -> Result, Error> { + config.check()?; + Ok((0..config.slots) + .map(|slot| slot_path(&config.directory, slot)) + .filter(|lock| is_held(lock)) + .filter_map(|lock| read_owner(&owner_path(&lock))) + .collect()) +} + +/// Whether a run holds the slot whose lock file is `lock`. The file is opened read-only and never +/// created; a free slot is locked shared for a moment and released when the file closes. +fn is_held(lock: &Path) -> bool { + match File::open(lock) { + Ok(file) => matches!(file.try_lock_shared(), Err(TryLockError::WouldBlock)), + Err(_) => false, + } +} + +fn read_owner(path: &Path) -> Option { + let mut bytes = Vec::new(); + File::open(path).ok()?.take(MAX_OWNER_BYTES).read_to_end(&mut bytes).ok()?; + let text = String::from_utf8_lossy(&bytes).trim().to_owned(); + (!text.is_empty()).then_some(text) +} + +/// Waits for a slot, printing the holders once while it waits. +/// +/// Returns [`Error::Canceled`] when `cancel` is set while waiting, and a configuration or lock error +/// before any wait. +pub fn acquire(config: &LockConfig, cancel: Option<&Cancel>) -> Result { + acquire_with(config, cancel, || { + eprintln!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots); + for h in holders(config).unwrap_or_default() { + eprintln!(" running: {h}"); + } + }) +} + +fn acquire_with(config: &LockConfig, cancel: Option<&Cancel>, on_wait: impl FnOnce()) -> Result { + if let Some(held) = try_acquire(config)? { + return Ok(held); + } + let waiting = Instant::now(); + on_wait(); + loop { + if !pause(config.poll, cancel) { + return Err(Error::Canceled { step: None }); + } + if let Some(held) = try_acquire(config)? { + eprintln!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64()); + return Ok(held); + } + } +} + +/// Sleeps for `poll`, checking `cancel` every [`CANCEL_CHECK`]. Returns `false` when canceled. A +/// `poll` too long for the clock to represent waits until canceled. +fn pause(poll: Duration, cancel: Option<&Cancel>) -> bool { + let until = Instant::now().checked_add(poll); + loop { + if cancel.is_some_and(Cancel::is_canceled) { + return false; + } + let left = match until { + Some(until) => until.saturating_duration_since(Instant::now()), + None => CANCEL_CHECK, + }; + if left.is_zero() { + return true; + } + std::thread::sleep(left.min(CANCEL_CHECK)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runner::{RunOptions, Step, run_steps_to}; + use std::sync::mpsc; + + fn config(dir: &Path, slots: usize, owner: &str) -> LockConfig { + LockConfig::new(dir, slots, owner).with_poll(Duration::from_millis(1)) + } + + #[test] + fn one_slot_is_exclusive_until_dropped() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let first = try_acquire(&config(dir.path(), 1, "first")).unwrap().expect("free slot"); + assert!(try_acquire(&config(dir.path(), 1, "second")).unwrap().is_none()); + assert_eq!(holders(&config(dir.path(), 1, "")).unwrap(), ["first"]); + drop(first); + assert!(holders(&config(dir.path(), 1, "")).unwrap().is_empty()); + assert!(try_acquire(&config(dir.path(), 1, "third")).unwrap().is_some()); + } + + #[test] + fn more_slots_admit_more_runs() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let a = try_acquire(&config(dir.path(), 2, "a")).unwrap(); + let b = try_acquire(&config(dir.path(), 2, "b")).unwrap(); + assert!(a.is_some() && b.is_some()); + assert!(try_acquire(&config(dir.path(), 2, "c")).unwrap().is_none()); + assert_eq!(holders(&config(dir.path(), 2, "")).unwrap(), ["a", "b"]); + } + + #[test] + fn slot_count_is_bounded() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + for slots in [0, MAX_SLOTS + 1, usize::MAX] { + let c = config(dir.path(), slots, "x"); + assert!(matches!(try_acquire(&c), Err(Error::Config(_))), "{slots}"); + assert!(matches!(holders(&c), Err(Error::Config(_))), "{slots}"); + assert!(matches!(acquire(&c, None), Err(Error::Config(_))), "{slots}"); + } + assert!(matches!(try_acquire(&config(dir.path(), 1, "x").with_poll(Duration::ZERO)), Err(Error::Config(_)))); + // Nothing was created for the rejected configurations. + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + + let one = try_acquire(&config(dir.path(), 1, "one")).unwrap(); + assert!(one.is_some()); + let all: Vec = (0..MAX_SLOTS - 1).filter_map(|_| try_acquire(&config(dir.path(), MAX_SLOTS, "n")).unwrap()).collect(); + assert_eq!(all.len(), MAX_SLOTS - 1); + assert!(try_acquire(&config(dir.path(), MAX_SLOTS, "full")).unwrap().is_none()); + } + + #[test] + fn owner_labels_are_read_within_the_limit() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let c = config(dir.path(), 1, ""); + let _held = try_acquire(&c).unwrap().expect("free slot"); + std::fs::write(owner_path(&slot_path(dir.path(), 0)), vec![b'x'; 3 * MAX_OWNER_BYTES as usize]).unwrap(); + assert_eq!(holders(&c).unwrap(), ["x".repeat(MAX_OWNER_BYTES as usize)]); + } + + #[test] + fn owner_files_of_free_slots_are_not_holders() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let c = config(dir.path(), 2, ""); + // The first slot: a run that ended without dropping its guard left its lock and owner files. + std::fs::write(slot_path(dir.path(), 0), b"").unwrap(); + std::fs::write(owner_path(&slot_path(dir.path(), 0)), b"crashed").unwrap(); + // The second slot: an owner file with no lock file. + std::fs::write(owner_path(&slot_path(dir.path(), 1)), b"orphan").unwrap(); + assert!(holders(&c).unwrap().is_empty()); + + // A live holder of the first slot is listed, and the free second slot still is not. + let _held = try_acquire(&config(dir.path(), 2, "live")).unwrap().expect("free slot"); + assert_eq!(holders(&c).unwrap(), ["live"]); + } + + #[test] + fn lock_wait_cancels_and_releases() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let holder = try_acquire(&config(dir.path(), 1, "holder")).unwrap().expect("free slot"); + + // A waiter stops waiting when canceled, also with a poll interval the clock cannot add. + for poll in [Duration::from_millis(1), Duration::MAX] { + let cancel = Cancel::new(); + let (waiting, waited) = mpsc::channel(); + let waiter = { + let (c, cancel) = (config(dir.path(), 1, "waiter").with_poll(poll), cancel.clone()); + std::thread::spawn(move || acquire_with(&c, Some(&cancel), || waiting.send(()).unwrap()).map(drop)) + }; + waited.recv().unwrap(); + cancel.cancel(); + assert_eq!(waiter.join().unwrap(), Err(Error::Canceled { step: None }), "{poll:?}"); + } + + // A waiter gets the slot once the holder drops it. + let (waiting, waited) = mpsc::channel(); + let waiter = { + let c = config(dir.path(), 1, "next"); + std::thread::spawn(move || acquire_with(&c, None, || waiting.send(()).unwrap()).map(drop)) + }; + waited.recv().unwrap(); + drop(holder); + assert_eq!(waiter.join().unwrap(), Ok(())); + + // A run that fails or is canceled releases its slot when it returns. + let c = config(dir.path(), 1, "run"); + let mut failing = vec![Step::new("test", |_| Err("failed".to_owned()))]; + let result = run_steps_to(&mut failing, &RunOptions::default().with_lock(c.clone()), &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Step { .. }))); + assert!(try_acquire(&c).unwrap().is_some()); + + let cancel = Cancel::new(); + cancel.cancel(); + let mut canceled = vec![Step::new("test", |_| Ok(()))]; + let options = RunOptions::default().with_lock(c.clone()).with_cancel(cancel); + let result = run_steps_to(&mut canceled, &options, &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Canceled { .. }))); + assert!(try_acquire(&c).unwrap().is_some()); + + // A run waiting for a held slot ends when canceled, without running a step. + let held = try_acquire(&c).unwrap().expect("free slot"); + let cancel = Cancel::new(); + cancel.cancel(); + let mut never = vec![Step::new("test", |_| Err("ran".to_owned()))]; + let options = RunOptions::default().with_lock(c.clone()).with_cancel(cancel); + let result = run_steps_to(&mut never, &options, &mut Vec::new(), &mut Vec::new()); + assert_eq!(result, Err(Error::Canceled { step: None })); + drop(held); + } +} diff --git a/crates/xtask/src/report.rs b/crates/xtask/src/report.rs new file mode 100644 index 0000000000..f876d06f99 --- /dev/null +++ b/crates/xtask/src/report.rs @@ -0,0 +1,164 @@ +//! The per-step JSON report of a gate run. +//! +//! Schema 1 holds the schema number and one object per step, in run order: +//! +//! ```json +//! { +//! "schema": 1, +//! "steps": [ +//! { "step": "fmt", "command": "cargo fmt --all -- --check", "status": "ok", "duration_ms": 812 }, +//! { "step": "test", "command": null, "status": "fail", "duration_ms": 4031 }, +//! { "step": "wasm", "command": null, "status": "skip", "duration_ms": null } +//! ] +//! } +//! ``` +//! +//! `status` is `ok`, `fail`, `canceled` or `skip`. `command` is `null` when the step recorded none, +//! and `duration_ms` is `null` for a step that did not start. Machine, GPU and other app-specific +//! details stay in the app's own report. +//! +//! The file is replaced atomically with `craft_atomic`: a reader sees the previous complete report or +//! the new one, never a partial file, and a failed write leaves the previous report in place. + +use std::io; +use std::path::Path; + +use craft_atomic::{AtomicFs, RealFs, RenameRetry}; +use serde_json::{Value, json}; + +use crate::runner::StepRecord; + +/// The schema number the report carries. +pub const SCHEMA: u64 = 1; + +/// The report of `records` as JSON. +pub fn to_json(records: &[StepRecord]) -> Value { + let steps: Vec = records + .iter() + .map(|r| { + json!({ + "step": r.step, + "command": r.command, + "status": r.status.as_str(), + "duration_ms": r.duration.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)), + }) + }) + .collect(); + json!({ "schema": SCHEMA, "steps": steps }) +} + +/// Writes the report of `records` to `path`, replacing any earlier report atomically. +pub fn write(path: &Path, records: &[StepRecord]) -> io::Result<()> { + write_custom(&RealFs, RenameRetry::platform(), path, records) +} + +fn write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, records: &[StepRecord]) -> io::Result<()> { + let mut bytes = serde_json::to_vec_pretty(&to_json(records)).map_err(io::Error::other)?; + bytes.push(b'\n'); + craft_atomic::atomic_write_custom(fs, retry, path, &bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runner::{Error, RunOptions, Step, run_steps_to}; + use craft_atomic::NewFilePermissions; + use std::fs::{File, Permissions}; + + /// The real file system with every rename failing. + struct FailingRename; + + impl AtomicFs for FailingRename { + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + RealFs.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { + RealFs.sync(file) + } + fn rename(&self, _from: &Path, _to: &Path) -> io::Result<()> { + Err(io::Error::other("injected rename failure")) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn set_permissions(&self, file: &File, perms: Permissions) -> io::Result<()> { + RealFs.set_permissions(file, perms) + } + } + + fn keys(v: &Value) -> Vec<&str> { + let mut k: Vec<&str> = v.as_object().expect("an object").keys().map(String::as_str).collect(); + k.sort_unstable(); + k + } + + #[test] + fn report_shape_and_atomic_replacement() { + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("ci.json"); + let mut steps = vec![ + Step::new("fmt", |log| { + log.command("cargo fmt --all -- --check"); + Ok(()) + }), + Step::new("test", |_| Err("exited with 101".to_owned())), + Step::new("wasm", |_| Ok(())).with_command("cargo check --target wasm32-unknown-unknown"), + ]; + let options = RunOptions::default().with_report(&path); + let result = run_steps_to(&mut steps, &options, &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Step { .. }))); + + let written = std::fs::read(&path).unwrap(); + let report: Value = serde_json::from_slice(&written).unwrap(); + assert_eq!(keys(&report), ["schema", "steps"]); + assert_eq!(report["schema"], 1); + let rows = report["steps"].as_array().unwrap(); + assert_eq!(rows.len(), 3); + for row in rows { + assert_eq!(keys(row), ["command", "duration_ms", "status", "step"]); + } + assert_eq!(rows[0]["step"], "fmt"); + assert_eq!(rows[0]["command"], "cargo fmt --all -- --check"); + assert_eq!(rows[0]["status"], "ok"); + assert!(rows[0]["duration_ms"].is_u64()); + assert_eq!(rows[1]["command"], Value::Null); + assert_eq!(rows[1]["status"], "fail"); + assert!(rows[1]["duration_ms"].is_u64()); + assert_eq!(rows[2]["status"], "skip"); + assert_eq!(rows[2]["command"], "cargo check --target wasm32-unknown-unknown"); + assert_eq!(rows[2]["duration_ms"], Value::Null); + + // A failed replacement keeps the previous complete report and returns the error. + let records = vec![StepRecord { step: "fmt".into(), command: None, status: crate::runner::Status::Ok, duration: None }]; + let no_retry = RenameRetry { attempts: 0, first_delay_ms: 0 }; + assert!(write_custom(&FailingRename, no_retry, &path, &records).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), written); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "a staging file was left behind"); + } + + #[test] + fn report_errors_never_pass_a_failed_run() { + let dir = tempfile::tempdir().expect("temporary directory"); + let unwritable = dir.path().join("missing").join("ci.json"); + let options = RunOptions::default().with_report(&unwritable); + + let mut passing = vec![Step::new("fmt", |_| Ok(()))]; + let mut out = Vec::new(); + let result = run_steps_to(&mut passing, &options, &mut out, &mut Vec::new()); + assert!(matches!(result, Err(Error::Report(_))), "{result:?}"); + let out = String::from_utf8_lossy(&out); + assert!(out.starts_with("\nCI summary:\n FAIL report: ") && out.ends_with("\n ok fmt\n") && !out.contains("passed"), "{out}"); + + let mut failing = vec![Step::new("fmt", |_| Err("bad".to_owned()))]; + let mut err = Vec::new(); + let result = run_steps_to(&mut failing, &options, &mut Vec::new(), &mut err); + assert_eq!(result, Err(Error::Step { step: "fmt".into(), cause: "bad".into() })); + assert!(String::from_utf8_lossy(&err).contains("report: ")); + } +} diff --git a/crates/xtask/src/runner.rs b/crates/xtask/src/runner.rs new file mode 100644 index 0000000000..459e9e8869 --- /dev/null +++ b/crates/xtask/src/runner.rs @@ -0,0 +1,819 @@ +//! The gate's step runner. +//! +//! An app builds its step list (`fmt`, `clippy`, `test` and its own checks) and passes it to +//! [`run_steps`], which runs the steps in order, stops at the first failure and prints a summary: +//! +//! ```text +//! CI summary: +//! ok fmt +//! FAIL clippy: cargo clippy --workspace --all-targets -- -D warnings: exited with exit status: 101 +//! skip test +//! ``` +//! +//! The workspace root comes from the caller ([`root`] takes the app's own xtask manifest directory), +//! and the test commands that [`nextest_or_test`] and [`doctest`] build exclude the running xtask +//! package, so that a test build never has to replace the `xtask` executable that is running it. +//! Child processes inherit stdout and stderr; their output is passed through as bytes and never +//! decoded or stored. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// How often [`run_cancelable`] checks a running child for exit or cancellation. +const CHILD_POLL: Duration = Duration::from_millis(50); + +/// Why a run did not pass. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The caller passed a configuration this crate cannot use (a root without `Cargo.toml`, an + /// invalid package name, a slot count outside 1 to 64). + Config(String), + /// A step returned an error. Later steps did not run. + Step { + /// The step's name. + step: String, + /// The error the step returned. + cause: String, + }, + /// The run was canceled, at the named step or before the first one. + Canceled { + /// The step that was canceled, or `None` when the run was canceled while waiting for a lock. + step: Option, + }, + /// The lock could not be set up or taken. + Lock(String), + /// The gate passed but its report could not be written. + Report(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Config(m) => f.write_str(m), + Error::Step { step, cause } => write!(f, "step `{step}` failed: {cause}"), + Error::Canceled { step: Some(step) } => write!(f, "canceled at step `{step}`"), + Error::Canceled { step: None } => f.write_str("canceled before the first step"), + Error::Lock(m) => write!(f, "lock: {m}"), + Error::Report(m) => write!(f, "report: {m}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// A cancellation flag shared between the run and whoever stops it (a Ctrl-C handler, a test). +#[derive(Debug, Clone, Default)] +pub struct Cancel(Arc); + +impl Cancel { + /// A flag that is not set. + pub fn new() -> Self { + Self::default() + } + + /// Sets the flag. Every clone sees it. + pub fn cancel(&self) { + self.0.store(true, Ordering::SeqCst); + } + + /// Whether [`Cancel::cancel`] has been called on this flag or a clone of it. + pub fn is_canceled(&self) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +/// What a running step records about itself. +#[derive(Debug, Default)] +pub struct StepLog { + command: Option, +} + +impl StepLog { + /// Records the command the step runs, for the report, and returns `label` so that it can be + /// passed on to [`run`]. + pub fn command<'s>(&mut self, label: &'s str) -> &'s str { + self.command = Some(label.to_owned()); + label + } +} + +/// A step's body. It returns the error to print in the summary. +pub type StepFn<'a> = Box Result<(), String> + 'a>; + +/// One step of a gate run. +pub struct Step<'a> { + /// The name shown in the heading, the summary and the report. + pub name: String, + /// The command shown in the report when the step does not record one itself. + pub command: Option, + /// The step's body. + pub run: StepFn<'a>, +} + +impl<'a> Step<'a> { + /// A step named `name` that runs `run`. + pub fn new(name: impl Into, run: impl FnMut(&mut StepLog) -> Result<(), String> + 'a) -> Self { + Self { name: name.into(), command: None, run: Box::new(run) } + } + + /// Sets the command shown in the report until the step records another one. + pub fn with_command(mut self, label: impl Into) -> Self { + self.command = Some(label.into()); + self + } +} + +impl fmt::Debug for Step<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Step").field("name", &self.name).field("command", &self.command).finish_non_exhaustive() + } +} + +/// How a step ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// The step passed. + Ok, + /// The step returned an error. + Fail, + /// The run was canceled before or while this step ran. + Canceled, + /// The step did not run because an earlier step failed or was canceled. + Skip, +} + +impl Status { + /// The status as the summary and the report write it: `ok`, `fail`, `canceled` or `skip`. + pub fn as_str(self) -> &'static str { + match self { + Status::Ok => "ok", + Status::Fail => "fail", + Status::Canceled => "canceled", + Status::Skip => "skip", + } + } +} + +/// The result of one step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StepRecord { + /// The step's name. + pub step: String, + /// The command the step recorded, if any. + pub command: Option, + /// How the step ended. + pub status: Status, + /// How long the step ran; `None` for a step that did not start. + pub duration: Option, +} + +/// Options for [`run_steps`]. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub struct RunOptions { + /// The word in each step heading (`=== ci: fmt ===`) and, in capitals, the summary (`CI summary:`). + pub title: String, + /// Stops the run when set: the current child is ended and no later step starts. + pub cancel: Option, + /// A slot to hold for the whole run; `None` runs without a lock. + #[cfg(feature = "lock")] + pub lock: Option, + /// Where to write the per-step JSON report; `None` writes none. + #[cfg(feature = "report")] + pub report: Option, +} + +impl Default for RunOptions { + fn default() -> Self { + Self { + title: "ci".to_owned(), + cancel: None, + #[cfg(feature = "lock")] + lock: None, + #[cfg(feature = "report")] + report: None, + } + } +} + +impl RunOptions { + /// Sets the heading and summary word. + pub fn with_title(mut self, title: impl Into) -> Self { + self.title = title.into(); + self + } + + /// Sets the cancellation flag. + pub fn with_cancel(mut self, cancel: Cancel) -> Self { + self.cancel = Some(cancel); + self + } + + /// Holds a slot of `lock` for the whole run. + #[cfg(feature = "lock")] + pub fn with_lock(mut self, lock: crate::lock::LockConfig) -> Self { + self.lock = Some(lock); + self + } + + /// Writes the per-step JSON report to `path` after the run, whether it passed or not. A run that + /// does not take its lock writes no report. + #[cfg(feature = "report")] + pub fn with_report(mut self, path: impl Into) -> Self { + self.report = Some(path.into()); + self + } + + fn is_canceled(&self) -> bool { + self.cancel.as_ref().is_some_and(Cancel::is_canceled) + } +} + +/// Runs `steps` in order and stops at the first failure. +/// +/// Each step's heading goes to stderr and the summary to stdout. With a lock configured, a slot is +/// taken before the first step and released when this function returns, whatever the outcome. With a +/// report configured, it is written after the run, passed or not, while the slot is still held. When +/// the lock is not taken (a configuration or lock error, or a cancel while waiting), no step runs and +/// no report is written. A report that cannot be written turns a passed run into [`Error::Report`]; a +/// failed run keeps its own error and the report error is printed. An empty list passes. +pub fn run_steps(steps: &mut [Step<'_>], options: &RunOptions) -> Result, Error> { + run_steps_to(steps, options, &mut io::stdout(), &mut io::stderr()) +} + +/// [`run_steps`] with the summary written to `out` and the headings to `err`. +pub fn run_steps_to(steps: &mut [Step<'_>], options: &RunOptions, out: &mut dyn Write, err: &mut dyn Write) -> Result, Error> { + // The slot stays held until the report is written, so a later run's report replaces this one. + // A run that did not take the lock writes no report, so it never replaces the report of a run + // that holds the slot. + let held = take_lock(options); + let (records, result) = match &held { + Ok(_) => { + let (records, result) = execute(steps, options, err); + let result = finish_report(&records, result, options, err); + (records, result) + } + Err(e) => (not_started(steps, Status::Skip), Err(e.clone())), + }; + print_summary(&records, &result, options, out); + drop(held); + result.map(|()| records) +} + +#[cfg(feature = "lock")] +fn take_lock(options: &RunOptions) -> Result, Error> { + options.lock.as_ref().map(|config| crate::lock::acquire(config, options.cancel.as_ref())).transpose() +} + +#[cfg(not(feature = "lock"))] +fn take_lock(_options: &RunOptions) -> Result<(), Error> { + Ok(()) +} + +#[cfg(feature = "report")] +fn finish_report(records: &[StepRecord], result: Result<(), Error>, options: &RunOptions, err: &mut dyn Write) -> Result<(), Error> { + let Some(path) = &options.report else { + return result; + }; + match (crate::report::write(path, records), result) { + (Ok(()), result) => result, + (Err(e), Ok(())) => Err(Error::Report(format!("{}: {e}", path.display()))), + (Err(e), Err(gate)) => { + let _ = writeln!(err, "report: {}: {e}", path.display()); + Err(gate) + } + } +} + +#[cfg(not(feature = "report"))] +fn finish_report(_records: &[StepRecord], result: Result<(), Error>, _options: &RunOptions, _err: &mut dyn Write) -> Result<(), Error> { + result +} + +fn not_started(steps: &[Step<'_>], status: Status) -> Vec { + steps.iter().map(|s| StepRecord { step: s.name.clone(), command: s.command.clone(), status, duration: None }).collect() +} + +fn execute(steps: &mut [Step<'_>], options: &RunOptions, err: &mut dyn Write) -> (Vec, Result<(), Error>) { + let mut records = Vec::with_capacity(steps.len()); + let mut result = Ok(()); + for step in steps.iter_mut() { + if result.is_err() { + records.push(StepRecord { step: step.name.clone(), command: step.command.clone(), status: Status::Skip, duration: None }); + continue; + } + if options.is_canceled() { + records.push(StepRecord { step: step.name.clone(), command: step.command.clone(), status: Status::Canceled, duration: None }); + result = Err(Error::Canceled { step: Some(step.name.clone()) }); + continue; + } + let (record, outcome) = run_one(step, options, err); + records.push(record); + result = outcome; + } + (records, result) +} + +fn run_one(step: &mut Step<'_>, options: &RunOptions, err: &mut dyn Write) -> (StepRecord, Result<(), Error>) { + let _ = writeln!(err, "\n=== {}: {} ===", options.title, step.name); + let mut log = StepLog { command: step.command.clone() }; + let started = Instant::now(); + let outcome = (step.run)(&mut log); + let duration = Some(started.elapsed()); + let (status, result) = match outcome { + _ if options.is_canceled() => (Status::Canceled, Err(Error::Canceled { step: Some(step.name.clone()) })), + Ok(()) => (Status::Ok, Ok(())), + Err(cause) => (Status::Fail, Err(Error::Step { step: step.name.clone(), cause })), + }; + (StepRecord { step: step.name.clone(), command: log.command, status, duration }, result) +} + +fn print_summary(records: &[StepRecord], result: &Result<(), Error>, options: &RunOptions, out: &mut dyn Write) { + let title = options.title.to_uppercase(); + if result.is_ok() { + let names: Vec<&str> = records.iter().map(|r| r.step.as_str()).collect(); + let _ = if names.is_empty() { + writeln!(out, "\n{title} summary: all 0 steps passed") + } else { + writeln!(out, "\n{title} summary: all {} steps passed ({})", names.len(), names.join(", ")) + }; + return; + } + let _ = writeln!(out, "\n{title} summary:"); + if let Err(e @ (Error::Config(_) | Error::Lock(_) | Error::Report(_) | Error::Canceled { step: None })) = result { + let _ = writeln!(out, " FAIL {e}"); + } + for r in records { + let _ = match (r.status, result) { + (Status::Ok, _) => writeln!(out, " ok {}", r.step), + (Status::Fail, Err(Error::Step { cause, .. })) => writeln!(out, " FAIL {}: {cause}", r.step), + (Status::Fail, _) => writeln!(out, " FAIL {}", r.step), + (Status::Canceled, _) => writeln!(out, " cancel {}", r.step), + (Status::Skip, _) => writeln!(out, " skip {}", r.step), + }; + } +} + +/// The workspace root of an app: the parent of its xtask manifest directory. +/// +/// Pass the app's own `Path::new(env!("CARGO_MANIFEST_DIR"))`. The parent must hold a +/// `Cargo.toml`; a layout where it does not passes its root to [`cargo`] directly instead. +pub fn root(xtask_manifest_dir: &Path) -> Result { + let parent = xtask_manifest_dir + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .ok_or_else(|| Error::Config(format!("{}: the xtask manifest directory has no parent directory", xtask_manifest_dir.display())))?; + if !parent.join("Cargo.toml").is_file() { + return Err(Error::Config(format!("{}: no Cargo.toml here, so this is not the workspace root", parent.display()))); + } + Ok(parent.to_path_buf()) +} + +/// `cargo` (the `CARGO` the xtask was started with, or `cargo` from `PATH`) with `root` as its +/// working directory. +pub fn cargo(root: &Path) -> Command { + let program = std::env::var_os("CARGO").filter(|p| !p.is_empty()).unwrap_or_else(|| OsString::from("cargo")); + let mut c = Command::new(program); + c.current_dir(root); + c +} + +/// Prints `$ label` to stderr and runs `cmd` with inherited stdin, stdout and stderr. +/// +/// Returns an error when the command cannot be started or exits with a failure status. +pub fn run(mut cmd: Command, label: &str) -> Result<(), String> { + eprintln!("$ {label}"); + let status = cmd.status().map_err(|e| spawn_error(label, &e))?; + exit_result(label, status) +} + +/// [`run`] that ends the child, with the processes it started, and waits for it to exit when +/// `cancel` is set while it runs. +/// +/// On Unix the child runs in a process group of its own, so a terminal's Ctrl-C reaches the xtask +/// and not the child: the app's Ctrl-C handler sets `cancel`, and this function ends the group with +/// `kill -s KILL`. On Windows it ends the process tree with `taskkill /T /F`. When that tool cannot +/// be run, only the child itself is ended. +pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result<(), String> { + eprintln!("$ {label}"); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?; + loop { + if let Some(status) = child.try_wait().map_err(|e| format!("{label}: {e}"))? { + return exit_result(label, status); + } + if cancel.is_canceled() { + let killed = end_tree(&mut child); + let reaped = child.wait(); + return match (killed, reaped) { + (_, Ok(_)) => Err(format!("{label}: canceled")), + (Err(k), Err(w)) => Err(format!("{label}: canceled, but the child could not be ended ({k}; {w})")), + (Ok(()), Err(w)) => Err(format!("{label}: canceled, but waiting for the child failed ({w})")), + }; + } + std::thread::sleep(CHILD_POLL); + } +} + +/// Ends `child` and every process in its group (Unix) or tree (Windows), falling back to the child +/// alone when the system tool fails. +fn end_tree(child: &mut Child) -> io::Result<()> { + let id = child.id().to_string(); + #[cfg(unix)] + let tree = Command::new("kill").args(["-s", "KILL", "--", &format!("-{id}")]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + #[cfg(windows)] + let tree = Command::new("taskkill").args(["/T", "/F", "/PID", &id]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + #[cfg(not(any(unix, windows)))] + let tree: io::Result = Err(io::Error::new(io::ErrorKind::Unsupported, id)); + match tree { + Ok(status) if status.success() => Ok(()), + _ => child.kill(), + } +} + +fn spawn_error(label: &str, e: &io::Error) -> String { + format!("{label}: failed to spawn: {e}") +} + +fn exit_result(label: &str, status: ExitStatus) -> Result<(), String> { + if status.success() { Ok(()) } else { Err(format!("{label}: exited with {status}")) } +} + +/// Which test runner [`nextest_or_test`] uses. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum TestMode { + /// `cargo test`. Nothing is probed. + #[default] + CargoTest, + /// `cargo nextest run` when `cargo nextest --version` succeeds, otherwise `cargo test` with a note. + PreferNextest, +} + +/// The workspace test command and its label, with the running xtask package excluded. +/// +/// The command is `cargo test --workspace --exclude ` or, with +/// [`TestMode::PreferNextest`] and nextest installed, `cargo nextest run --workspace --exclude +/// `. `args` holds the app's targets, features and filters. The label names +/// the command that will run, so a fallback shows as `cargo test`. +pub fn nextest_or_test(root: &Path, xtask_package: &str, mode: TestMode, args: &[impl AsRef]) -> Result<(Command, String), Error> { + select_test(cargo(root), xtask_package, mode, args, || nextest_available(cargo(root))) +} + +/// [`nextest_or_test`] with the nextest probe passed in. +fn select_test( + cargo: Command, + xtask_package: &str, + mode: TestMode, + args: &[impl AsRef], + probe: impl FnOnce() -> bool, +) -> Result<(Command, String), Error> { + check_package(xtask_package)?; + let nextest = match mode { + TestMode::CargoTest => false, + TestMode::PreferNextest => { + let found = probe(); + if !found { + eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + } + found + } + }; + Ok(test_command(cargo, xtask_package, if nextest { &["nextest", "run"] } else { &["test"] }, args)) +} + +/// The workspace doctest command and its label: `cargo test --workspace --exclude +/// --doc `. nextest does not run doctests. +pub fn doctest(root: &Path, xtask_package: &str, args: &[impl AsRef]) -> Result<(Command, String), Error> { + check_package(xtask_package)?; + let doc_args: Vec<&OsStr> = std::iter::once(OsStr::new("--doc")).chain(args.iter().map(AsRef::as_ref)).collect(); + Ok(test_command(cargo(root), xtask_package, &["test"], &doc_args)) +} + +/// Whether `cargo nextest --version` succeeds for this `cargo` command. +pub fn nextest_available(mut cargo: Command) -> bool { + cargo.args(["nextest", "--version"]).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success()) +} + +fn test_command(mut c: Command, xtask_package: &str, tool: &[&str], args: &[impl AsRef]) -> (Command, String) { + c.args(tool).args(["--workspace", "--exclude", xtask_package]).args(args); + let mut label = format!("cargo {} --workspace --exclude {xtask_package}", tool.join(" ")); + for a in args { + label.push(' '); + label.push_str(&a.as_ref().to_string_lossy()); + } + (c, label) +} + +/// A Cargo package name: ASCII letters, digits, `-` and `_`, not starting with `-`. +fn check_package(name: &str) -> Result<(), Error> { + let valid = !name.is_empty() && !name.starts_with('-') && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if valid { Ok(()) } else { Err(Error::Config(format!("`{name}` is not a package name to exclude from the test build"))) } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(c: &Command) -> Vec { + c.get_args().map(|a| a.to_string_lossy().into_owned()).collect() + } + + fn run_capture(steps: &mut [Step<'_>], options: &RunOptions) -> (Result, Error>, String, String) { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let result = run_steps_to(steps, options, &mut out, &mut err); + (result, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned()) + } + + #[test] + fn run_steps_success_failure_and_skips() { + let later_ran = Cell::new(false); + let mut steps = vec![ + Step::new("fmt", |_| Ok(())), + Step::new("clippy", |log| Err(format!("{}: exited with 101", log.command("cargo clippy")))), + Step::new("test", |_| { + later_ran.set(true); + Ok(()) + }), + ]; + let (result, out, err) = run_capture(&mut steps, &RunOptions::default()); + assert_eq!(result, Err(Error::Step { step: "clippy".into(), cause: "cargo clippy: exited with 101".into() })); + assert!(!later_ran.get(), "a step after the failure ran"); + assert_eq!(out, "\nCI summary:\n ok fmt\n FAIL clippy: cargo clippy: exited with 101\n skip test\n"); + assert!(err.contains("=== ci: fmt ===") && err.contains("=== ci: clippy ===") && !err.contains("=== ci: test ==="), "{err}"); + + let mut passing = vec![Step::new("fmt", |_| Ok(())), Step::new("test", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut passing, &RunOptions::default().with_title("gate")); + let records = result.unwrap_or_default(); + assert_eq!(records.iter().map(|r| r.status).collect::>(), [Status::Ok, Status::Ok]); + assert_eq!(out, "\nGATE summary: all 2 steps passed (fmt, test)\n"); + } + + #[test] + fn run_steps_empty() { + let (result, out, err) = run_capture(&mut [], &RunOptions::default()); + assert_eq!(result, Ok(Vec::new())); + assert_eq!(out, "\nCI summary: all 0 steps passed\n"); + assert!(err.is_empty()); + } + + #[test] + fn run_steps_canceled_runs_nothing_more() { + let cancel = Cancel::new(); + let ran = Cell::new(0); + let mut steps = vec![ + Step::new("fmt", |_| { + ran.set(ran.get() + 1); + cancel.cancel(); + Err("interrupted".to_owned()) + }), + Step::new("test", |_| { + ran.set(ran.get() + 1); + Ok(()) + }), + ]; + let options = RunOptions::default().with_cancel(cancel.clone()); + let (result, out, _) = run_capture(&mut steps, &options); + assert_eq!(result, Err(Error::Canceled { step: Some("fmt".into()) })); + assert_eq!(ran.get(), 1); + assert_eq!(out, "\nCI summary:\n cancel fmt\n skip test\n"); + + // A last step that passes after the flag was set does not make the run pass. + let late = Cancel::new(); + let mut last = vec![Step::new("last", |_| { + late.cancel(); + Ok(()) + })]; + let (result, out, _) = run_capture(&mut last, &RunOptions::default().with_cancel(late.clone())); + assert_eq!(result, Err(Error::Canceled { step: Some("last".into()) })); + assert_eq!(out, "\nCI summary:\n cancel last\n"); + + let mut again = vec![Step::new("fmt", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut again, &options); + assert_eq!(result, Err(Error::Canceled { step: Some("fmt".into()) })); + assert!(!out.contains("passed"), "{out}"); + } + + #[cfg(all(feature = "lock", feature = "report"))] + #[test] + fn a_run_without_its_lock_writes_no_report() { + use crate::lock::{LockConfig, try_acquire}; + let _guard = crate::spawn_guard(); + let Ok(dir) = tempfile::tempdir() else { panic!("no temporary directory") }; + let locks = dir.path().join("locks"); + let lock = LockConfig::new(&locks, 1, "holder").with_poll(Duration::from_millis(1)); + let Ok(Some(_held)) = try_acquire(&lock) else { panic!("free slot") }; + + // A run canceled while another run holds the slot leaves that run's report alone. + let report = dir.path().join("ci.json"); + let Ok(()) = std::fs::write(&report, b"sentinel") else { panic!("cannot write the sentinel") }; + let cancel = Cancel::new(); + cancel.cancel(); + let ran = Cell::new(false); + let mut steps = vec![Step::new("test", |_| { + ran.set(true); + Ok(()) + })]; + let options = RunOptions::default().with_lock(lock.clone()).with_report(&report).with_cancel(cancel); + let (result, out, _) = run_capture(&mut steps, &options); + assert_eq!(result, Err(Error::Canceled { step: None })); + assert!(!ran.get(), "a step ran without the lock"); + assert_eq!(out, "\nCI summary:\n FAIL canceled before the first step\n skip test\n"); + assert_eq!(std::fs::read(&report).ok(), Some(b"sentinel".to_vec())); + + // A rejected lock configuration creates no report file. + let fresh = dir.path().join("rejected.json"); + let options = RunOptions::default().with_lock(LockConfig::new(&locks, 0, "zero")).with_report(&fresh); + let (result, _, _) = run_capture(&mut [Step::new("test", |_| Ok(()))], &options); + assert!(matches!(result, Err(Error::Config(_))), "{result:?}"); + assert!(!fresh.exists(), "a report was written without the lock"); + + // A lock directory that cannot be created leaves the existing report alone. + let not_a_dir = dir.path().join("file"); + let Ok(()) = std::fs::write(¬_a_dir, b"") else { panic!("cannot write the file") }; + let options = RunOptions::default().with_lock(LockConfig::new(not_a_dir.join("locks"), 1, "run")).with_report(&report); + let (result, _, _) = run_capture(&mut [Step::new("test", |_| Ok(()))], &options); + assert!(matches!(result, Err(Error::Lock(_))), "{result:?}"); + assert_eq!(std::fs::read(&report).ok(), Some(b"sentinel".to_vec())); + } + + #[test] + fn root_uses_callers_manifest() { + let Ok(dir) = tempfile::tempdir() else { panic!("no temporary directory") }; + let app = dir.path().join("app"); + let xtask = app.join("xtask"); + let Ok(()) = std::fs::create_dir_all(&xtask) else { panic!("cannot create the fixture") }; + let Ok(()) = std::fs::write(app.join("Cargo.toml"), "[workspace]\n") else { panic!("cannot write the fixture") }; + assert_eq!(root(&xtask), Ok(app.clone())); + assert_eq!(cargo(&app).get_current_dir(), Some(app.as_path())); + + // A manifest directory whose parent is not a workspace, and one with no parent at all. + assert!(matches!(root(&dir.path().join("xtask")), Err(Error::Config(_)))); + assert!(matches!(root(Path::new("xtask")), Err(Error::Config(_)))); + assert!(matches!(root(Path::new("")), Err(Error::Config(_)))); + } + + #[test] + fn workspace_tests_exclude_running_package() { + let root = Path::new("."); + let targets = ["--lib", "--bins", "--tests"]; + let (c, label) = test_command(cargo(root), "designcraft-xtask", &["test"], &targets); + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "designcraft-xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo test --workspace --exclude designcraft-xtask --lib --bins --tests"); + + let (c, label) = test_command(cargo(root), "xtask", &["nextest", "run"], &targets); + assert_eq!(args(&c), ["nextest", "run", "--workspace", "--exclude", "xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo nextest run --workspace --exclude xtask --lib --bins --tests"); + + let Ok((c, label)) = nextest_or_test(root, "xtask", TestMode::CargoTest, &targets) else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --lib --bins --tests"); + + let Ok((c, label)) = doctest(root, "xtask", &["--features", "full"]) else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--doc", "--features", "full"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --doc --features full"); + + for bad in ["", "-p", "--workspace", "two words", "x;y"] { + assert!(matches!(nextest_or_test(root, bad, TestMode::CargoTest, &targets), Err(Error::Config(_))), "{bad:?}"); + assert!(matches!(doctest(root, bad, &[] as &[&str]), Err(Error::Config(_))), "{bad:?}"); + } + } + + #[test] + fn missing_tools_and_output_bytes() { + let _guard = crate::spawn_guard(); + let missing = "craft-xtask-test-no-such-program"; + let Err(e) = run(Command::new(missing), "missing tool") else { panic!("a missing program ran") }; + assert!(e.starts_with("missing tool: failed to spawn: "), "{e}"); + assert!(!nextest_available(Command::new(missing))); + + // PreferNextest without nextest falls back to cargo test; CargoTest never probes. + let targets = ["--lib"]; + let fallback = select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &targets, || nextest_available(Command::new(missing))); + let Ok((c, label)) = fallback else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--lib"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --lib"); + let Ok((c, label)) = select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &targets, || true) else { panic!("valid package") }; + assert_eq!(args(&c), ["nextest", "run", "--workspace", "--exclude", "xtask", "--lib"]); + assert_eq!(label, "cargo nextest run --workspace --exclude xtask --lib"); + let probed = Cell::new(false); + let Ok((c, _)) = select_test(cargo(Path::new(".")), "xtask", TestMode::CargoTest, &targets, || { + probed.set(true); + true + }) else { + panic!("valid package") + }; + assert_eq!(args(&c)[0], "test"); + assert!(!probed.get(), "CargoTest probed for nextest"); + + // A child's output that is not UTF-8 reaches the stream it was given unchanged. + let (mut reader, writer) = io::pipe().expect("pipe"); + let mut child = test_child("runner::tests::bytes_child", BYTES_CHILD); + child.stdout(writer).stderr(Stdio::null()); + assert_eq!(run(child, "bytes"), Ok(())); + let mut got = Vec::new(); + io::Read::read_to_end(&mut reader, &mut got).expect("child output"); + assert!(got.windows(RAW_BYTES.len()).any(|w| w == RAW_BYTES), "{got:?}"); + + // The test binary itself, given a flag it does not know, exits with a failure status. + let Ok(exe) = std::env::current_exe() else { panic!("no test executable") }; + let mut child = Command::new(&exe); + child.arg("--craft-xtask-unknown-flag").stdout(Stdio::null()).stderr(Stdio::null()); + let Err(e) = run(child, "child") else { panic!("an unknown flag passed") }; + assert!(e.starts_with("child: exited with "), "{e}"); + + let mut steps = vec![Step::new("cargo", |log| run(Command::new(missing), log.command("cargo"))), Step::new("after", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut steps, &RunOptions::default()); + assert!(matches!(&result, Err(Error::Step { step, cause }) if step == "cargo" && cause.contains("failed to spawn")), "{result:?}"); + assert!(out.contains(" FAIL cargo: cargo: failed to spawn: ") && out.ends_with("\n skip after\n"), "{out}"); + } + + const TREE_CHILD: &str = "CRAFT_XTASK_TREE_CHILD"; + const BLOCKED_CHILD: &str = "CRAFT_XTASK_BLOCKED_CHILD"; + const BYTES_CHILD: &str = "CRAFT_XTASK_BYTES_CHILD"; + const RAW_BYTES: &[u8] = b"\xff\xfe\x00 not UTF-8 \x80\xc3\n"; + + /// This test binary, run as a child that runs only the ignored test `name`. + fn test_child(name: &str, env: &str) -> Command { + let exe = std::env::current_exe().expect("test executable"); + let mut c = Command::new(exe); + c.args(["--ignored", "--exact", name, "--nocapture"]).env(env, "1").stdin(Stdio::null()); + c + } + + /// Reads a pipe whose writing end this process also holds, so the read never ends. + fn block_forever() { + let (mut reader, _writer) = io::pipe().expect("pipe"); + let _ = io::Read::read_to_end(&mut reader, &mut Vec::new()); + } + + #[test] + fn run_cancelable_ends_the_process_tree() { + use io::BufRead; + let _guard = crate::spawn_guard(); + let (reader, writer) = io::pipe().expect("pipe"); + let mut child = test_child("runner::tests::tree_child", TREE_CHILD); + child.stdout(writer).stderr(Stdio::null()); + let cancel = Cancel::new(); + let runner = { + let cancel = cancel.clone(); + std::thread::spawn(move || run_cancelable(child, "tree", &cancel)) + }; + // The child prints `ready` once it has started its own child, which shares the pipe. + let mut lines = io::BufReader::new(reader); + let mut line = String::new(); + while !line.trim_end().ends_with("ready") { + line.clear(); + assert_ne!(lines.read_line(&mut line).expect("child output"), 0, "the child ended before it was ready"); + } + cancel.cancel(); + assert_eq!(runner.join().expect("runner thread"), Err("tree: canceled".to_owned())); + // The pipe ends only when every process holding it has ended, the child's child included. + io::Read::read_to_end(&mut lines, &mut Vec::new()).expect("pipe end"); + } + + /// Starts a blocked child of its own, says `ready`, and blocks; run by `run_cancelable_ends_the_process_tree`. + #[test] + #[ignore = "child process of run_cancelable_ends_the_process_tree"] + fn tree_child() { + if std::env::var_os(TREE_CHILD).is_some() { + let mut grandchild = test_child("runner::tests::blocked_child", BLOCKED_CHILD).spawn().expect("grandchild"); + let mut out = io::stdout(); + writeln!(out, "ready").and_then(|()| out.flush()).expect("stdout"); + // The grandchild never exits, so this blocks too. + let _ = grandchild.wait(); + } + } + + /// Writes bytes that are not UTF-8 to stdout; run by `missing_tools_and_output_bytes`. + #[test] + #[ignore = "child process of missing_tools_and_output_bytes"] + fn bytes_child() { + if std::env::var_os(BYTES_CHILD).is_some() { + let mut out = io::stdout(); + out.write_all(RAW_BYTES).and_then(|()| out.flush()).expect("stdout"); + } + } + + /// Blocks; run by `tree_child`. + #[test] + #[ignore = "child process of tree_child"] + fn blocked_child() { + if std::env::var_os(BLOCKED_CHILD).is_some() { + block_forever(); + } + } +} From dc8f3481022ca2ecfeaf8023ac3f33ce81b6d863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:43:35 -0800 Subject: [PATCH 2/8] craft-xtask: count Rust files, lines and tests per crate without following links Adds the stats module behind a new stats feature, the library form of the apps' cargo xtask stats. The app passes its cargo metadata JSON, a function that builds its cargo command, and a writer. Compared with the app copies, links and junctions are not followed, every input has a size limit, only workspace members are walked, a member nested in another member's folder is counted once, and malformed or duplicate packages are errors. The exact-mode tests start child processes and take spawn_guard like the runner and lock tests. --- crates/xtask/Cargo.toml | 2 + crates/xtask/README.md | 47 +- crates/xtask/src/lib.rs | 3 + crates/xtask/src/stats.rs | 898 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 948 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/stats.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..ed7be0d7ff 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -16,6 +16,8 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# `cargo xtask stats`: files, lines and tests of Rust per workspace crate, read from `cargo metadata`. +stats = ["dep:serde_json"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..cfe87e2247 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,10 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `stats` | `stats` | `run`, `collect` and `write_table`: files, lines and tests of Rust per workspace crate (`cargo xtask stats`) | -No feature is on by default. `report` adds `serde_json` and `craft-atomic`. +No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `stats` adds +`serde_json`. ## Use @@ -91,6 +93,42 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Stats + +`cargo xtask stats [--exact]` prints the `.rs` files, lines, `#[test]` attributes and `proptest!` blocks +of each workspace crate. The app passes the `cargo metadata --format-version 1 --no-deps` JSON, a +function that builds its `cargo` command, and a writer: + +```rust,ignore +Some("stats") => { + let options = craft_xtask::stats::Options { exact: rest.contains(&"--exact"), ..Default::default() }; + craft_xtask::stats::run(&metadata_bytes()?, &options, cargo, &mut std::io::stdout().lock()) + .map(drop) + .map_err(|e| e.to_string()) +} +``` + +- Each workspace member's folder is walked. Folders named `target` or `fuzz` and folders whose names + start with `.` are skipped, and a member inside another member's folder is counted in its own row + only. Symbolic links and Windows junctions are not followed, to folders or to files. +- `#[test]` counts the text `#[test]` on lines that do not start with `//`. Tests that macros generate + count once, and `#[tokio::test]` is not counted. `--exact` runs + `cargo test -q -p -- --list` for each crate and counts the lines that end in `: test`. A + crate whose listing fails shows `error`, and a line under the table names it. +- `Limits` bounds every input. A larger input is an error naming the path and the limit: + + | Limit | Default | + |---|---| + | `metadata_bytes`: the `cargo metadata` JSON | 64 MiB | + | `source_bytes`: one `.rs` file | 16 MiB | + | `total_source_bytes`: all `.rs` files of a run | 1 GiB | + | `entries`: folder entries of a run | 1,000,000 | + | `depth`: folder levels below a crate's folder | 256 | + | `harness_output_bytes`: one crate's `--list` output | 64 MiB | + + A folder or file that cannot be read and a `.rs` file that is not UTF-8 are errors too. +- `collect` returns the `Report` without writing it, and `write_table` writes a `Report`. + ## Origin | Part | Source | @@ -98,7 +136,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | -| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `stats`: the folder walk that skips directory links, and the table | DesignCraft `xtask/src/stats.rs` at `dc9eea2695` | +| `stats`: regular files only, and `a_walk_does_not_follow_directory_links` | WordCraft `xtask/src/stats.rs` at `6b163b33dc` | +| `stats`: the entry budget that returns an error, and its two tests | CADCraft `xtask/src/stats.rs` at `ca87680fb0` | +| `stats`: the per-file size limit, and its two tests | GridCraft `xtask/src/stats.rs` at `9e9f13114f` | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `stats`, the metadata, total-size, depth and `--list` output limits, the metadata checks and the line naming failed listings | written here | ## Migration @@ -108,6 +150,7 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| CADCraft, DeckCraft, DesignCraft, GridCraft, LightCraft, PhotoCraft, VectorCraft, WordCraft | Planned: `xtask/src/stats.rs` moves to `stats`. Each app's switch lists its per-crate counts before and after in its pull request. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..eb92226999 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,7 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - `stats` (feature `stats`): files, lines and tests of Rust per workspace crate (`cargo xtask stats`). //! //! ```no_run //! use std::path::Path; @@ -40,6 +41,8 @@ pub mod lock; #[cfg(feature = "report")] pub mod report; pub mod runner; +#[cfg(feature = "stats")] +pub mod stats; /// Keeps the tests that start child processes apart from the tests that check whether a slot is free. /// A child holds copies of the parent's open files, and so its file locks, until it starts its program. diff --git a/crates/xtask/src/stats.rs b/crates/xtask/src/stats.rs new file mode 100644 index 0000000000..c51590e897 --- /dev/null +++ b/crates/xtask/src/stats.rs @@ -0,0 +1,898 @@ +//! `cargo xtask stats`: files, lines and tests of Rust per workspace crate. +//! +//! [`run`] reads the workspace packages from the `cargo metadata --format-version 1 --no-deps` JSON the +//! caller passes in, walks each package's folder and writes a table to the caller's writer: +//! +//! ```text +//! crate files lines #[test] proptest! +//! -------------------------------------------------------------- +//! app-core 12 3410 41 2 +//! -------------------------------------------------------------- +//! TOTAL 12 3410 41 2 +//! ``` +//! +//! What it counts: +//! +//! - Every regular file whose name ends in `.rs`, in the package's folder and the folders below it. +//! Folders named `target` or `fuzz`, and folders whose names start with `.`, are skipped. The +//! folder of another workspace member is counted in that member's row only. +//! Symbolic links (and Windows junctions) are not followed, to folders or to files. +//! - Lines as [`str::lines`] counts them, blank and comment lines included. +//! - `#[test]` is an estimate read from the text: each `#[test]` on a line that does not start with +//! `//`. `#[tokio::test]` and the tests inside `proptest!` are not counted; each line that starts +//! with `proptest!` counts as one block in its own column. +//! - With [`Options::exact`], the harness column runs `cargo test -q -p -- --list` for each +//! crate and counts the output lines that end in `: test`. A crate whose command fails shows +//! `error`, the harness total leaves it out, and a line under the table says how many failed. +//! +//! Every input has a size limit ([`Limits`]); an input over a limit, a folder or file that cannot be +//! read, and a source that is not UTF-8 return an [`Error`] naming the path, and nothing is written. + +use std::collections::HashSet; +use std::fmt; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// Size limits for one [`run`]. An input over a limit is an [`Error`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Bytes of `cargo metadata` JSON, checked before it is parsed. Default 64 MiB. + pub metadata_bytes: usize, + /// Bytes of one `.rs` file. Default 16 MiB. + pub source_bytes: u64, + /// Bytes of all `.rs` files read in one run. Default 1 GiB. + pub total_source_bytes: u64, + /// Folder entries visited in one run, all crates together. Default 1,000,000. + pub entries: usize, + /// Levels of folders below a crate's folder. Default 256. + pub depth: usize, + /// Bytes of standard output from one crate's `cargo test -- --list`, in exact mode. Default 64 MiB. + pub harness_output_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + metadata_bytes: 64 << 20, + source_bytes: 16 << 20, + total_source_bytes: 1 << 30, + entries: 1_000_000, + depth: 256, + harness_output_bytes: 64 << 20, + } + } +} + +/// How [`run`] counts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Options { + /// Ask each crate's test harness for its test count (`--exact`). + pub exact: bool, + /// The size limits. + pub limits: Limits, +} + +/// Counts for one crate, or for all of them. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counts { + /// `.rs` files. + pub files: usize, + /// Lines in those files. + pub lines: usize, + /// `#[test]` attributes found in the text. + pub tests: usize, + /// Lines that start a `proptest!` block. + pub proptests: usize, +} + +impl Counts { + fn add(&mut self, other: &Counts) { + self.files = self.files.saturating_add(other.files); + self.lines = self.lines.saturating_add(other.lines); + self.tests = self.tests.saturating_add(other.tests); + self.proptests = self.proptests.saturating_add(other.proptests); + } + + fn add_source(&mut self, src: &str) { + let (tests, proptests) = count_tests(src); + self.add(&Counts { files: 1, lines: src.lines().count(), tests, proptests }); + } +} + +/// The result of one crate's `cargo test -- --list`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Harness { + /// The command succeeded and listed this many tests. + Listed(usize), + /// The command could not start or did not succeed; the text says why. + Failed(String), +} + +/// One crate's row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Row { + /// The package name. + pub name: String, + /// The package's `Cargo.toml`, as `cargo metadata` gives it. + pub manifest_path: PathBuf, + /// What the walk of the package's folder found. + pub counts: Counts, + /// The harness count, in exact mode only. + pub harness: Option, +} + +/// Every crate's counts, sorted by package name and then by manifest path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + /// One row per workspace package. + pub rows: Vec, + /// The sum of the rows' counts. + pub total: Counts, + /// Whether the harness counts were asked for. + pub exact: bool, +} + +impl Report { + /// The sum of the harness counts that succeeded, or `None` outside exact mode. + pub fn harness_total(&self) -> Option { + self.exact.then(|| { + self.rows + .iter() + .filter_map(|r| match r.harness { + Some(Harness::Listed(n)) => Some(n), + _ => None, + }) + .fold(0, usize::saturating_add) + }) + } + + /// The rows whose harness command failed. + pub fn harness_failures(&self) -> impl Iterator { + self.rows.iter().filter(|r| matches!(r.harness, Some(Harness::Failed(_)))) + } +} + +/// Why [`run`] stopped. +#[derive(Debug)] +pub enum Error { + /// The `cargo metadata` JSON is too large, is not JSON, or lacks a field. + Metadata(String), + /// A folder or file could not be read. + Io { + /// The folder or file. + path: PathBuf, + /// The error reading it. + source: io::Error, + }, + /// A `.rs` file is not UTF-8. + NotUtf8(PathBuf), + /// A `.rs` file is larger than [`Limits::source_bytes`]. + SourceTooLarge { + /// The file. + path: PathBuf, + /// The limit in bytes. + limit: u64, + }, + /// Reading a file would take the run past [`Limits::total_source_bytes`]. + TotalTooLarge { + /// The file being read. + path: PathBuf, + /// The limit in bytes. + limit: u64, + }, + /// The run visited [`Limits::entries`] folder entries. + TooManyEntries { + /// The folder being read. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A folder is more than [`Limits::depth`] levels below its crate's folder. + TooDeep { + /// The folder. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A crate's `cargo test -- --list` printed more than [`Limits::harness_output_bytes`]. + HarnessOutputTooLarge { + /// The package name. + package: String, + /// The limit in bytes. + limit: u64, + }, + /// The table could not be written. + Write(io::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Metadata(why) => write!(f, "cargo metadata: {why}"), + Error::Io { path, source } => write!(f, "{}: {source}", path.display()), + Error::NotUtf8(path) => write!(f, "{}: not UTF-8", path.display()), + Error::SourceTooLarge { path, limit } => write!(f, "{}: larger than the limit of {limit} bytes for one source", path.display()), + Error::TotalTooLarge { path, limit } => { + write!(f, "{}: reading it passes the limit of {limit} bytes for all sources", path.display()) + } + Error::TooManyEntries { path, limit } => write!(f, "{}: the walk reached its limit of {limit} folder entries", path.display()), + Error::TooDeep { path, limit } => write!(f, "{}: more than {limit} folders deep", path.display()), + Error::HarnessOutputTooLarge { package, limit } => { + write!(f, "cargo test -p {package} -- --list: printed more than the limit of {limit} bytes") + } + Error::Write(e) => write!(f, "writing the table: {e}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io { source, .. } | Error::Write(source) => Some(source), + _ => None, + } + } +} + +/// Counts every workspace crate in `metadata_json` and writes the table to `out`. +/// +/// `cargo` builds the app's `cargo` command (program, folder and environment); in exact mode the +/// arguments `test -q -p -- --list` are added to it for each crate. Outside exact mode it is +/// not called. Nothing is written when an [`Error`] is returned before the table. +pub fn run(metadata_json: &[u8], options: &Options, cargo: impl FnMut() -> Command, out: &mut impl Write) -> Result { + let report = collect(metadata_json, options, cargo)?; + write_table(&report, out).map_err(Error::Write)?; + Ok(report) +} + +/// Counts every workspace crate in `metadata_json`, as [`run`] does, without writing anything. +pub fn collect(metadata_json: &[u8], options: &Options, mut cargo: impl FnMut() -> Command) -> Result { + let limits = &options.limits; + let packages = packages(metadata_json, limits.metadata_bytes)?; + let mut dirs = Vec::with_capacity(packages.len()); + for package in &packages { + let dir = package + .manifest_path + .parent() + .ok_or_else(|| Error::Metadata(format!("package {}: manifest path {} has no folder", package.name, package.manifest_path.display())))?; + dirs.push(dir.to_path_buf()); + } + let members = dirs.iter().cloned().collect(); + let mut walker = Walker { limits, members, entries: 0, bytes: 0 }; + let mut rows = Vec::new(); + let mut total = Counts::default(); + for (package, dir) in packages.into_iter().zip(dirs) { + let counts = walker.walk(&dir)?; + total.add(&counts); + let harness = if options.exact { Some(harness_count(&mut cargo, &package.name, limits.harness_output_bytes)?) } else { None }; + rows.push(Row { name: package.name, manifest_path: package.manifest_path, counts, harness }); + } + Ok(Report { rows, total, exact: options.exact }) +} + +/// Writes `report` as the `cargo xtask stats` table. +pub fn write_table(report: &Report, out: &mut impl Write) -> io::Result<()> { + let exact = report.exact; + let exact_col = if exact { format!(" {:>8}", "harness") } else { String::new() }; + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{exact_col}", "crate", "files", "lines", "#[test]", "proptest!")?; + let rule = "-".repeat(62 + if exact { 9 } else { 0 }); + writeln!(out, "{rule}")?; + for row in &report.rows { + let c = &row.counts; + let ex = match &row.harness { + None => String::new(), + Some(Harness::Listed(n)) => format!(" {n:>8}"), + Some(Harness::Failed(_)) => format!(" {:>8}", "error"), + }; + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{ex}", row.name, c.files, c.lines, c.tests, c.proptests)?; + } + writeln!(out, "{rule}")?; + let t = &report.total; + let ex = report.harness_total().map_or_else(String::new, |n| format!(" {n:>8}")); + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{ex}", "TOTAL", t.files, t.lines, t.tests, t.proptests)?; + if exact { + let failed: Vec<&str> = report.harness_failures().map(|r| r.name.as_str()).collect(); + if !failed.is_empty() { + writeln!(out, "\n(The harness total leaves out {} crate(s) whose test listing failed: {}.)", failed.len(), failed.join(", "))?; + } + } else { + writeln!(out, "\n(#[test] counts source attributes; macro-generated tests count once. Use --exact for harness counts.)")?; + } + Ok(()) +} + +/// A workspace package from `cargo metadata`. +struct Package { + name: String, + manifest_path: PathBuf, +} + +/// The workspace members of `cargo metadata` JSON, sorted by name and then by manifest path. +/// +/// Packages that are not workspace members (dependencies, when the JSON was made without +/// `--no-deps`) are left out. A member without a package entry, a package listed twice, and a missing +/// or non-string `id`, `name` or `manifest_path` are errors. +fn packages(json: &[u8], limit: usize) -> Result, Error> { + if json.len() > limit { + return Err(Error::Metadata(format!("{} bytes of JSON is more than the limit of {limit}", json.len()))); + } + let meta: serde_json::Value = serde_json::from_slice(json).map_err(|e| Error::Metadata(format!("not JSON: {e}")))?; + let field = |v: &serde_json::Value, what: &str| -> Result { + v.as_str().map(str::to_owned).ok_or_else(|| Error::Metadata(format!("{what} is missing or not a string"))) + }; + let members = meta["workspace_members"].as_array().ok_or_else(|| Error::Metadata("workspace_members is missing".into()))?; + let mut wanted = HashSet::new(); + for member in members { + wanted.insert(field(member, "a workspace_members entry")?); + } + let list = meta["packages"].as_array().ok_or_else(|| Error::Metadata("packages is missing".into()))?; + let mut found = HashSet::new(); + let mut paths = HashSet::new(); + let mut out = Vec::new(); + for p in list { + let id = field(&p["id"], "a package id")?; + if !wanted.contains(&id) { + continue; + } + let name = field(&p["name"], &format!("the name of package {id}"))?; + let manifest_path = PathBuf::from(field(&p["manifest_path"], &format!("the manifest_path of package {id}"))?); + if !found.insert(id.clone()) || !paths.insert(manifest_path.clone()) { + return Err(Error::Metadata(format!("package {id} ({}) is listed twice", manifest_path.display()))); + } + out.push(Package { name, manifest_path }); + } + if let Some(missing) = wanted.iter().find(|id| !found.contains(*id)) { + return Err(Error::Metadata(format!("workspace member {missing} has no package entry"))); + } + out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.manifest_path.cmp(&b.manifest_path))); + Ok(out) +} + +/// Walks crate folders within one run's entry and byte budgets. +struct Walker<'a> { + limits: &'a Limits, + /// The folders of every workspace member. A member's folder inside another member's folder is + /// counted in its own row only. + members: HashSet, + entries: usize, + bytes: u64, +} + +impl Walker<'_> { + /// Counts the `.rs` files under `root`, without following links. + fn walk(&mut self, root: &Path) -> Result { + let mut counts = Counts::default(); + let mut pending = vec![(root.to_path_buf(), 0usize)]; + while let Some((dir, depth)) = pending.pop() { + let io_err = |source| Error::Io { path: dir.clone(), source }; + for entry in std::fs::read_dir(&dir).map_err(io_err)? { + let entry = entry.map_err(io_err)?; + if self.entries >= self.limits.entries { + return Err(Error::TooManyEntries { path: dir.clone(), limit: self.limits.entries }); + } + self.entries += 1; + let path = entry.path(); + // The entry's own type: a link is never followed, so links to a parent folder, or + // many links to one folder, do not multiply the walk, and a link to a file outside + // the crate is not counted. + let kind = entry.file_type().map_err(|source| Error::Io { path: path.clone(), source })?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if kind.is_symlink() { + continue; + } + if kind.is_dir() { + // Nested fuzz workspaces and build output are not part of the crate. + if name == "target" || name == "fuzz" || name.starts_with('.') || self.members.contains(&path) { + continue; + } + if depth >= self.limits.depth { + return Err(Error::TooDeep { path, limit: self.limits.depth }); + } + pending.push((path, depth + 1)); + } else if kind.is_file() && name.ends_with(".rs") { + let src = self.read_source(&path)?; + counts.add_source(&src); + } + } + } + Ok(counts) + } + + /// A source file's text, read within the per-file and per-run byte limits. A file that grew + /// past a limit while it is read is an error too, since the read stops one byte past the limit. + fn read_source(&mut self, path: &Path) -> Result { + let per_file = self.limits.source_bytes; + let left = self.limits.total_source_bytes.saturating_sub(self.bytes); + let cap = per_file.min(left); + let io_err = |source| Error::Io { path: path.to_path_buf(), source }; + let file = File::open(path).map_err(io_err)?; + let Some(bytes) = read_bounded(file, cap).map_err(io_err)? else { + return Err(if per_file <= left { + Error::SourceTooLarge { path: path.to_path_buf(), limit: per_file } + } else { + Error::TotalTooLarge { path: path.to_path_buf(), limit: self.limits.total_source_bytes } + }); + }; + self.bytes = self.bytes.saturating_add(bytes.len() as u64); + String::from_utf8(bytes).map_err(|_| Error::NotUtf8(path.to_path_buf())) + } +} + +/// Everything `reader` gives, or `None` when that is more than `limit` bytes. +fn read_bounded(reader: impl Read, limit: u64) -> io::Result>> { + let mut buf = Vec::new(); + reader.take(limit.saturating_add(1)).read_to_end(&mut buf)?; + Ok((buf.len() as u64 <= limit).then_some(buf)) +} + +/// `#[test]` attributes and `proptest!` blocks (each block may hold many +/// property tests, and macro-generated tests are only counted once; use +/// `--exact` for harness-accurate numbers). +fn count_tests(src: &str) -> (usize, usize) { + let mut tests = 0; + let mut props = 0; + for line in src.lines() { + let t = line.trim_start(); + if t.starts_with("//") { + continue; + } + tests += t.matches("#[test]").count(); + if t.starts_with("proptest!") { + props += 1; + } + } + (tests, props) +} + +/// The tests a `-- --list` output names: the lines that end in `: test`. +fn count_listed(stdout: &[u8]) -> usize { + String::from_utf8_lossy(stdout).lines().filter(|l| l.ends_with(": test")).count() +} + +/// Runs `cargo test -q -p -- --list` and counts the tests it lists. Output past `limit` is +/// an error; a command that cannot start or fails is a [`Harness::Failed`] row. +fn harness_count(cargo: &mut impl FnMut() -> Command, package: &str, limit: u64) -> Result { + let mut cmd = cargo(); + cmd.args(["test", "-q", "-p", package, "--", "--list"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(e) => return Ok(Harness::Failed(format!("could not start: {e}"))), + }; + let read = match child.stdout.take() { + Some(stdout) => read_bounded(stdout, limit), + None => Err(io::Error::other("no output pipe")), + }; + let stdout = match read { + Ok(Some(stdout)) => stdout, + Ok(None) => { + stop(&mut child); + return Err(Error::HarnessOutputTooLarge { package: package.to_owned(), limit }); + } + Err(e) => { + stop(&mut child); + return Ok(Harness::Failed(format!("reading its output: {e}"))); + } + }; + match child.wait() { + Ok(status) if status.success() => Ok(Harness::Listed(count_listed(&stdout))), + Ok(status) => Ok(Harness::Failed(format!("exited with {status}"))), + Err(e) => Ok(Harness::Failed(format!("waiting for it: {e}"))), + } +} + +/// Ends a child whose output is no longer read. +fn stop(child: &mut std::process::Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::{Counts, Error, Harness, Limits, Options, Report, Row, Walker, collect, count_listed, count_tests, read_bounded, write_table}; + use std::collections::HashSet; + use std::path::{Path, PathBuf}; + use std::process::Command; + + /// A new, private directory: `create_dir` fails if the name exists (even as a link), so a + /// directory somebody else made in advance is never used. + fn private_dir(tag: &str) -> PathBuf { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("craft-xtask-stats-{tag}-{}-{n}", std::process::id())); + let mut b = std::fs::DirBuilder::new(); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + match b.create(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("{e}"), + } + n += 1; + } + } + + fn walk_with(dir: &Path, limits: &Limits) -> Result { + Walker { limits, members: HashSet::new(), entries: 0, bytes: 0 }.walk(dir) + } + + fn walk(dir: &Path) -> Result { + walk_with(dir, &Limits::default()) + } + + /// `cargo metadata --no-deps` JSON for packages `(id, name, folder)`, all workspace members. + fn metadata(packages: &[(&str, &str, &Path)]) -> Vec { + let list: Vec<_> = + packages.iter().map(|(id, name, dir)| serde_json::json!({ "id": id, "name": name, "manifest_path": dir.join("Cargo.toml") })).collect(); + let ids: Vec<_> = packages.iter().map(|(id, _, _)| id).collect(); + serde_json::to_vec(&serde_json::json!({ "packages": list, "workspace_members": ids })).unwrap() + } + + fn no_cargo() -> Command { + panic!("cargo is only run in exact mode") + } + + #[test] + fn counts_attributes_and_proptest_blocks() { + let src = "#[test]\nfn a() {}\n// #[test] commented\n #[test]\nfn b() {}\nproptest! {\n}\n"; + assert_eq!(count_tests(src), (2, 1)); + } + + #[cfg(unix)] + #[test] + fn a_walk_does_not_follow_directory_links() { + let dir = private_dir("loop"); + std::fs::write(dir.join("a.rs"), "#[test]\n").unwrap(); + std::os::unix::fs::symlink(&dir, dir.join("loop")).unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(&dir); + let c = c.unwrap(); + assert_eq!((c.files, c.tests), (1, 1)); + } + + /// A directory alias does not cause its Rust source to be counted twice. + #[cfg(unix)] + #[test] + fn walk_does_not_follow_directory_symlinks() { + use std::os::unix::fs::symlink; + let base = private_dir("xtask"); + let real = base.join("real"); + std::fs::create_dir_all(&real).unwrap(); + std::fs::write(real.join("a.rs"), "fn a() {}\n").unwrap(); + // A directory symlink pointing back at `real` would be re-scanned if followed. + symlink(&real, base.join("alias")).unwrap(); + let c = walk(&base).unwrap(); + assert_eq!(c.files, 1, "the aliased directory was followed and counted twice"); + std::fs::remove_dir_all(&base).ok(); + } + + /// Traversal reports an exhausted entry budget and accepts a tree that exactly fits it. + #[test] + fn walk_reports_budget_exhaustion() { + let base = private_dir("stats-budget"); + std::fs::write(base.join("a.rs"), "fn a() {}\n").unwrap(); + let none = walk_with(&base, &Limits { entries: 0, ..Limits::default() }); + let one = walk_with(&base, &Limits { entries: 1, ..Limits::default() }); + std::fs::remove_dir_all(&base).unwrap(); + assert!(matches!(none, Err(Error::TooManyEntries { limit: 0, .. })), "{none:?}"); + assert_eq!(one.unwrap().files, 1); + } + + #[test] + fn a_source_past_the_size_limit_is_not_read() { + let dir = private_dir("size"); + let (small, big) = (dir.join("a.rs"), dir.join("b.rs")); + std::fs::write(&small, "fn a() {}\n").unwrap(); + std::fs::write(&big, "fn b() { }\n").unwrap(); + let limits = Limits { source_bytes: 10, ..Limits::default() }; + let mut walker = Walker { limits: &limits, members: HashSet::new(), entries: 0, bytes: 0 }; + let small_text = walker.read_source(&small); + let big_text = walker.read_source(&big); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(small_text.unwrap(), "fn a() {}\n"); + assert!(matches!(big_text, Err(Error::SourceTooLarge { limit: 10, .. })), "{big_text:?}"); + } + + #[cfg(unix)] + #[test] + fn walk_counts_regular_sources_once_and_skips_links_and_big_files() { + let dir = private_dir("walk"); + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(dir.join("a.rs"), "#[test]\nfn a() {}\n").unwrap(); + std::fs::write(sub.join("b.rs"), "fn b() {}\n").unwrap(); + // A directory link back to the root and a file link are not followed. + std::os::unix::fs::symlink(&dir, sub.join("loop")).unwrap(); + std::os::unix::fs::symlink(dir.join("a.rs"), sub.join("link.rs")).unwrap(); + let linked = walk(&dir); + // A source over the size limit is an error, not a silently smaller count. + std::fs::write(dir.join("big.rs"), "x".repeat(64)).unwrap(); + let big = walk_with(&dir, &Limits { source_bytes: 32, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + let c = linked.unwrap(); + assert_eq!((c.files, c.tests), (2, 1)); + assert!(matches!(big, Err(Error::SourceTooLarge { limit: 32, .. })), "{big:?}"); + } + + #[test] + fn a_source_exactly_at_the_size_limit_is_read() { + let dir = private_dir("exact-size"); + std::fs::write(dir.join("a.rs"), "fn a() {}\n").unwrap(); + let at = walk_with(&dir, &Limits { source_bytes: 10, ..Limits::default() }); + let under = walk_with(&dir, &Limits { source_bytes: 9, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(at.unwrap().files, 1); + assert!(matches!(under, Err(Error::SourceTooLarge { limit: 9, .. })), "{under:?}"); + } + + #[test] + fn the_total_source_limit_spans_every_file_of_the_run() { + let dir = private_dir("total"); + std::fs::write(dir.join("a.rs"), "fn a() {}\n").unwrap(); + std::fs::write(dir.join("b.rs"), "fn b() {}\n").unwrap(); + let fits = walk_with(&dir, &Limits { total_source_bytes: 20, ..Limits::default() }); + let over = walk_with(&dir, &Limits { total_source_bytes: 19, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(fits.unwrap().files, 2); + assert!(matches!(over, Err(Error::TotalTooLarge { limit: 19, .. })), "{over:?}"); + } + + #[test] + fn a_folder_past_the_depth_limit_is_an_error() { + let dir = private_dir("depth"); + std::fs::create_dir_all(dir.join("a").join("b")).unwrap(); + std::fs::write(dir.join("a").join("b").join("c.rs"), "fn c() {}\n").unwrap(); + let fits = walk_with(&dir, &Limits { depth: 2, ..Limits::default() }); + let over = walk_with(&dir, &Limits { depth: 1, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(fits.unwrap().files, 1); + assert!(matches!(&over, Err(Error::TooDeep { path, limit: 1 }) if path.ends_with("b")), "{over:?}"); + } + + #[test] + fn build_output_fuzz_and_hidden_entries_are_skipped() { + let dir = private_dir("skip"); + for skipped in ["target", "fuzz", ".git"] { + std::fs::create_dir(dir.join(skipped)).unwrap(); + std::fs::write(dir.join(skipped).join("x.rs"), "#[test]\n").unwrap(); + } + std::fs::write(dir.join("lib.rs"), "#[test]\n").unwrap(); + std::fs::write(dir.join("notes.rs.txt"), "#[test]\n").unwrap(); + // Only folders are skipped by a leading dot; a file named so is still a source. + std::fs::write(dir.join(".hidden.rs"), "#[test]\n").unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(c.unwrap(), Counts { files: 2, lines: 2, tests: 2, proptests: 0 }); + } + + #[test] + fn a_source_that_is_not_utf8_is_an_error() { + let dir = private_dir("utf8"); + std::fs::write(dir.join("a.rs"), b"fn a() {}\n\xff\n").unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&c, Err(Error::NotUtf8(path)) if path.ends_with("a.rs")), "{c:?}"); + } + + #[test] + fn a_missing_package_folder_is_an_error() { + let dir = private_dir("missing"); + let gone = dir.join("gone"); + let json = metadata(&[("gone 0.1.0", "gone", &gone)]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&report, Err(Error::Io { path, .. }) if *path == gone), "{report:?}"); + } + + #[test] + fn metadata_over_its_limit_is_refused_before_it_is_parsed() { + let options = Options { limits: Limits { metadata_bytes: 4, ..Limits::default() }, ..Options::default() }; + let report = collect(b"not json at all", &options, no_cargo); + assert!(matches!(&report, Err(Error::Metadata(why)) if why.contains("limit")), "{report:?}"); + } + + #[test] + fn malformed_metadata_is_an_error() { + let dir = private_dir("malformed"); + let manifest = dir.join("Cargo.toml"); + let cases = [ + serde_json::json!({ "packages": [] }), + serde_json::json!({ "workspace_members": [] }), + serde_json::json!({ "workspace_members": [1], "packages": [] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "id": "a", "manifest_path": manifest }] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "id": "a", "name": "a" }] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "name": "a", "manifest_path": manifest }] }), + ]; + let results: Vec<_> = cases.iter().map(|c| collect(&serde_json::to_vec(c).unwrap(), &Options::default(), no_cargo)).collect(); + let not_json = collect(b"{", &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + for (case, result) in cases.iter().zip(&results) { + assert!(matches!(result, Err(Error::Metadata(_))), "{case}: {result:?}"); + } + assert!(matches!(not_json, Err(Error::Metadata(_))), "{not_json:?}"); + } + + #[test] + fn a_package_listed_twice_is_an_error() { + let dir = private_dir("twice"); + let twice = metadata(&[("a 0.1.0", "a", &dir), ("a 0.1.0", "a", &dir)]); + let same_folder = metadata(&[("a 0.1.0", "a", &dir), ("b 0.1.0", "b", &dir)]); + let twice = collect(&twice, &Options::default(), no_cargo); + let same_folder = collect(&same_folder, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&twice, Err(Error::Metadata(why)) if why.contains("twice")), "{twice:?}"); + assert!(matches!(&same_folder, Err(Error::Metadata(why)) if why.contains("twice")), "{same_folder:?}"); + } + + #[test] + fn packages_outside_the_workspace_are_not_walked() { + let dir = private_dir("deps"); + std::fs::write(dir.join("lib.rs"), "#[test]\n").unwrap(); + let dependency = dir.join("not-here"); + let json = serde_json::to_vec(&serde_json::json!({ + "workspace_members": ["a 0.1.0"], + "packages": [ + { "id": "dep 1.0.0", "name": "dep", "manifest_path": dependency.join("Cargo.toml") }, + { "id": "a 0.1.0", "name": "a", "manifest_path": dir.join("Cargo.toml") }, + ], + })) + .unwrap(); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + assert_eq!(report.rows.iter().map(|r| r.name.as_str()).collect::>(), ["a"]); + assert_eq!(report.total.tests, 1); + } + + #[test] + fn rows_sort_by_name_and_the_total_adds_them() { + let dir = private_dir("order"); + for (name, src) in [("zeta", "#[test]\n#[test]\n"), ("alpha", "proptest! {\n}\n")] { + std::fs::create_dir(dir.join(name)).unwrap(); + std::fs::write(dir.join(name).join("lib.rs"), src).unwrap(); + } + let json = metadata(&[("z 0.1.0", "zeta", &dir.join("zeta")), ("a 0.1.0", "alpha", &dir.join("alpha"))]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + assert_eq!(report.rows.iter().map(|r| r.name.as_str()).collect::>(), ["alpha", "zeta"]); + assert_eq!(report.total, Counts { files: 2, lines: 4, tests: 2, proptests: 1 }); + assert_eq!(report.harness_total(), None); + } + + #[test] + fn a_nested_workspace_member_is_counted_in_its_own_row_only() { + let dir = private_dir("nested"); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("src").join("main.rs"), "fn main() {}\n").unwrap(); + std::fs::create_dir_all(dir.join("xtask").join("src")).unwrap(); + std::fs::write(dir.join("xtask").join("src").join("main.rs"), "#[test]\nfn t() {}\n").unwrap(); + let json = metadata(&[("app 0.1.0", "app", &dir), ("xtask 0.1.0", "xtask", &dir.join("xtask"))]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + let rows: Vec<_> = report.rows.iter().map(|r| (r.name.as_str(), r.counts.files, r.counts.tests)).collect(); + assert_eq!(rows, [("app", 1, 0), ("xtask", 1, 1)]); + assert_eq!((report.total.files, report.total.tests), (2, 1)); + } + + fn row(name: &str, counts: Counts, harness: Option) -> Row { + Row { name: name.into(), manifest_path: PathBuf::from(name).join("Cargo.toml"), counts, harness } + } + + fn table(report: &Report) -> String { + let mut out = Vec::new(); + write_table(report, &mut out).unwrap(); + String::from_utf8(out).unwrap() + } + + #[test] + fn the_table_keeps_its_columns() { + let counts = Counts { files: 3, lines: 120, tests: 7, proptests: 1 }; + let report = Report { rows: vec![row("app-core", counts, None)], total: counts, exact: false }; + let expected = concat!( + "crate files lines #[test] proptest!\n", + "--------------------------------------------------------------\n", + "app-core 3 120 7 1\n", + "--------------------------------------------------------------\n", + "TOTAL 3 120 7 1\n", + "\n(#[test] counts source attributes; macro-generated tests count once. Use --exact for harness counts.)\n", + ); + assert_eq!(table(&report), expected); + } + + #[test] + fn the_exact_table_marks_failed_listings_and_leaves_them_out_of_the_total() { + let counts = Counts { files: 1, lines: 2, tests: 1, proptests: 0 }; + let report = Report { + rows: vec![row("a", counts, Some(Harness::Listed(4))), row("b", counts, Some(Harness::Failed("exited with 101".into())))], + total: Counts { files: 2, lines: 4, tests: 2, proptests: 0 }, + exact: true, + }; + let expected = concat!( + "crate files lines #[test] proptest! harness\n", + "-----------------------------------------------------------------------\n", + "a 1 2 1 0 4\n", + "b 1 2 1 0 error\n", + "-----------------------------------------------------------------------\n", + "TOTAL 2 4 2 0 4\n", + "\n(The harness total leaves out 1 crate(s) whose test listing failed: b.)\n", + ); + assert_eq!(table(&report), expected); + assert_eq!(report.harness_total(), Some(4)); + assert_eq!(report.harness_failures().map(|r| r.name.as_str()).collect::>(), ["b"]); + } + + #[test] + fn listed_tests_are_the_lines_that_end_in_test() { + assert_eq!(count_listed(b"a::one: test\na::two: test\nbench: benchmark\n\n2 tests, 1 benchmark\n"), 2); + assert_eq!(count_listed(b""), 0); + } + + #[test] + fn a_bounded_read_refuses_more_than_its_limit() { + assert_eq!(read_bounded(&b"abcd"[..], 4).unwrap().as_deref(), Some(&b"abcd"[..])); + assert_eq!(read_bounded(&b"abcde"[..], 4).unwrap(), None); + assert_eq!(read_bounded(&b""[..], 0).unwrap().as_deref(), Some(&b""[..])); + } + + /// A stand-in for `cargo`: `sh -c