diff --git a/Cargo.lock b/Cargo.lock index 1f6a230b66..f4935768f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4864,6 +4864,7 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "libc", "serde_json", "tempfile", ] diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..5b86932aeb 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -13,13 +13,19 @@ 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 = [] +lock = ["dep:libc"] # 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 } serde_json = { workspace = true, optional = true } +[target.'cfg(unix)'.dependencies] +# O_NONBLOCK and O_NOFOLLOW for lock and owner opens that must not wait on a FIFO or follow a symlink. Constants only. +libc = { version = "0.2", optional = true } + [dev-dependencies] tempfile = "3" diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 02b604a5af..de63234f7e 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -10,8 +10,10 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `assets` | always | `Policy`, `RowMode`, `check`, `run`, `list_files`, `read_document`, `is_asset`, `ASSET_EXT`: the asset attribution check against the document, folders and extensions the app supplies | | `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 @@ -51,6 +53,9 @@ fn ci() -> Result<(), String> { `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. +- On Unix a child started by `run_cancelable` is not in the terminal's foreground process group. A + child that reads from the terminal is stopped by `SIGTTIN`, and the run waits until the `Cancel` flag + is set. Run a command that reads from the terminal with `run`. ## Errors @@ -151,7 +156,9 @@ process ends. A slot count of 0 or more than 64, or a poll interval (`with_poll` 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 +behind. An owner entry that is a link, or on Unix a file with more than one name, is also left +out, and a link is not followed. On Unix, a lock or owner open does not wait on a FIFO: a FIFO +lock file counts as a free slot to `holders`, and taking it is a lock error. 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 @@ -175,6 +182,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 | @@ -182,7 +225,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 | | `assets`: `is_asset`, the exact-row check, `run`, the three asset folders and the test `detects_unattributed_assets` | VectorCraft `xtask/src/assets.rs` at [bada8e1](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/assets.rs) and DesignCraft `xtask/src/assets.rs` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/assets.rs) | | `assets`: the CADCraft and WordCraft extension lists, the `-z` listing, the exit-status check and the tests in `assets::tests::wordcraft` | CADCraft `xtask/src/assets.rs` at [8e69890](https://github.com/storytold/cadcraft/blob/8e6989022398ff5f79adaab77d19fdd7137591f3/xtask/src/assets.rs), WordCraft `xtask/src/assets.rs` at [42a5df5](https://github.com/storytold/wordcraft/blob/42a5df5f94e03288037f731ffd86dee7c7cf1332/xtask/src/assets.rs) | | `assets`: the DeckCraft extension list, the pattern table and the tests in `assets::tests::deckcraft` | DeckCraft `xtask/src/assets.rs` at [b0c77eb](https://github.com/storytold/deckcraft/blob/b0c77ebd6a6fe6c9037cfbe1c8a7f397304b2205/xtask/src/assets.rs) | @@ -198,6 +245,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. | | VectorCraft, DesignCraft, CADCraft, DeckCraft, WordCraft, GridCraft, LightCraft | Planned: `xtask/src/assets.rs` moves to `assets`, each with its own document, folders and row mode; LightCraft with `RowMode::Patterns`, its forbidden extensions and names, and `license_column: Some(4)`. The `cargo xtask assets` output stays in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index cf9e346e8c..ab7f3b0569 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -15,6 +15,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; @@ -44,6 +45,15 @@ pub mod lock; #[cfg(feature = "report")] pub mod report; pub mod runner; +#[cfg(feature = "stats")] +pub mod stats; + +/// Writes one diagnostic line to stderr. A failed write, such as one to a closed pipe, is ignored, so a +/// diagnostic never stops a run. +pub(crate) fn note(line: std::fmt::Arguments<'_>) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{line}"); +} /// 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/lock.rs b/crates/xtask/src/lock.rs index 965b71408d..01cc5cdb6d 100644 --- a/crates/xtask/src/lock.rs +++ b/crates/xtask/src/lock.rs @@ -90,8 +90,7 @@ pub fn try_acquire(config: &LockConfig) -> Result, Error> { 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())))?; + let file = no_wait().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, @@ -112,7 +111,7 @@ fn record_owner(lock: &Path, label: &str) -> PathBuf { 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()); + crate::note(format_args!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display())); } owner_file } @@ -120,7 +119,8 @@ fn record_owner(lock: &Path, label: &str) -> PathBuf { /// 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. +/// its [`Held`] guard left its owner file behind. An owner entry that is a link, or on Unix a file +/// with more than one name, is left out too. pub fn holders(config: &LockConfig) -> Result, Error> { config.check()?; Ok((0..config.slots) @@ -130,10 +130,27 @@ pub fn holders(config: &LockConfig) -> Result, Error> { .collect()) } +/// Open options that do not wait on a FIFO under a name in a shared lock directory. On Unix the open +/// returns at once, and a write open of a FIFO with no reader fails. +#[cfg(unix)] +fn no_wait() -> OpenOptions { + use std::os::unix::fs::OpenOptionsExt; + let mut options = OpenOptions::new(); + options.custom_flags(libc::O_NONBLOCK); + options +} + +/// Open options that do not wait on a FIFO under a name in a shared lock directory. +#[cfg(not(unix))] +fn no_wait() -> OpenOptions { + OpenOptions::new() +} + /// 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. +/// created, without waiting on a FIFO; 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) { + match no_wait().read(true).open(lock) { Ok(file) => matches!(file.try_lock_shared(), Err(TryLockError::WouldBlock)), Err(_) => false, } @@ -141,20 +158,47 @@ fn is_held(lock: &Path) -> bool { 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()?; + open_owner(path)?.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) } +/// Opens an owner file for reading when the entry is a regular file with no other name. A link planted +/// under the name in a shared lock directory is not followed, and the open does not wait on a FIFO. +#[cfg(unix)] +fn open_owner(path: &Path) -> Option { + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + let file = OpenOptions::new().read(true).custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW).open(path).ok()?; + let opened = file.metadata().ok()?; + (opened.is_file() && opened.nlink() == 1).then_some(file) +} + +/// Opens an owner file for reading when the entry is a regular file. The entry itself is opened, not +/// the target of a link planted under the name in a shared lock directory. +#[cfg(windows)] +fn open_owner(path: &Path) -> Option { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + let file = OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path).ok()?; + file.metadata().ok()?.is_file().then_some(file) +} + +/// Opens an owner file for reading when the entry is a regular file. +#[cfg(not(any(unix, windows)))] +fn open_owner(path: &Path) -> Option { + std::fs::symlink_metadata(path).ok().filter(std::fs::Metadata::is_file)?; + File::open(path).ok() +} + /// 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); + crate::note(format_args!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots)); for h in holders(config).unwrap_or_default() { - eprintln!(" running: {h}"); + crate::note(format_args!(" running: {h}")); } }) } @@ -170,7 +214,7 @@ fn acquire_with(config: &LockConfig, cancel: Option<&Cancel>, on_wait: impl FnOn 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()); + crate::note(format_args!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64())); return Ok(held); } } @@ -259,6 +303,75 @@ mod tests { assert_eq!(holders(&c).unwrap(), ["x".repeat(MAX_OWNER_BYTES as usize)]); } + #[cfg(any(unix, windows))] + #[test] + fn owner_reads_do_not_follow_links() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let private = dir.path().join("private.txt"); + std::fs::write(&private, b"private").unwrap(); + let c = config(dir.path(), 1, ""); + let _held = try_acquire(&c).unwrap().expect("free slot"); + let owner = owner_path(&slot_path(dir.path(), 0)); + std::fs::remove_file(&owner).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&private, &owner).unwrap(); + // Creating a link on Windows needs Developer Mode or an elevated process. + #[cfg(windows)] + if std::os::windows::fs::symlink_file(&private, &owner).is_err() { + return; + } + assert!(holders(&c).unwrap().is_empty()); + } + + #[cfg(unix)] + #[test] + fn owner_reads_skip_files_with_other_names() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let private = dir.path().join("private.txt"); + std::fs::write(&private, b"private").unwrap(); + let c = config(dir.path(), 1, ""); + let _held = try_acquire(&c).unwrap().expect("free slot"); + let owner = owner_path(&slot_path(dir.path(), 0)); + std::fs::remove_file(&owner).unwrap(); + std::fs::hard_link(&private, &owner).unwrap(); + assert!(holders(&c).unwrap().is_empty()); + } + + #[cfg(unix)] + fn mkfifo(path: &Path) { + let made = std::process::Command::new("mkfifo").arg(path).status().is_ok_and(|s| s.success()); + assert!(made, "mkfifo {}", path.display()); + } + + /// A FIFO under a lock or owner name, or a link to one, is opened without waiting for a writer. + #[cfg(unix)] + #[test] + fn lock_and_owner_opens_do_not_wait_on_a_fifo() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let fifo = dir.path().join("pipe"); + mkfifo(&fifo); + + // A lock file that is a FIFO is not a held slot, and taking it fails at once. + let pipes = tempfile::tempdir().expect("temporary directory"); + std::fs::rename(&fifo, slot_path(pipes.path(), 0)).unwrap(); + assert!(holders(&config(pipes.path(), 1, "")).unwrap().is_empty()); + assert!(matches!(try_acquire(&config(pipes.path(), 1, "x")), Err(Error::Lock(_)))); + + // A held slot whose owner entry is a link to a FIFO. + mkfifo(&fifo); + let c = config(dir.path(), 1, ""); + let _held = try_acquire(&c).unwrap().expect("free slot"); + let owner = owner_path(&slot_path(dir.path(), 0)); + std::fs::remove_file(&owner).unwrap(); + std::os::unix::fs::symlink(&fifo, &owner).unwrap(); + assert!(holders(&c).unwrap().is_empty()); + assert!(open_owner(&owner).is_none()); + assert!(open_owner(&fifo).is_none()); + } + #[test] fn owner_files_of_free_slots_are_not_holders() { let _guard = crate::spawn_guard(); diff --git a/crates/xtask/src/runner.rs b/crates/xtask/src/runner.rs index 459e9e8869..e798e817ef 100644 --- a/crates/xtask/src/runner.rs +++ b/crates/xtask/src/runner.rs @@ -394,7 +394,7 @@ pub fn cargo(root: &Path) -> Command { /// /// 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}"); + crate::note(format_args!("$ {label}")); let status = cmd.status().map_err(|e| spawn_error(label, &e))?; exit_result(label, status) } @@ -405,18 +405,40 @@ pub fn run(mut cmd: Command, label: &str) -> Result<(), String> { /// 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. +/// be run, only the child itself is ended. `taskkill` finds the tree through the running child, so on +/// Windows the processes a child started keep running when the child has already exited. +/// +/// On Unix the child's process group is not the terminal's foreground group. A child that reads from +/// the terminal is stopped by `SIGTTIN`, and this function waits until `cancel` is set. Run a command +/// that reads from the terminal with [`run`]. pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result<(), String> { - eprintln!("$ {label}"); + crate::note(format_args!("$ {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))?; + let mut child = spawn(&mut cmd, label)?; + wait_cancelable(&mut child, label, cancel) +} + +/// Waits for `child`, ending its group or tree when `cancel` is set. The flag is checked before and +/// after each look at the child's status, so a child that exits before or while `cancel` is set still +/// has its group or tree ended, and the run counts as canceled. +fn wait_cancelable(child: &mut Child, label: &str, cancel: &Cancel) -> Result<(), String> { + wait_cancelable_with(child, label, cancel, Child::try_wait) +} + +/// [`wait_cancelable`] that reads the child's status with `status`. +fn wait_cancelable_with( + child: &mut Child, + label: &str, + cancel: &Cancel, + mut status: impl FnMut(&mut Child) -> io::Result>, +) -> Result<(), String> { loop { - if let Some(status) = child.try_wait().map_err(|e| format!("{label}: {e}"))? { - return exit_result(label, status); - } + // The status is not read once `cancel` is set, so a child that is still running is not reaped + // before its tree is ended. + let exited = if cancel.is_canceled() { Ok(None) } else { status(child) }; if cancel.is_canceled() { - let killed = end_tree(&mut child); + let killed = end_tree(child); let reaped = child.wait(); return match (killed, reaped) { (_, Ok(_)) => Err(format!("{label}: canceled")), @@ -424,6 +446,9 @@ pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result< (Ok(()), Err(w)) => Err(format!("{label}: canceled, but waiting for the child failed ({w})")), }; } + if let Some(status) = exited.map_err(|e| format!("{label}: {e}"))? { + return exit_result(label, status); + } std::thread::sleep(CHILD_POLL); } } @@ -444,6 +469,14 @@ fn end_tree(child: &mut Child) -> io::Result<()> { } } +/// Starts `cmd` and closes its stdin when the caller piped it, as `Command::status` does in [`run`], so +/// a child that reads stdin to the end can exit. +fn spawn(cmd: &mut Command, label: &str) -> Result { + let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?; + drop(child.stdin.take()); + Ok(child) +} + fn spawn_error(label: &str, e: &io::Error) -> String { format!("{label}: failed to spawn: {e}") } @@ -486,7 +519,7 @@ fn select_test( TestMode::PreferNextest => { let found = probe(); if !found { - eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + crate::note(format_args!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)")); } found } @@ -744,6 +777,8 @@ mod tests { 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 STDIN_CHILD: &str = "CRAFT_XTASK_STDIN_CHILD"; + const CLOSED_STDERR_CHILD: &str = "CRAFT_XTASK_CLOSED_STDERR_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`. @@ -785,6 +820,141 @@ mod tests { io::Read::read_to_end(&mut lines, &mut Vec::new()).expect("pipe end"); } + #[test] + fn spawn_closes_a_piped_stdin() { + let _guard = crate::spawn_guard(); + let mut cmd = test_child("runner::tests::stdin_child", STDIN_CHILD); + cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()); + // The child reads stdin to the end, so it exits only once the pipe is closed. A failed check + // drops the child's stdin with it, so the child still exits. + let mut child = spawn(&mut cmd, "stdin").expect("child"); + assert!(child.stdin.is_none(), "the child's stdin is still open"); + assert!(child.wait().expect("child").success()); + } + + #[test] + fn a_child_that_exits_after_cancel_counts_as_canceled() { + let _guard = crate::spawn_guard(); + // The filter matches no test, so the child exits at once with success. Waiting here first + // stands for a child that exits while `cancel` is already set. + let mut cmd = test_child("runner::tests::no_such_test", "CRAFT_XTASK_EXITED_CHILD"); + cmd.stdout(Stdio::null()).stderr(Stdio::null()); + let mut child = spawn(&mut cmd, "exited").expect("child"); + assert!(child.wait().expect("child").success()); + let cancel = Cancel::new(); + cancel.cancel(); + assert_eq!(wait_cancelable(&mut child, "exited", &cancel), Err("exited: canceled".to_owned())); + } + + #[test] + fn a_child_that_exits_as_cancel_is_set_counts_as_canceled() { + let _guard = crate::spawn_guard(); + let mut cmd = test_child("runner::tests::no_such_test", "CRAFT_XTASK_EXITED_CHILD"); + cmd.stdout(Stdio::null()).stderr(Stdio::null()); + let mut child = spawn(&mut cmd, "exited").expect("child"); + let cancel = Cancel::new(); + // `cancel` is set while the status is read, after the flag's last check before the read. + let result = wait_cancelable_with(&mut child, "exited", &cancel, |c| { + cancel.cancel(); + c.wait().map(Some) + }); + assert_eq!(result, Err("exited: canceled".to_owned())); + } + + #[test] + fn the_status_is_not_read_once_cancel_is_set() { + let _guard = crate::spawn_guard(); + let mut cmd = test_child("runner::tests::no_such_test", "CRAFT_XTASK_EXITED_CHILD"); + cmd.stdout(Stdio::null()).stderr(Stdio::null()); + let mut child = spawn(&mut cmd, "exited").expect("child"); + let cancel = Cancel::new(); + cancel.cancel(); + let mut reads = 0; + let result = wait_cancelable_with(&mut child, "exited", &cancel, |c| { + reads += 1; + c.try_wait() + }); + assert_eq!(result, Err("exited: canceled".to_owned())); + assert_eq!(reads, 0, "the status was read after cancel was set"); + } + + #[cfg(unix)] + #[test] + fn a_child_that_exits_as_cancel_is_set_has_its_group_ended() { + use io::BufRead; + let _guard = crate::spawn_guard(); + let (reader, writer) = io::pipe().expect("pipe"); + let mut cmd = test_child("runner::tests::tree_child", TREE_CHILD); + cmd.stdout(writer).stderr(Stdio::null()); + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = spawn(&mut cmd, "tree").expect("child"); + drop(cmd); + // 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"); + } + let cancel = Cancel::new(); + // The direct child is killed while `cancel` is set, and its own child keeps running. + let result = wait_cancelable_with(&mut child, "tree", &cancel, |c| { + cancel.cancel(); + c.kill()?; + c.wait().map(Some) + }); + if result != Err("tree: canceled".to_owned()) { + // A failed check still ends the group, so the test leaves no process behind. + let _ = end_tree(&mut child); + } + assert_eq!(result, 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"); + } + + #[test] + fn diagnostics_to_a_closed_stderr_do_not_panic() { + let _guard = crate::spawn_guard(); + let (reader, writer) = io::pipe().expect("pipe"); + drop(reader); + let mut child = test_child("runner::tests::closed_stderr_child", CLOSED_STDERR_CHILD); + child.stdout(Stdio::null()).stderr(writer); + let status = child.status().expect("child"); + assert!(status.success(), "the child failed with a closed stderr: {status}"); + } + + /// Reads stdin to the end; run by `spawn_closes_a_piped_stdin`. + #[test] + #[ignore = "child process of spawn_closes_a_piped_stdin"] + fn stdin_child() { + if std::env::var_os(STDIN_CHILD).is_some() { + io::Read::read_to_end(&mut io::stdin(), &mut Vec::new()).expect("stdin"); + } + } + + /// Prints every diagnostic to a stderr whose reading end is closed; run by + /// `diagnostics_to_a_closed_stderr_do_not_panic`. + #[test] + #[ignore = "child process of diagnostics_to_a_closed_stderr_do_not_panic"] + fn closed_stderr_child() { + if std::env::var_os(CLOSED_STDERR_CHILD).is_none() { + return; + } + let missing = "craft-xtask-test-no-such-program"; + assert!(run(Command::new(missing), "missing").is_err_and(|e| e.contains("failed to spawn"))); + assert!(run_cancelable(Command::new(missing), "missing", &Cancel::new()).is_err_and(|e| e.contains("failed to spawn"))); + assert!(select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &["--lib"], || false).is_ok()); + #[cfg(feature = "lock")] + { + let dir = tempfile::tempdir().expect("temp dir"); + let config = crate::lock::LockConfig::new(dir.path(), 1, "holder"); + let _held = crate::lock::try_acquire(&config).expect("lock").expect("free slot"); + let cancel = Cancel::new(); + cancel.cancel(); + assert_eq!(crate::lock::acquire(&config, Some(&cancel)).err(), Some(Error::Canceled { step: None })); + } + } + /// 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"] diff --git a/crates/xtask/src/stats.rs b/crates/xtask/src/stats.rs new file mode 100644 index 0000000000..7a381dc807 --- /dev/null +++ b/crates/xtask/src/stats.rs @@ -0,0 +1,899 @@ +//! `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())); + #[cfg_attr(not(unix), allow(unused_mut))] + 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