Files
reims-vgpu/xtask/src/main.rs
T
Anees Iqbal 24c281a610 ✅ Test that checkouts keep LF whatever autocrlf says
A user's install of the development channel on Windows stopped in cargo
xtask dist: Git for Windows' installer sets core.autocrlf=true, the clone
held CRLF .metal sources, and reims-vgpu-vulkan's build script found the
committed metallibs built from other bytes. 5fdd3c05f's .gitattributes
(* text=auto eol=lf) keeps LF in every checkout, but nothing checked that
the attribute holds for the files read byte for byte.

xtask's new test asks git check-attr for text and eol of a .metal source,
the C header and a guest Info.plist, and wants auto and lf for each. With
the attribute line taken out it fails: eol is unspecified.
2026-11-27 11:30:01 -08:00

495 lines
19 KiB
Rust

//! `cargo xtask <command>`: the workspace's lints and packaging (architecture 2.1, 13.1, 11.3).
// xtask is tooling, not product behaviour: it keeps its own tables in std's maps and sorts freely.
#![allow(clippy::disallowed_types, clippy::disallowed_methods)]
mod dist;
mod header;
mod lint;
mod metallibs;
mod tools;
mod util;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use util::{Res, read, repo_root};
/// One subcommand: its name and what it does.
struct Command {
name: &'static str,
about: &'static str,
run: Runner,
}
/// A command's body: its arguments in, whether it passed out.
type Runner = fn(&[String]) -> Res<bool>;
const COMMANDS: &[Command] = &[
Command {
name: "paths",
about: "every path git tracks checks out on Windows: no device name Windows keeps (aux.rs), no character it refuses, no name ending in a dot or a space, no two paths that differ only by case",
run: cmd_paths,
},
Command {
name: "testkit",
about: "core's testkit module is gated, and only dev-dependencies turn its feature on (D50)",
run: cmd_testkit,
},
Command {
name: "header",
about: "regenerate include/reims_vgpu.h with cbindgen; --check fails when the committed header differs from cbindgen's output",
run: header::cmd_header,
},
Command {
name: "dist",
about: "the library as a plain library in target/dist-vulkan: libreims_vgpu.a and the shared library, reims_vgpu.h and reims-vgpu.pc; --profile <p>, --out DIR, --platform vulkan (the only platform, kept for the builds that name it)",
run: dist::cmd_dist,
},
#[cfg(target_os = "linux")]
Command {
name: "link-order",
about: "rewrite crates/reims-vgpu-c/link-order.txt, the order Linux's archive lays the library's functions out in: BINARY CALL_GRAPH, a QEMU lld linked with --call-graph-ordering-file=CALL_GRAPH, after this tree's dist (docs/development.md, \"The link order\")",
run: dist::order::cmd_link_order,
},
Command {
name: "metallibs",
about: "the Vulkan platform's metallibs and their record, metallibs.toml, compiled on a Mac into crates/reims-vgpu-vulkan/metallibs, which a build elsewhere takes them from, or into <dir> (RVG_METALLIB_DIR=<dir>)",
run: metallibs::cmd_metallibs,
},
Command {
name: "check",
about: "paths, testkit, header --check, the records of the prebuilt option ROM and guest kexts (make -C firmware prebuilt-check, make -C guest prebuilt-check), rustfmt, clippy, cargo nextest and the doc-tests; on a Mac, also clippy for x86-64 Linux, links to Homebrew's Vulkan loader and KosmicKrisp in ../lib of each test binary's directory (cargo nextest list), and, where Rosetta runs x86-64 code, core's tests as x86-64; off Windows, clippy for x86-64 Windows",
run: cmd_check,
},
];
fn usage() {
eprintln!("usage: cargo xtask <command> [args...]\n\ncommands:");
for c in COMMANDS {
eprintln!(" {:<13} {}", c.name, c.about);
}
}
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let Some(name) = args.first() else {
usage();
return ExitCode::from(2);
};
match COMMANDS.iter().find(|c| c.name == name) {
Some(c) => match (c.run)(args.get(1..).unwrap_or(&[])) {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::FAILURE,
Err(e) => {
eprintln!("xtask {name}: {e}");
ExitCode::FAILURE
}
},
None => {
eprintln!("xtask: unknown command `{name}`");
usage();
ExitCode::from(2)
}
}
}
fn flag(args: &[String], f: &str) -> bool {
args.iter().any(|a| a == f)
}
/// Prints a report; true when it has no errors.
fn show(name: &str, rep: &lint::Report) -> bool {
for e in &rep.errors {
eprintln!("error: {e}");
}
if rep.errors.is_empty() {
println!("{name}: ok");
} else {
eprintln!("{name}: {} errors", rep.errors.len());
}
rep.errors.is_empty()
}
// ---------------------------------------------------------------------------------------------
/// The paths git tracks in the whole tree, reims-ctl's and reims-restore's workspaces among them,
/// checked for what a Windows checkout refuses ([`lint::windows_paths`]).
fn cmd_paths(_args: &[String]) -> Res<bool> {
let out = std::process::Command::new("git")
.args(["ls-files", "-z"])
.current_dir(repo_root())
.output()
.map_err(|e| format!("git ls-files: {e}"))?;
if !out.status.success() {
return Err(format!(
"git ls-files: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
let paths: Vec<String> = String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter(|p| !p.is_empty())
.map(str::to_owned)
.collect();
Ok(show("paths", &lint::windows_paths(&paths)))
}
fn cmd_testkit(_args: &[String]) -> Res<bool> {
let root = repo_root();
let lib = read(&root.join("crates/reims-vgpu-vulkan/src/core.rs"))?;
let mut manifests = Vec::new();
for p in util::walk(&root.join("crates"), &["Cargo.toml"]) {
manifests.push((util::rel(&p, &root), read(&p)?));
}
Ok(show("testkit", &lint::testkit_manifests(&lib, &manifests)))
}
/// Runs one of the check's cargo steps, in the environment the check started in: incremental, as
/// cargo's dev and test profiles are, so a check run again after a fix rebuilds only what changed.
fn cargo(args: &[&str]) -> Res<bool> {
cargo_with(args, &[])
}
/// [`cargo`], with `env` added to Cargo's environment.
fn cargo_with(args: &[&str], env: &[(&str, &std::path::Path)]) -> Res<bool> {
let shown: String = env
.iter()
.map(|(k, v)| format!("{k}={} ", v.display()))
.collect();
println!("$ {shown}cargo {}", args.join(" "));
let status =
std::process::Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()))
.args(args)
.envs(env.iter().copied())
.current_dir(repo_root())
.status()
.map_err(|e| format!("cargo: {e}"))?;
Ok(status.success())
}
/// Runs `make` with `args` from the repository's root: one of the check's steps that are not
/// cargo's.
fn make(args: &[&str]) -> Res<bool> {
println!("$ make {}", args.join(" "));
let status = std::process::Command::new("make")
.args(args)
.current_dir(repo_root())
.status()
.map_err(|e| format!("make: {e}"))?;
Ok(status.success())
}
/// The features `check` tests with: the testkits, and the `vulkan` features, which change
/// nothing now that the Vulkan platform is the library's only one, and which the builds that name
/// them keep. Clippy lints with every feature as well.
const TESTED_FEATURES: &str =
"reims-vgpu-vulkan/testkit,reims-vgpu/testkit,reims-vgpu/vulkan,reims-vgpu-c/vulkan";
/// The Linux the library ships for, which a Mac type-checks.
const LINUX_TARGET: &str = "x86_64-unknown-linux-gnu";
/// The Windows the library is being brought up on (AGENTS.md), which every other OS
/// type-checks.
const WINDOWS_TARGET: &str = "x86_64-pc-windows-gnullvm";
/// The features another OS's target is type-checked with ([`LINUX_TARGET`] on a Mac,
/// [`WINDOWS_TARGET`] off Windows): [`TESTED_FEATURES`], and SDL's sources left unbuilt, as the
/// host has no C toolchain for that target and nothing links.
const CROSS_CHECK_FEATURES: &str = "reims-vgpu-vulkan/testkit,reims-vgpu/testkit,\
reims-vgpu/vulkan,reims-vgpu-c/vulkan,reims-vgpu-window/sdl-no-link";
/// The variable jemalloc's build script (`tikv-jemalloc-sys`, the C API's allocator on
/// [`LINUX_TARGET`]) reads for that target as a library to link in place of the one it builds. A
/// Mac's type-check of Linux sets it to an empty archive ([`empty_archive`]), as the Mac has no
/// Linux C toolchain to build jemalloc with and nothing links.
const LINUX_JEMALLOC_OVERRIDE: &str = "X86_64_UNKNOWN_LINUX_GNU_JEMALLOC_OVERRIDE";
/// An archive with no members, `libjemalloc.a` under the target directory, written for
/// [`LINUX_JEMALLOC_OVERRIDE`].
fn empty_archive() -> Res<std::path::PathBuf> {
let dir = tools::target_dir(&mut tools::System)?.join("linux-check");
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let path = dir.join("libjemalloc.a");
std::fs::write(&path, b"!<arch>\n").map_err(|e| format!("{}: {e}", path.display()))?;
Ok(path)
}
/// The Vulkan libraries a Mac's tests load, under Homebrew's prefix: its loader, and Mesa's
/// KosmicKrisp, each through its formula's `opt` directory, which `brew upgrade` moves to the new
/// version, as the Makefile's `vulkan-links` links them for QEMU.
const MAC_TEST_LIBS: [&str; 2] = [
"opt/vulkan-loader/lib/libvulkan.1.dylib",
"opt/mesa/lib/libvulkan_kosmickrisp.dylib",
];
/// Where each of `binaries` finds the Vulkan libraries: `../lib` from its directory, where the rt
/// platform looks (`crates/reims-vgpu-vulkan/src/os/macos/rt_driver.rs`), each once, sorted.
fn test_lib_dirs(binaries: &[PathBuf]) -> Vec<PathBuf> {
let mut dirs: Vec<_> = (binaries.iter())
.filter_map(|b| Some(b.parent()?.parent()?.join("lib")))
.collect();
dirs.sort();
dirs.dedup();
dirs
}
/// A symbolic link at `at` to `to`.
#[cfg(unix)]
fn symlink(to: &Path, at: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(to, at)
}
/// A symbolic link at `at` to `to`: refused, as only a Mac's check links.
#[cfg(not(unix))]
fn symlink(_to: &Path, _at: &Path) -> std::io::Result<()> {
Err(std::io::Error::other("the check links only on a Mac"))
}
/// On a Mac, links [`MAC_TEST_LIBS`] where each test binary of the run loads them
/// ([`test_lib_dirs`]): the rt platform loads both only from beside the process's executable or
/// from `../lib`, and without them every test that opens a device finds none. Where Cargo puts a
/// test binary is its own: `<target>/debug/deps` before its build-dir layout,
/// `build/<crate>/<hash>/out` under it. So the paths are nextest's, from `cargo nextest list`
/// with the run's arguments, which builds the binaries the run then takes. A file Homebrew lacks
/// is named and not linked, as `vulkan-links` does. False where the list fails or names no binary.
fn link_mac_test_libs(features: &str) -> Res<bool> {
let args = [
"nextest",
"list",
"--workspace",
"--features",
features,
"--list-type",
"binaries-only",
"--message-format",
"json",
];
println!("$ cargo {}", args.join(" "));
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
let out = std::process::Command::new(cargo)
.args(args)
.current_dir(repo_root())
.stderr(std::process::Stdio::inherit())
.output()
.map_err(|e| format!("cargo: {e}"))?;
if !out.status.success() {
println!("check: cargo nextest list failed ({})", out.status);
return Ok(false);
}
let listed = tools::json_strings(&String::from_utf8_lossy(&out.stdout), "binary-path");
let binaries: Vec<PathBuf> = listed.into_iter().map(PathBuf::from).collect();
if binaries.is_empty() {
println!("check: cargo nextest list named no test binary");
return Ok(false);
}
let dirs = test_lib_dirs(&binaries);
let prefix = match tools::Tools::output(&mut tools::System, "brew", &["--prefix".to_owned()]) {
Ok(p) => PathBuf::from(p),
Err(e) => {
println!("check: no Homebrew ({e}): no Vulkan library linked for the tests");
return Ok(true);
}
};
for lib in MAC_TEST_LIBS {
let from = prefix.join(lib);
let name = from.file_name().unwrap_or_default();
if !from.is_file() {
println!(
"check: Homebrew has no {}: {} not linked for the tests",
from.display(),
name.to_string_lossy()
);
continue;
}
for dir in &dirs {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let at = dir.join(name);
// A link left by an earlier check, which may name another prefix.
let _ = std::fs::remove_file(&at);
symlink(&from, &at).map_err(|e| format!("{}: {e}", at.display()))?;
}
println!(
"check: {} linked in {} directories, ../lib of the {} test binaries",
name.to_string_lossy(),
dirs.len(),
binaries.len()
);
}
Ok(true)
}
/// The macOS core's tests run as under Rosetta, with the x86-64 guest's pages.
const X86_64_MACOS_TARGET: &str = "x86_64-apple-darwin";
/// core's tests, which run as [`X86_64_MACOS_TARGET`] too: the Vulkan crate's unit tests in its
/// `core` module, a nextest filter over the crate's library (`-p reims-vgpu-vulkan --lib`).
const CORE_TESTS: &str = "test(/^core::/)";
/// Whether this Mac runs x86-64 code: an x86-64 `true` run under `arch -x86_64` exits 0, which
/// it does where Rosetta is installed (and on an Intel Mac); without Rosetta the launch fails.
fn runs_x86_64() -> bool {
std::process::Command::new("/usr/bin/arch")
.args(["-x86_64", "/usr/bin/true"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
fn cmd_check(args: &[String]) -> Res<bool> {
let mut ok = true;
// First, as the cheapest: a path Windows refuses stops every checkout there.
ok &= cmd_paths(&[])?;
ok &= cmd_testkit(&[])?;
ok &= header::cmd_header(&["--check".to_owned()])?;
// The option ROM and the guest's kexts reims-ctl carries are built from the tree's sources:
// a change to what they are built from (the wire header among them) without them built
// again fails here, though the library's checks reach neither (firmware/prebuilt.sh,
// guest/tools/prebuilt.py).
ok &= make(&["-C", "firmware", "prebuilt-check"])?;
ok &= make(&["-C", "guest", "prebuilt-check"])?;
if !flag(args, "--no-cargo") {
let features = TESTED_FEATURES;
ok &= cargo(&["fmt", "--all", "--check"])?;
let clippy = |more: &[&str], env: &[(&str, &std::path::Path)]| {
let mut args = vec!["clippy", "--workspace", "--all-targets"];
args.extend_from_slice(more);
args.extend(["--", "-D", "warnings"]);
cargo_with(&args, env)
};
// Every feature, SDL3's macOS window among them; then the tested features without the
// default ones, so the macOS library without SDL (`macos-sdl` off,
// `native/macos/sdl_off.rs`) is checked too.
ok &= clippy(&["--all-features"], &[])?;
ok &= clippy(&["--no-default-features", "--features", features], &[])?;
if cfg!(target_os = "macos") {
// Every Linux file, type-checked with no Linux host: build scripts run on the Mac,
// and nothing links.
let jemalloc = empty_archive()?;
ok &= clippy(
&["--target", LINUX_TARGET, "--features", CROSS_CHECK_FEATURES],
&[(LINUX_JEMALLOC_OVERRIDE, &jemalloc)],
)?;
}
if !cfg!(target_os = "windows") {
// Every Windows file, type-checked from the Mac or Linux as Linux's are from the
// Mac: nothing else here builds for Windows, which links no jemalloc.
ok &= clippy(
&[
"--target",
WINDOWS_TARGET,
"--features",
CROSS_CHECK_FEATURES,
],
&[],
)?;
}
if cfg!(target_os = "macos") {
ok &= link_mac_test_libs(features)?;
}
ok &= cargo(&[
"nextest",
"run",
"--workspace",
"--features",
features,
"--no-fail-fast",
])?;
if cfg!(target_os = "macos") {
if runs_x86_64() {
ok &= cargo(&[
"nextest",
"run",
"-p",
"reims-vgpu-vulkan",
"--lib",
"--target",
X86_64_MACOS_TARGET,
"--no-fail-fast",
"-E",
CORE_TESTS,
])?;
} else {
println!(
"check: core's tests as {X86_64_MACOS_TARGET} skipped: this Mac runs no \
x86-64 code (`softwareupdate --install-rosetta` installs Rosetta)"
);
}
}
// nextest runs no doc-tests.
ok &= cargo(&["test", "--workspace", "--features", features, "--doc"])?;
}
println!("check: {}", if ok { "ok" } else { "FAILED" });
Ok(ok)
}
#[cfg(test)]
mod tests {
use super::*;
/// A target the check type-checks that the toolchain file does not install fails the check
/// on a host that never added it by hand.
#[test]
fn the_cross_checked_targets_are_in_the_toolchain_file() {
let toolchain = read(&repo_root().join("rust-toolchain.toml")).unwrap();
let targets = toolchain
.split_once("targets = [")
.and_then(|(_, rest)| rest.split_once(']'))
.map(|(list, _)| list)
.expect("rust-toolchain.toml lists its targets");
for target in [LINUX_TARGET, WINDOWS_TARGET, X86_64_MACOS_TARGET] {
assert!(
targets.contains(&format!("\"{target}\"")),
"{target} in {targets}"
);
}
}
/// Text is checked out with LF line ends whatever core.autocrlf says (5fdd3c05f): Git for
/// Windows' installer sets it true, and a user's install then stopped in `cargo xtask dist`,
/// where reims-vgpu-vulkan's build script hashed CRLF .metal sources against the committed
/// metallibs. Asked of git for files the build and its checks read byte for byte.
#[test]
fn text_is_checked_out_with_lf_whatever_autocrlf_says() {
let files = [
"crates/reims-vgpu-vulkan/src/gpu/shaders.metal",
"crates/reims-vgpu-c/include/reims_vgpu.h",
"guest/prebuilt/ReimsGraphics.kext/Contents/Info.plist",
];
let out = std::process::Command::new("git")
.args(["check-attr", "text", "eol", "--"])
.args(files)
.current_dir(repo_root())
.output()
.expect("git check-attr");
assert!(out.status.success(), "{out:?}");
let said: String = files
.iter()
.map(|f| format!("{f}: text: auto\n{f}: eol: lf\n"))
.collect();
assert_eq!(String::from_utf8_lossy(&out.stdout), said);
}
/// Each test binary's `../lib`, once a directory: under Cargo's build-dir layout each binary
/// has a directory of its own, and before it they share `deps`.
#[test]
fn the_test_libs_go_in_lib_beside_each_binarys_directory() {
let binaries = [
"/t/debug/build/a/1f/out/a-1f",
"/t/debug/build/a/2e/out/a-2e",
"/t/debug/deps/b-3d",
"/t/debug/deps/c-4c",
]
.map(PathBuf::from);
assert_eq!(
test_lib_dirs(&binaries),
[
"/t/debug/build/a/1f/lib",
"/t/debug/build/a/2e/lib",
"/t/debug/lib",
]
.map(PathBuf::from)
);
}
}