Files
vectorcraft/xtask/src/main.rs
T
dotCooCoo fb3f2d545f CI: the build job runs each shard's doctests in a command of its own
`cargo xtask ci doctests` ran the doctests of every workspace member in
one `cargo test --doc`, which resolves features over all of them and
rebuilt the libraries the per-shard builds had built: the step took 24
minutes in the build job of pull request run 47488581650. It now runs
one `cargo test --doc` per shard with the crates `ci shard` runs them
for. On the build host, after `ci archive`, the step took 34 seconds.
2026-12-04 23:58:57 -08:00

762 lines
37 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Workspace tooling: `cargo xtask <command>`.
//!
//! Pure Rust (std + serde_json). External tools (`cargo`, `curl`, `tar`) are
//! invoked through `std::process::Command`.
mod affinity_corpus;
mod assets;
mod brands;
mod bundle;
mod cache_units;
mod cursors;
mod doc_tests;
mod grant_sites;
mod ico;
mod layers;
mod pdf_deps;
mod pngsuite;
mod script_corpus;
mod sha256;
mod shards;
mod stats;
mod test262;
mod test_lint;
mod ui_commands;
mod version;
mod web_fonts;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
const USAGE: &str = "\
usage: cargo xtask <command>
commands:
assets check that every icon/image/font/asset is attributed in ASSETS.md
brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products
cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails)
grant-sites check that only the listed shipped code makes a plug-in grant token or records a grant
test-lint [--base <rev>] [--all]
weak tests in the lines changed since the base: fail on self-compares, reasonless
#[ignore], sleeps, reads of Rust source and tests no CI target runs; list only
is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env
gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit
by crate and never fails
i18n-report list the strings each language's catalog lacks, shown in English (fails only on a
broken scan; ci runs it too)
ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift
pdf-deps verify immutable shared PDF writer and patched Krilla sources
layers enforce the crate dependency layering (plan/architecture.md §3)
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker
test the workspace tests (cargo nextest when installed, else cargo test), then the doctests
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci's tests (xtask/src/shards.rs): from the
nextest archive in $NEXTEST_ARCHIVE_FILE when set, otherwise it builds them and
also runs the doctests of its crates
ci archive build every shard's tests once and write shard k's nextest archive to
$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME for k from 1 to $GATE_SHARDS; with
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for the build to that file
ci doctests the doctests of each shard's crates, one cargo command per shard
ci checks the ci steps other than the tests, the doctests and the i18n report
shards list the crates each shard tests; fails when a member is in no shard or in two,
or builds with other features in its shard than in the whole workspace
corpus [--download | --affinity | --scripts]
show where test corpora live; --download fetches PngSuite into corpus/pngsuite,
--affinity the pinned public Affinity documents into corpus/affinity, --scripts
the pinned public scripts of xtask/script-corpus.txt into corpus/scripts
bundle build dist/VectorCraft.app (macOS) with assets/app-icon/vectorcraft.icns
ico <out.ico> <png>...
pack PNGs into a Windows .ico (used by packaging/icons.sh)
scripts --pass-rate [--report <path>]
run each script in corpus/scripts headless in a process of its own and report how
many pass, as JSON (default target/script-corpus/report-<time>-<pid>.json, a new
file); script failures never fail it, and without the corpus it skips
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
test262 fetch the pinned ECMAScript conformance suite into corpus/test262 (sha256
verified), parse its ES5 subset with vectorcraft-js and run the ES5 language
and built-in tests its interpreter supports and the String, Number, RegExp
and Date built-ins tests, printing the counts; then fetch json2.js into
corpus/json2 (sha256 verified) and run it
web-fonts copy the craft-fonts faces in crates/text/web-fonts.txt into the web site, the
interface's startup and demand faces also under fonts/ui/ (the Trunk post_build
hook; a no-op without CRAFT_FONTS_DIR)
";
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let rest: Vec<&str> = args.iter().skip(1).map(String::as_str).collect();
let result = match args.first().map(String::as_str) {
Some("assets") => assets::run(&root()),
Some("brands") => brands::run(&root()),
Some("cursors") => cursors::run(&root()),
Some("grant-sites") => grant_sites::run(&root()),
Some("test-lint") => test_lint::run(&root(), &rest),
Some("i18n-report") => cmd_i18n_report(),
Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")),
Some("layers") => cmd_layers(),
Some("pdf-deps") => pdf_deps::run(&root()),
Some("wasm") => cmd_wasm(),
Some("test") => cmd_test().and_then(|()| cmd_doctests()),
Some("ci") if rest.first() == Some(&"shard") => cmd_ci_shard(),
Some("ci") if rest.first() == Some(&"archive") => cmd_ci_archive(),
Some("ci") if rest.first() == Some(&"doctests") => cmd_ci_doctests(),
Some("ci") if rest.first() == Some(&"checks") => cmd_ci_checks(),
Some("ci") => cmd_ci(),
Some("shards") => shards::run().map(drop),
Some("corpus") => cmd_corpus_args(&rest),
Some("scripts") => script_corpus::scripts(&rest),
Some("bundle") => bundle::run(&root()),
Some("ico") => ico::run(&rest),
Some("version") => version::run(&root(), &rest),
Some("stats") => stats::run(&root(), rest.contains(&"--exact")),
Some("test262") => test262::run_suite(),
Some("web-fonts") => web_fonts::run(&root()),
Some("-h" | "--help" | "help") | None => {
print!("{USAGE}");
Ok(())
}
Some(other) => Err(format!("unknown command `{other}`\n\n{USAGE}")),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
/// Workspace root (parent of the xtask crate).
pub fn root() -> PathBuf {
// The repository root, as a clean path (`join("..")` would print as `…/xtask/..`).
let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
manifest.parent().unwrap_or(manifest).to_path_buf()
}
/// Tracked and untracked (not ignored) files that exist, relative to `root`.
pub fn repo_files(root: &Path) -> Result<Vec<String>, String> {
let out = Command::new("git")
.current_dir(root)
.args(["ls-files", "-z", "--cached", "--others", "--exclude-standard"])
.output()
.map_err(|e| format!("git ls-files: {e}"))?;
if !out.status.success() {
return Err(format!("git ls-files failed: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
Ok(String::from_utf8_lossy(&out.stdout).split('\0').filter(|l| !l.is_empty() && root.join(l).exists()).map(str::to_owned).collect())
}
/// A `cargo` command (the one running xtask, else `cargo` on the PATH) run in the workspace root.
pub fn cargo() -> Command {
let mut c = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()));
c.current_dir(root());
c
}
/// Prints `what` and runs `cmd`, which must exit successfully.
fn run(mut cmd: Command, what: &str) -> Result<(), String> {
eprintln!("$ {what}");
let status = cmd.status().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) }
}
/// `vectorcraft-ui-egui` and `vectorcraft-mcp` without their default features leave
/// vectorcraft-text's bundled fonts out: no crate they depend on turns them on (docs/development.md
/// › Leaving out the bundled fonts). The same tree with the default features must show them, so a
/// change in cargo tree's output can't make the check pass by finding nothing.
fn libraries_without_bundled_fonts() -> Result<(), String> {
["vectorcraft-ui-egui", "vectorcraft-mcp"].into_iter().try_for_each(without_bundled_fonts)
}
/// `package` shows vectorcraft-text's `bundled-fonts` in its feature tree with its default features
/// and nowhere without them, for any target.
fn without_bundled_fonts(package: &str) -> Result<(), String> {
const FEATURE: &str = "vectorcraft-text feature \"bundled-fonts\"";
let tree = |defaults: bool| -> Result<String, String> {
let mut args = vec!["tree", "-p", package, "--target", "all", "-e", "features,normal", "-i", "vectorcraft-text"];
if !defaults {
args.insert(3, "--no-default-features");
}
let what = format!("cargo {}", args.join(" "));
eprintln!("$ {what}");
let out = cargo().args(&args).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
if !out.status.success() {
return Err(format!("{what}: exited with {}:\n{}", out.status, String::from_utf8_lossy(&out.stderr)));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
};
let with = tree(true)?;
if !with.contains(FEATURE) {
return Err(format!("{package} with its default features shows no {FEATURE} (has cargo tree's output changed?):\n{with}"));
}
let without = tree(false)?;
if without.contains(FEATURE) {
return Err(format!("{package} without default features still bundles the fonts:\n{without}"));
}
Ok(())
}
/// `cargo metadata --no-deps` for the workspace, as JSON.
pub fn metadata() -> Result<serde_json::Value, String> {
let out = cargo().args(["metadata", "--format-version", "1", "--no-deps"]).output().map_err(|e| format!("cargo metadata: {e}"))?;
if !out.status.success() {
return Err(format!("cargo metadata failed:\n{}", String::from_utf8_lossy(&out.stderr)));
}
serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: bad JSON: {e}"))
}
fn cmd_layers() -> Result<(), String> {
let meta = metadata()?;
let crates = layers::from_metadata(&meta)?;
println!("Dependency layering (plan/architecture.md §3)\n");
println!("{:<28} {:<14} workspace deps", "crate", "layer");
for c in &crates {
let ws: Vec<String> = c
.deps
.iter()
.filter(|d| d.workspace)
.map(|d| {
let k = match d.kind {
layers::DepKind::Normal => "",
layers::DepKind::Dev => " (dev)",
layers::DepKind::Build => " (build)",
};
format!("{}{k}", layers::short_name(&d.name))
})
.collect();
println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", "));
}
let mut violations: Vec<String> = layers::check(&crates).iter().map(ToString::to_string).collect();
violations.extend(doc_tests::check(&meta)?);
println!();
if violations.is_empty() {
println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len());
Ok(())
} else {
println!("{} violation(s):", violations.len());
for v in &violations {
println!(" - {v}");
}
Err(format!("{} violation(s)", violations.len()))
}
}
/// Workspace packages that must build for wasm32: all L0–L5 crates, the egui
/// shell, and the web app and its plug-in worker (their wasm-only code is compiled by nothing
/// else). Each comes with its
/// package id, which `-p` takes where the name would be ambiguous: craft-libs builds against this
/// repo's geom and pathops by git, so the graph can hold a second, older copy of a workspace crate.
fn wasm_set() -> Result<Vec<(String, String)>, String> {
let meta = metadata()?;
let ids: std::collections::HashMap<&str, &str> =
meta["packages"].as_array().into_iter().flatten().filter_map(|p| Some((p["name"].as_str()?, p["id"].as_str()?))).collect();
layers::from_metadata(&meta)?
.into_iter()
.filter(|c| match layers::classify(&c.name) {
Some(layers::Class::Layer(l)) => l <= 5 || layers::short_name(&c.name) == "ui-egui",
Some(layers::Class::Standalone) => true,
_ => matches!(layers::short_name(&c.name), "web" | "plugin-worker"),
})
.map(|c| {
let id = ids.get(c.name.as_str()).ok_or_else(|| format!("cargo metadata: no package id for {}", c.name))?.to_string();
Ok((c.name, id))
})
.collect()
}
/// One `cargo check` over the whole wasm set: the crates share one build, and `--keep-going`
/// reports every crate that fails rather than only the first.
fn cmd_wasm() -> Result<(), String> {
let set = wasm_set()?;
let mut c = cargo();
c.args(["check", "--target", "wasm32-unknown-unknown", "--keep-going"]);
for (_, id) in &set {
c.args(["-p", id]);
}
let names: Vec<&str> = set.iter().map(|(name, _)| name.as_str()).collect();
cache_units::run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going ({} crates: {})", set.len(), names.join(", ")))
}
/// Whether `cargo nextest` is installed.
fn has_nextest() -> bool {
cargo().args(["nextest", "--version"]).output().is_ok_and(|o| o.status.success())
}
/// The workspace's unit and integration tests, without examples (clippy still checks those).
/// nextest runs each test in its own process, in parallel across all test binaries.
fn cmd_test() -> Result<(), String> {
test_packages(&["--workspace".to_owned()], "--workspace", shards::Targets::All, None)
}
/// [`cmd_test`] for the `targets` of the packages `select` picks (`--workspace` or `-p` ids),
/// shown as `shown`; with `part`, only that part's share of their tests (xtask/src/shards.rs),
/// which needs nextest. A part runs its counted share, then its pinned tests, each with
/// nextest's default thread count. Every run finishes before the first error is returned.
fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option<shards::Part>) -> Result<(), String> {
let (listed, args) = (targets.shown(), targets.args());
if part.is_none() && !has_nextest() {
eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)");
let mut c = cargo();
c.arg("test").args(select).args(args);
return run(c, &format!("cargo test {shown} {listed}"));
}
let nextest = |sub: &str| {
let mut c = cargo();
c.args(["nextest", sub]).args(select).args(args);
c
};
nextest_tests(&nextest, &format!("{shown} {listed}"), part)
}
/// The tests of the nextest archive `file`, which `cargo xtask ci archive` wrote for one shard;
/// with `part`, that part's share of them, as [`test_packages`] runs it.
fn archive_tests(file: &Path, part: Option<shards::Part>) -> Result<(), String> {
let nextest = |sub: &str| {
let mut c = cargo();
c.args(["nextest", sub, "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
c
};
nextest_tests(&nextest, &format!("--archive-file {}", file.display()), part)
}
/// The tests `nextest(sub)` selects for `cargo nextest <sub>`, shown after the subcommand as
/// `shown`; with `part`, only that part's share of them (see [`test_packages`]).
fn nextest_tests(nextest: &dyn Fn(&str) -> Command, shown: &str, part: Option<shards::Part>) -> Result<(), String> {
if !has_nextest() {
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests, or runs an archive, needs cargo-nextest"));
}
let Some(part) = part else {
return run(nextest("run"), &format!("cargo nextest run {shown}"));
};
let mut c = nextest("list");
c.args(["--color", "never", "--message-format", "json"]);
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
if !out.status.success() {
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
}
let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?;
if !missing.is_empty() {
return Err(format!(
"cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)",
missing.join(", ")
));
}
let mut result = Ok(());
for args in part.runs() {
let mut c = nextest("run");
c.args(&args);
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
result = result.and(run(c, &format!("cargo nextest run {shown} {quoted}")));
}
result
}
/// The doctests, which nextest doesn't run.
fn cmd_doctests() -> Result<(), String> {
doctest_packages(&shards::members(&metadata()?)?)
}
/// [`cmd_doctests`] for the crates of `crates` that have doc tests.
fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> {
let crates = shards::with_doctests(crates);
if crates.is_empty() {
return Ok(());
}
let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
let mut c = cargo();
c.arg("test").args(shards::select(&crates)).arg("--doc");
run(c, &format!("cargo test {shown} --doc"))
}
/// One `cargo xtask ci` step: its name and what it runs.
type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>);
/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard,
/// and `ci checks` runs the other steps.
const TEST_STEPS: [&str; 3] = ["test", "doctests", "i18n-report"];
/// `cargo xtask ci`: each step in turn, stopping at the first that fails; the summary names the
/// steps that passed and, after a failure, the one that failed and those skipped.
fn cmd_ci() -> Result<(), String> {
run_steps(&ci_steps())
}
/// `GATE_SHARDS`, the shard count the shared gate workflow sets, for `ci <what>`; it must equal
/// the number of shards in xtask/src/shards.rs.
fn gate_shards(what: &str) -> Result<usize, String> {
let count = gate_number(what, "GATE_SHARDS")?;
if count != shards::GROUPS.len() {
return Err(format!(
"ci {what}: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
shards::GROUPS.len()
));
}
Ok(count)
}
/// The number in the environment variable `key`, which the shared gate workflow sets.
fn gate_number(what: &str, key: &str) -> Result<usize, String> {
let value = std::env::var(key).map_err(|_| format!("ci {what}: {key} is not set (the gate workflow sets it)"))?;
value.trim().parse().map_err(|_| format!("ci {what}: {key} is `{value}`, not a number"))
}
/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate
/// workflow sets them). A shard runs the tests of its crates, and the i18n report where it tests
/// vectorcraft-ui-egui; a part of a split runs its share of the tests, and only part 1 the report.
///
/// With `NEXTEST_ARCHIVE_FILE` set (the gate's shard legs), it runs the tests of that archive,
/// which `ci archive` built for this shard after the shard checks, and leaves the doctests to
/// `ci doctests`. Otherwise it runs the shard checks, builds the tests, and runs the doctests of
/// its crates on part 1 too.
fn cmd_ci_shard() -> Result<(), String> {
let count = gate_shards("shard")?;
let shard = gate_number("shard", "GATE_SHARD")?;
if !(1..=count).contains(&shard) {
return Err(format!("ci shard: GATE_SHARD is {shard}, not 1 to {count}"));
}
let archive = std::env::var_os("NEXTEST_ARCHIVE_FILE").filter(|f| !f.is_empty()).map(PathBuf::from);
let shards::Shard { runs, part } = if archive.is_some() { shards::assigned()? } else { shards::run()? }.swap_remove(shard - 1);
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(&runs));
let first = part.is_none_or(|p| p.is_first());
let report =
runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")).filter(|_| first);
let mut steps: Vec<Step> = Vec::new();
if let Some(file) = archive {
let tests = file.clone();
steps.push(("test", Box::new(move || archive_tests(&tests, part))));
if report.is_some() {
steps.push(("i18n-report", Box::new(move || i18n_report_archive(&file))));
}
return run_steps(&steps);
}
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
let report = report.map(|r| (shards::select(&r.crates), shown(&r.crates)));
let tests: Vec<(Vec<String>, String, shards::Targets)> = runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
// Each run finishes before the first error is returned.
steps.push((
"test",
Box::new(move || {
let mut result = Ok(());
for (s, w, t) in &tests {
result = result.and(test_packages(s, w, *t, part));
}
result
}),
));
// The doctests and the i18n report run once, on a split's first part.
if first {
let c = shards::unit_crates(&runs);
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
}
if let Some((select, shown)) = report {
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
}
run_steps(&steps)
}
/// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with
/// `shard-archives`). After the shard checks it builds the tests of each shard's run, one cargo
/// command per run ([`archive_builds`]), then writes the tests of shard k's run (1-based,
/// [`archived_runs`]) to the nextest archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for
/// every k up to `GATE_SHARDS`, with the run's package and target selection, so the archive's own
/// build finds them built. A split's later parts run the same binaries as part 1, so their archive
/// is a copy of part 1's.
///
/// In a leg that saves the cache, the library and binary tests' builds record their units in
/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the
/// integration tests' builds do not, so the saved entry holds every dependency and
/// dev-dependency the tests build with and none of the integration tests' executables.
fn cmd_ci_archive() -> Result<(), String> {
let var = |key: &str| {
std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)"))
};
let (dir, name) = (PathBuf::from(var("NEXTEST_ARCHIVE_DIR")?), var("NEXTEST_ARCHIVE_NAME")?);
gate_shards("archive")?;
if !has_nextest() {
return Err("ci archive: cargo-nextest is not installed".into());
}
cache_units::record_xtask()?;
let checked = shards::run()?;
let archived = archived_runs(&checked)?;
for (units, r) in archive_builds(&checked) {
let (c, what) = test_build(&r, units);
if units { cache_units::run(c, &what)? } else { run(c, &what)? }
}
for (i, (shard, r)) in checked.iter().zip(archived).enumerate() {
let file = dir.join((i + 1).to_string()).join(&name);
let parent = file.parent().unwrap_or(&dir);
std::fs::create_dir_all(parent).map_err(|e| format!("ci archive: {}: {e}", parent.display()))?;
if let Some(p) = shard.part.filter(|p| !p.is_first()) {
let first = dir.join((i + 2 - p.index).to_string()).join(&name);
std::fs::hard_link(&first, &file)
.or_else(|_| std::fs::copy(&first, &file).map(drop))
.map_err(|e| format!("ci archive: copy {} to {}: {e}", first.display(), file.display()))?;
eprintln!("ci archive: shard {} runs part {} of shard {}'s archive", i + 1, p.index, i + 2 - p.index);
continue;
}
let mut c = cargo();
c.args(["nextest", "archive"]).args(shards::select(&r.crates)).args(r.targets.args()).arg("--archive-file").arg(&file);
let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display());
run(c, &what)?;
}
Ok(())
}
/// The run of each shard, whose tests `ci archive` writes to the shard's archive with one cargo
/// selection. A shard that makes more than one run is an error.
fn archived_runs(shards: &[shards::Shard]) -> Result<Vec<&shards::Run>, String> {
shards
.iter()
.enumerate()
.map(|(i, s)| match s.runs.as_slice() {
[r] => Ok(r),
runs => Err(format!(
"ci archive: shard {} makes {} runs, and its archive holds the tests of one (xtask/src/shards.rs › GROUPS)",
i + 1,
runs.len()
)),
})
.collect()
}
/// The builds `ci archive` runs before it writes the archives, in order: `(true, run)` builds the
/// library and binary tests of a run of the first part of each shard (none for a run of
/// integration tests alone, whose crate has its library tests in a run on another shard), then
/// `(false, run)` builds each such run's integration tests.
fn archive_builds(shards: &[shards::Shard]) -> Vec<(bool, shards::Run)> {
let runs: Vec<&shards::Run> = shards.iter().filter(|s| s.part.is_none_or(|p| p.is_first())).flat_map(|s| &s.runs).collect();
let units = runs.iter().filter(|r| r.targets != shards::Targets::Integration).map(|r| (true, (*r).clone()));
let integration = runs.iter().filter(|r| r.targets != shards::Targets::Units).map(|r| (false, (*r).clone()));
units.chain(integration).collect()
}
/// The `cargo test --no-run` command that builds a run's library and binary tests (`units`) or its
/// integration tests, and its description.
fn test_build(r: &shards::Run, units: bool) -> (Command, String) {
let targets = if units { shards::Targets::Units } else { shards::Targets::Integration };
let mut c = cargo();
c.arg("test").args(shards::select(&r.crates)).args(targets.args()).arg("--no-run");
(c, format!("cargo test {} --no-run ({})", targets.shown(), shards::names(&r.crates)))
}
/// `cargo xtask ci doctests`: the doctests of each shard's crates, one cargo command per shard
/// with the crates `ci shard` runs them for, after `ci archive` (the shared gate's
/// `after-archive-command`). Every command runs before the first error is returned.
fn cmd_ci_doctests() -> Result<(), String> {
let mut result = Ok(());
for s in shards::assigned()?.iter().filter(|s| s.part.is_none_or(|p| p.is_first())) {
result = result.and(doctest_packages(&shards::unit_crates(&s.runs)));
}
result
}
/// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's
/// `lint` leg.
fn cmd_ci_checks() -> Result<(), String> {
run_steps(&ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)).collect::<Vec<_>>())
}
/// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed
/// and, after a failure, the one that failed and those skipped.
fn run_steps(steps: &[Step]) -> Result<(), String> {
let mut done = Vec::new();
for (name, f) in steps {
eprintln!("\n=== ci: {name} ===");
if let Err(e) = f() {
println!("\nCI summary:");
for d in &done {
println!(" ok {d}");
}
println!(" FAIL {name}: {e}");
for (n, _) in steps.iter().skip(done.len() + 1) {
println!(" skip {n}");
}
return Err(format!("ci failed at `{name}`"));
}
done.push(*name);
}
println!("\nCI summary: all {} steps passed ({})", done.len(), done.join(", "));
Ok(())
}
/// Every `cargo xtask ci` step, in order.
fn ci_steps() -> Vec<Step> {
vec![
(
"fmt",
Box::new(|| {
let mut c = cargo();
c.args(["fmt", "--all", "--", "--check"]);
run(c, "cargo fmt --all -- --check")
}),
),
(
"clippy",
Box::new(|| {
let mut c = cargo();
c.args(["clippy", "--workspace", "--all-targets", "--keep-going", "--", "-D", "warnings"]);
run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings")
}),
),
("test", Box::new(cmd_test)),
("doctests", Box::new(cmd_doctests)),
(
"no-bundled-fonts",
Box::new(|| {
// vectorcraft-text as embedders that bring their own fonts build it.
let mut c = cargo();
c.args(["test", "-p", "vectorcraft-text", "--no-default-features", "--test", "without_bundled_fonts"]);
run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts")?;
// The egui panels and the MCP server as such an embedder builds them: nothing turns
// the fonts back on.
libraries_without_bundled_fonts()?;
// The panels without their interface faces lint clean and still bind every family
// they draw in.
let mut c = cargo();
c.args(["clippy", "-p", "vectorcraft-ui-egui", "--no-default-features", "--all-targets", "--", "-D", "warnings"]);
run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets -- -D warnings")?;
let mut c = cargo();
c.args(["test", "-p", "vectorcraft-ui-egui", "--no-default-features", "--test", "install_fonts"]);
run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts")
}),
),
("pdf-deps", Box::new(|| pdf_deps::run(&root()))),
("assets", Box::new(|| assets::run(&root()))),
("brands", Box::new(|| brands::run(&root()))),
("grant-sites", Box::new(|| grant_sites::run(&root()))),
("cursors", Box::new(|| cursors::run(&root()))),
("test-lint", Box::new(|| test_lint::run(&root(), &[]))),
("i18n-report", Box::new(cmd_ci_i18n_report)),
("ui-commands", Box::new(|| ui_commands::run(&root(), true))),
("layers", Box::new(cmd_layers)),
("wasm", Box::new(cmd_wasm)),
]
}
/// `cargo xtask corpus` with at most one of its flags.
fn cmd_corpus_args(rest: &[&str]) -> Result<(), String> {
match rest {
[] => cmd_corpus(false),
["--download"] => cmd_corpus(true),
["--affinity"] => affinity_corpus::fetch(),
["--scripts"] => script_corpus::fetch(),
_ => Err(format!("`corpus` takes at most one of --download, --affinity and --scripts, got `{}`\n\n{USAGE}", rest.join(" "))),
}
}
fn cmd_corpus(download: bool) -> Result<(), String> {
let corpus = root().join("corpus");
println!(
"Test corpora live under {} (git-ignored, never committed).
Tests that use a corpus skip cleanly when it is absent.
corpus/pngsuite/ Original PngSuite PNGs (redistribution permitted), pinned and SHA-256
verified. Fetch: cargo xtask corpus --download
corpus/psd/ PSD samples from MIT/BSD projects (ag-psd, psd-tools test data).
Copy files in manually; licences must be MIT/BSD/CC0.
corpus/tiff/ libtiff pics (optional)
corpus/exr/ OpenEXR sample images (optional)
corpus/raw/ raw.pixls.us samples, CC0 (optional)
corpus/affinity/ public Affinity documents (CC0/MIT/Apache-2.0) at pinned commits, sha256
verified: oracles for the Affinity reader. Fetch: cargo xtask corpus --affinity
corpus/test262/ the ECMAScript conformance suite (BSD-3-Clause) at a pinned commit, sha256
verified: the JavaScript parser's and interpreter's ES5 subsets. Fetch and run:
cargo xtask test262
corpus/json2/ json2.js, the public-domain JSON polyfill, at a pinned commit, sha256 verified:
compared with vectorcraft-js's JSON. Fetch and run: cargo xtask test262
corpus/scripts/ public scripts from MIT and Apache-2.0 repositories at pinned commits, each
with its repository's license file, sha256 verified (xtask/script-corpus.txt):
the script host's headless pass rate. Fetch: cargo xtask corpus --scripts;
run: cargo xtask scripts --pass-rate
",
corpus.display()
);
if !download {
return Ok(());
}
pngsuite::fetch()
}
/// Prints the strings each language's catalog has no row for (`i18n::tests::untranslated_report`).
/// The interface shows them in English, so a gap never fails it; only a scan that finds nothing does.
fn cmd_i18n_report() -> Result<(), String> {
let mut c = cargo();
c.args(["test", "-p", "vectorcraft-ui-egui", "--lib", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]);
run(c, "cargo test -p vectorcraft-ui-egui --lib -- i18n::tests::untranslated_report --exact --nocapture")
}
/// [`cmd_i18n_report`] in `ci`, selecting the packages and targets the test stage did so it
/// reuses that build: with `-p vectorcraft-ui-egui --lib` alone cargo resolves features
/// differently and recompiled for about 3.5 minutes. Every other test binary runs with no test
/// matching the filter.
fn cmd_ci_i18n_report() -> Result<(), String> {
i18n_report_packages(&["--workspace".to_owned()], "--workspace")
}
/// [`cmd_ci_i18n_report`] for the packages `select` picks (a `ci shard`'s), shown as `shown`.
fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> {
let mut c = cargo();
c.arg("test").args(select).args(["--lib", "--bins", "--tests", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]);
run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture"))
}
/// [`cmd_ci_i18n_report`] from the nextest archive `file` of a `ci shard` that tests
/// vectorcraft-ui-egui.
fn i18n_report_archive(file: &Path) -> Result<(), String> {
let mut c = cargo();
c.args(["nextest", "run", "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
c.args(["--no-capture", "-E", "test(=i18n::tests::untranslated_report)"]);
run(c, &format!("cargo nextest run --archive-file {} --no-capture -E 'test(=i18n::tests::untranslated_report)'", file.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use shards::{Group, Split, Targets};
#[test]
fn the_archive_builds_each_run_once_library_tests_first() {
let m =
|name: &str| shards::Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true };
static SPLIT: Split = Split { crates: &["a"], pinned: &[&[], &[]] };
let groups = [
Group::Part(&SPLIT, 1),
Group::Part(&SPLIT, 2),
Group::Targets(&[(Targets::Units, &["b"])]),
Group::Targets(&[(Targets::All, &["c"]), (Targets::Integration, &["b"])]),
Group::Rest,
];
let shards = shards::assign(&groups, &[m("a"), m("b"), m("c"), m("d")]).unwrap();
let builds: Vec<(Vec<String>, String)> = archive_builds(&shards)
.iter()
.map(|(units, r)| {
let (c, what) = test_build(r, *units);
(c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(), what)
})
.collect();
let shown: Vec<&str> = builds.iter().map(|(_, what)| what.as_str()).collect();
assert_eq!(
shown,
[
"cargo test --lib --bins --no-run (a)",
"cargo test --lib --bins --no-run (b)",
"cargo test --lib --bins --no-run (c)",
"cargo test --lib --bins --no-run (d)",
"cargo test --test '*' --no-run (a)",
"cargo test --test '*' --no-run (c)",
"cargo test --test '*' --no-run (b)",
"cargo test --test '*' --no-run (d)",
]
);
assert_eq!(builds[1].0, ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]);
assert_eq!(builds[6].0, ["test", "-p", "path+file:///w/b#0.1.0", "--test", "*", "--no-run"]);
let two = archived_runs(&shards).unwrap_err();
assert!(two.contains("shard 4 makes 2 runs"), "{two}");
let real = shards::assigned().unwrap();
let archived = archived_runs(&real).unwrap();
assert_eq!(archived.len(), shards::GROUPS.len());
assert!(archived.iter().zip(&real).all(|(r, s)| s.runs == [(*r).clone()]));
}
}