From b6b174fda9e0e92be10606b2041d704da56e82fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:15:12 -0800 Subject: [PATCH 01/58] craft-testkit: add TempDir, a private test folder removed on drop TempDir::new(tag) makes a new folder craft-testkit-- in the system temporary directory with tempfile::Builder and returns an error instead of panicking. A taken name is skipped and its folder left alone. On Unix the folder has mode 0o700, and new() returns an error when the folder it made is a link, is open to other users or is owned by another user; such a folder is not removed. path() is the canonical path, so a temporary directory reached through a link works. file(name) rejects empty names, ".", "..", and names with "/", "\", ":" or NUL. Dropping the guard removes the folder, also when the test panics, and close() returns the removal error. The module is not built for wasm32. The tests of VectorCraft's TempDir and PdfCraft's ScratchDir that apply to this API keep their names. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 3 + crates/testkit/README.md | 31 +++ crates/testkit/src/lib.rs | 7 + crates/testkit/src/temp.rs | 442 +++++++++++++++++++++++++++++++++++++ 5 files changed, 486 insertions(+) create mode 100644 crates/testkit/src/temp.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..8f53a06bfe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "tempfile", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..cce60d08ae 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,5 +10,8 @@ publish = false [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tempfile = "3" + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..dd41509e7e 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,37 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Test folders: `temp` + +`TempDir::new(tag)` makes a new, empty folder `craft-testkit--` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix the folder has mode 0o700, and `new` returns an error when the folder it made is a link, is open to other users or is owned by another user. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder and returns `InvalidInput` for an empty name, `.`, `..`, or a name with `/`, `\`, `:` or NUL. The module is not built for `wasm32`. + +```rust +let dir = craft_testkit::TempDir::new("export")?; +std::fs::write(dir.file("out.png")?, &png)?; +``` + +| Module | Consumers | +|---|---| +| `temp` | VectorCraft, PdfCraft, CADCraft, `craft-media-testkit` | + +### Origin + +| Module | Source | Path | SHA | +|---|---|---|---| +| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e17` | +| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e20711` | +| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4` | +| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e698902` | + +### Migration + +| Consumer | State | +|---|---| +| VectorCraft | Not switched. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | +| PdfCraft | Not switched. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | +| CADCraft | Not switched. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | +| `craft-media-testkit` | Not switched. `private_dir()` is unchanged. | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..94889a2551 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,9 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! [`temp::TempDir`] is a new, private test folder that is removed with its contents when dropped, +//! also when the test panics. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,8 +29,12 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(not(target_arch = "wasm32"))] +pub mod temp; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; #[cfg(not(target_arch = "wasm32"))] pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits}; +#[cfg(not(target_arch = "wasm32"))] +pub use temp::TempDir; diff --git a/crates/testkit/src/temp.rs b/crates/testkit/src/temp.rs new file mode 100644 index 0000000000..1f3799b525 --- /dev/null +++ b/crates/testkit/src/temp.rs @@ -0,0 +1,442 @@ +//! Test folders that are removed with their contents when the test that made them ends. +//! +//! [`TempDir::new`] makes a new, empty folder in the system temporary directory with +//! [`tempfile::Builder`]: the name is `craft-testkit--` followed by random characters, and a +//! name that is already taken is skipped. A folder this module did not make is never emptied or +//! reused. On Unix the folder is made with mode 0o700, and before [`TempDir::new`] returns it checks +//! that the folder is a real folder, not a link, with no access for other users, and owned by the +//! user running the test. The checks apply to the created folder only, so a temporary directory +//! reached through a link (`/var` on macOS links to `/private/var`) works. +//! +//! [`TempDir::path`] returns the canonical path of the folder: `/private/var/...` on macOS, and a +//! `\\?\` path on Windows. Compare it with another canonical path, not with a join of +//! [`std::env::temp_dir`]. +//! +//! Dropping a [`TempDir`], also while a test panics, removes the folder with everything in it. A +//! link inside the folder is removed, not followed. Removal on drop is best effort: a file another +//! process holds open can stop it on Windows. [`TempDir::close`] removes the folder and returns the +//! error. A process that is killed or aborts leaves its folders behind, and later calls skip them. +//! +//! The checks read the folder once, after it is made. They do not protect against a process of the +//! same user that replaces the folder after the check. + +use std::io; +use std::path::{Path, PathBuf}; + +/// How many random characters follow the tag in a folder name. +const RANDOM_CHARS: usize = 10; + +/// The file [`TempDir::new`] makes, reads and removes in a new folder on Unix to learn which user +/// owns the files this process makes. +#[cfg(unix)] +const OWNER_PROBE: &str = ".craft-testkit-owner"; + +/// A new, empty folder in the system temporary directory, removed with its contents when dropped, +/// also when the test panics. +/// +/// Bind it to a variable that lives as long as the folder is needed. Used as a temporary, as in +/// `TempDir::new("x")?.file("a.png")`, it is dropped, and the folder removed, at the end of that +/// statement. +#[derive(Debug)] +pub struct TempDir { + /// The canonical path of the folder. + path: PathBuf, + /// Removes the folder when dropped. + dir: tempfile::TempDir, +} + +impl TempDir { + /// Makes a new folder named `craft-testkit--` in + /// [`std::env::temp_dir`]. Each call makes a folder of its own, also for calls with the same + /// tag at the same time. + /// + /// # Errors + /// + /// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL character. + /// The error from the file system when the folder cannot be made. An error when the folder that + /// was made is a link or another kind of entry, is open to other users, or is owned by another + /// user; such a folder is left in place. + pub fn new(tag: &str) -> io::Result { + Self::new_in(tag, &std::env::temp_dir(), RANDOM_CHARS) + } + + /// Makes the folder in `root`, with `random` random characters after the tag. + fn new_in(tag: &str, root: &Path, random: usize) -> io::Result { + one_name("tag", tag)?; + let prefix = format!("craft-testkit-{tag}-"); + let mut builder = tempfile::Builder::new(); + builder.prefix(&prefix).rand_bytes(random); + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + Self::guard(builder.tempdir_in(root)?) + } + + /// Checks the folder `dir` made and returns it with its canonical path. A folder that fails the + /// check is left in place, since it may not be the one `dir` made. + fn guard(mut dir: tempfile::TempDir) -> io::Result { + if let Err(e) = verify(dir.path()) { + dir.disable_cleanup(true); + return Err(e); + } + let path = std::fs::canonicalize(dir.path())?; + Ok(Self { path, dir }) + } + + /// The canonical, absolute path of the folder. + pub fn path(&self) -> &Path { + &self.path + } + + /// The path of `name` in the folder. The file is not made. + /// + /// # Errors + /// + /// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL + /// character, so the path always names an entry directly inside the folder. + pub fn file(&self, name: &str) -> io::Result { + one_name("file name", name)?; + Ok(self.path.join(name)) + } + + /// Removes the folder with everything in it. + /// + /// # Errors + /// + /// The error from the file system when the folder or something in it cannot be removed. + pub fn close(self) -> io::Result<()> { + self.dir.close() + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// Returns `InvalidInput` unless `name` is one path component on every platform. +fn one_name(what: &str, name: &str) -> io::Result<()> { + if name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '\0']) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{what} {name:?} is not a single file name"))); + } + Ok(()) +} + +/// What [`verify`] reads about a folder, without following a link. +#[derive(Debug, Clone, Copy)] +struct Entry { + is_dir: bool, + is_symlink: bool, + /// The permission bits, on Unix. + mode: Option, + /// The user id of the owner, on Unix. + owner: Option, +} + +/// Checks that `path` is a folder this process made, as [`check`] describes. +fn verify(path: &Path) -> io::Result<()> { + let meta = std::fs::symlink_metadata(path)?; + #[cfg(unix)] + let (mode, owner) = (Some(std::os::unix::fs::PermissionsExt::mode(&meta.permissions())), Some(std::os::unix::fs::MetadataExt::uid(&meta))); + #[cfg(not(unix))] + let (mode, owner) = (None, None); + let entry = Entry { is_dir: meta.is_dir(), is_symlink: meta.file_type().is_symlink(), mode, owner }; + check(path, entry, || my_uid(path)) +} + +/// Returns an error unless `entry` is a real folder, not a link, with no access for group or other +/// users, owned by the user `me` returns. `me` runs only after the other checks pass. +fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result>) -> io::Result<()> { + if entry.is_symlink || !entry.is_dir { + return Err(io::Error::other(format!("{}: a link or another kind of entry is in place of the new folder", path.display()))); + } + if entry.mode.is_some_and(|mode| mode & 0o077 != 0) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is open to other users", path.display()))); + } + if entry.owner != me()? { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is owned by another user", path.display()))); + } + Ok(()) +} + +/// The user id that owns a file this process makes, read from a probe file made new in `dir` and +/// removed again. +#[cfg(unix)] +fn my_uid(dir: &Path) -> io::Result> { + let probe = dir.join(OWNER_PROBE); + let meta = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?.metadata(); + std::fs::remove_file(&probe)?; + Ok(Some(std::os::unix::fs::MetadataExt::uid(&meta?))) +} + +/// Files have no Unix owner here. +#[cfg(not(unix))] +fn my_uid(_dir: &Path) -> io::Result> { + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entries(dir: &Path) -> usize { + std::fs::read_dir(dir).unwrap().count() + } + + #[test] + fn a_test_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("dropped").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.txt"), b"a").unwrap(); + drop(dir); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn a_test_dir_is_removed_when_its_test_panics() { + let mut path = None; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let dir = TempDir::new("panicked").unwrap(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + path = Some(dir.path().to_path_buf()); + panic!("the test fails"); + })); + assert_eq!(r.err().and_then(|p| p.downcast_ref::<&str>().copied()), Some("the test fails")); + let path = path.unwrap(); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn test_dirs_with_one_tag_are_separate_and_private() { + let (a, b) = (TempDir::new("shared-tag").unwrap(), TempDir::new("shared-tag").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("a.txt").unwrap(), b"a").unwrap(); + assert_eq!(entries(b.path()), 0, "one test's files are not in another's directory"); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(a.path()).unwrap().permissions()) & 0o777, 0o700); + drop(a); + assert!(b.path().is_dir(), "dropping one leaves the other"); + } + + #[test] + fn a_scratch_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("testkit-scratch").unwrap(); + let path = dir.path().to_path_buf(); + assert!(path.is_dir(), "{path:?} exists while the test holds it"); + assert_eq!(entries(&path), 0, "and starts empty"); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.pdf"), b"%PDF").unwrap(); + drop(dir); + assert!(!path.exists(), "{path:?} is gone, contents and all"); + } + + #[test] + fn scratch_dirs_with_the_same_name_are_separate_folders() { + let (a, b) = (TempDir::new("testkit-same").unwrap(), TempDir::new("testkit-same").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("x").unwrap(), b"a").unwrap(); + drop(b); + assert_eq!(std::fs::read(a.file("x").unwrap()).unwrap(), b"a", "dropping one leaves the other's files"); + } + + /// With one random character there are 62 names, and every one but `7` is taken: the new folder + /// is `7`, and the folders that were there keep their files. + #[test] + fn a_taken_name_is_skipped_and_its_folder_left_alone() { + let root = TempDir::new("taken-root").unwrap(); + let free = '7'; + let mut planted = Vec::new(); + for c in ('a'..='z').chain('A'..='Z').chain('0'..='9').filter(|&c| c != free) { + let folder = root.path().join(format!("craft-testkit-taken-{c}")); + // On a file system that ignores case, `A` is the folder `a` made. + match std::fs::create_dir(&folder) { + Ok(()) => std::fs::write(folder.join("theirs.pdf"), b"%PDF").unwrap(), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("{}: {e}", folder.display()), + } + planted.push(folder); + } + let dir = TempDir::new_in("taken", root.path(), 1).unwrap(); + assert_eq!(dir.path().file_name().and_then(|n| n.to_str()), Some("craft-testkit-taken-7")); + assert_eq!(entries(dir.path()), 0, "and starts empty"); + drop(dir); + for folder in &planted { + assert_eq!(std::fs::read(folder.join("theirs.pdf")).unwrap(), b"%PDF", "{folder:?} kept its file"); + } + } + + #[test] + fn existing_folder_is_never_reused() { + let root = TempDir::new("reuse-root").unwrap(); + let theirs = root.path().join("craft-testkit-reuse-"); + std::fs::create_dir(&theirs).unwrap(); + std::fs::write(theirs.join("theirs.txt"), b"theirs").unwrap(); + // With no random characters the one name tried is the folder above. + let err = TempDir::new_in("reuse", root.path(), 0).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(theirs.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&theirs), 1); + } + + #[test] + fn creation_failure_returns_error() { + let root = TempDir::new("failure-root").unwrap(); + let file = root.file("a-file").unwrap(); + std::fs::write(&file, b"not a folder").unwrap(); + assert!(TempDir::new_in("x", &file, RANDOM_CHARS).is_err(), "a file as the root"); + assert!(TempDir::new_in("x", &root.path().join("missing"), RANDOM_CHARS).is_err(), "a missing root"); + } + + #[test] + fn tag_rejects_empty_and_separators() { + for tag in ["", ".", "..", "a/b", "a\\b", "../x", "..\\x", "/x", "C:\\x", "C:x", "a\0b"] { + let err = TempDir::new(tag).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{tag:?}"); + } + } + + #[test] + fn file_rejects_absolute_parent_and_separators() { + let root = TempDir::new("file-root").unwrap(); + let dir = TempDir::new_in("file", root.path(), RANDOM_CHARS).unwrap(); + for name in ["", ".", "..", "a/b", "a\\b", "../outside.txt", "..\\outside.txt", "/x", "\\x", "C:\\x", "C:x", "a:stream", "a\0b"] { + let err = dir.file(name).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{name:?}"); + } + let a = dir.file("a.txt").unwrap(); + assert_eq!(a, dir.path().join("a.txt")); + assert!(!a.exists(), "file does not make the file"); + drop(dir); + assert_eq!(entries(root.path()), 0, "nothing was written next to the folder"); + } + + #[test] + fn path_is_canonical() { + let dir = TempDir::new("canonical").unwrap(); + assert!(dir.path().is_absolute()); + assert_eq!(dir.path(), std::fs::canonicalize(dir.path()).unwrap()); + assert_eq!(dir.path().parent().map(Path::to_path_buf), Some(std::fs::canonicalize(std::env::temp_dir()).unwrap())); + } + + #[cfg(windows)] + #[test] + fn windows_path_is_verbatim() { + let dir = TempDir::new("verbatim").unwrap(); + assert!(dir.path().to_string_lossy().starts_with(r"\\?\"), "{:?}", dir.path()); + } + + #[test] + fn same_tag_concurrent_creation_is_unique() { + let barrier = std::sync::Arc::new(std::sync::Barrier::new(16)); + let threads: Vec<_> = (0..16) + .map(|_| { + let barrier = std::sync::Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + TempDir::new("concurrent") + }) + }) + .collect(); + let dirs: Vec = threads.into_iter().map(|t| t.join().unwrap().unwrap()).collect(); + let paths: std::collections::BTreeSet<&Path> = dirs.iter().map(TempDir::path).collect(); + assert_eq!(paths.len(), 16); + assert!(dirs.iter().all(|d| entries(d.path()) == 0), "each starts empty"); + } + + #[test] + fn close_removes_the_folder() { + let dir = TempDir::new("close").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + dir.close().unwrap(); + assert!(!path.exists()); + } + + #[test] + fn close_reports_cleanup_failure() { + let dir = TempDir::new("close-failure").unwrap(); + std::fs::remove_dir(dir.path()).unwrap(); + assert!(dir.close().is_err(), "a folder that is already gone cannot be removed"); + } + + #[test] + fn wrong_owner_or_public_mode_is_rejected() { + let path = Path::new("folder"); + let private = Entry { is_dir: true, is_symlink: false, mode: Some(0o40700), owner: Some(1000) }; + assert!(check(path, private, || Ok(Some(1000))).is_ok()); + for mode in [0o40750, 0o40705, 0o40777] { + let err = check(path, Entry { mode: Some(mode), ..private }, || Ok(Some(1000))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); + } + let err = check(path, private, || Ok(Some(1001))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!(check(path, Entry { is_symlink: true, ..private }, || panic!("no probe through a link")).is_err()); + assert!(check(path, Entry { is_dir: false, ..private }, || panic!("no probe in a file")).is_err()); + let open = Entry { mode: Some(0o40777), ..private }; + assert!(check(path, open, || panic!("no probe in an open folder")).is_err()); + } + + #[cfg(unix)] + #[test] + fn new_dir_is_owner_private() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let dir = TempDir::new("private").unwrap(); + let meta = std::fs::symlink_metadata(dir.path()).unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o700); + let mine = dir.file("mine.txt").unwrap(); + std::fs::write(&mine, b"a").unwrap(); + assert_eq!(meta.uid(), std::fs::metadata(&mine).unwrap().uid()); + std::fs::remove_file(&mine).unwrap(); + assert_eq!(entries(dir.path()), 0, "the owner probe is removed"); + } + + #[cfg(unix)] + #[test] + fn created_folder_symlink_is_rejected() { + let root = TempDir::new("link-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + std::fs::write(real.join("theirs.txt"), b"theirs").unwrap(); + let made = tempfile::Builder::new().prefix("craft-testkit-link-").tempdir_in(root.path()).unwrap(); + let link = made.path().to_path_buf(); + std::fs::remove_dir(&link).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(TempDir::guard(made).is_err()); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is left in place"); + assert_eq!(std::fs::read(real.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&real), 1, "no probe was made through the link"); + } + + #[cfg(unix)] + #[test] + fn temp_root_reached_through_symlink_works() { + let root = TempDir::new("symlink-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = root.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let dir = TempDir::new_in("through-link", &link, RANDOM_CHARS).unwrap(); + assert_eq!(dir.path().parent(), Some(real.as_path()), "the path is canonical"); + assert!(dir.path().is_dir()); + let path = dir.path().to_path_buf(); + drop(dir); + assert!(!path.exists()); + assert!(real.is_dir() && link.is_symlink(), "the root and the link stay"); + } + + #[cfg(unix)] + #[test] + fn drop_does_not_follow_inner_symlink() { + let root = TempDir::new("inner-link-root").unwrap(); + let outside = root.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("keep.txt"), b"keep").unwrap(); + let dir = TempDir::new_in("inner-link", root.path(), RANDOM_CHARS).unwrap(); + std::os::unix::fs::symlink(&outside, dir.file("link").unwrap()).unwrap(); + let path = dir.path().to_path_buf(); + drop(dir); + assert!(!path.exists()); + assert_eq!(std::fs::read(outside.join("keep.txt")).unwrap(), b"keep"); + } +} From 67129ca6b5d7ba3ea1deb3f8d56ee74eab84b149 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:13:46 -0800 Subject: [PATCH 02/58] craft-testkit: list temp in the Origin and Migration tables and the crate list The temp module's sources and consumers are rows in the README's existing Origin and Migration tables, whose Guard column is now Module. The root README's craft-testkit entry names the temp module. --- README.md | 3 ++- crates/testkit/README.md | 28 +++++++++------------------- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index adbb6c120e..e88d227ec6 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit `color` and `write`; re-exports them for existing users. - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - out of range, and `std::time::Instant` in code the web build runs. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `temp` module makes a new, + private test folder that is removed with its contents when dropped. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/README.md b/crates/testkit/README.md index dd41509e7e..81fd01af41 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -24,24 +24,6 @@ std::fs::write(dir.file("out.png")?, &png)?; |---|---| | `temp` | VectorCraft, PdfCraft, CADCraft, `craft-media-testkit` | -### Origin - -| Module | Source | Path | SHA | -|---|---|---|---| -| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e17` | -| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e20711` | -| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4` | -| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e698902` | - -### Migration - -| Consumer | State | -|---|---| -| VectorCraft | Not switched. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | -| PdfCraft | Not switched. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | -| CADCraft | Not switched. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | -| `craft-media-testkit` | Not switched. `private_dir()` is unchanged. | - ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: @@ -114,10 +96,18 @@ fn no_std_instant_in_code_the_web_build_runs() { | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e1710` | +| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e2071199` | +| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4f8` | +| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e69890223` | ## Migration -| Consumer | Guard | Replaces | State | +| Consumer | Module | Replaces | State | |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| VectorCraft | `temp` | `temp_dir` and `TempDir` in `crates/testkit/src/lib.rs` | Not started. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | +| PdfCraft | `temp` | `ScratchDir` in `crates/testkit/src/scratch.rs` (#6124) | Not started. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | +| CADCraft | `temp` | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | Not started. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | +| `craft-media-testkit` | `temp` | `private_dir()` in `crates/media-testkit/src/lib.rs` | Not started. `private_dir()` is unchanged. | From 61141bcf72970cee9b682d3126b95604570610e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:43:23 -0800 Subject: [PATCH 03/58] craft-xtask: check pinned dependencies from cargo metadata Add a pins module, behind the pins feature, for the apps' pdf-deps xtask commands. Each app passes its own table: the version, source and allowed features of each pinned package, and packages it forbids, either when resolved at all or when reached from a root package over normal and build edges. Unlisted packages are allowed. run_target_features checks the features one target enables through cargo tree, and host_target reads the host from rustc -vV. Every command's standard output is read within a configurable limit (64 MiB for metadata and tree output by default); a larger output stops the command and returns an error. Standard error is drained, and its first 64 KiB are kept for the message. The DeckCraft, VectorCraft, DesignCraft and EffectCraft tests move in under their own names, with their tables as fixtures. --- crates/xtask/Cargo.toml | 4 +- crates/xtask/README.md | 59 +- crates/xtask/src/lib.rs | 4 + crates/xtask/src/pins.rs | 1217 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 1282 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/pins.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..680cc3bb4b 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report and a check of pinned dependencies" [lints] workspace = true @@ -16,6 +16,8 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# Pinned dependencies and forbidden packages, checked in `cargo metadata` (`cargo xtask pdf-deps`). +pins = ["dep:serde_json"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..72208948a8 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,9 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `pins` | `pins` | `run`, `check`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, and packages the app forbids, read from `cargo metadata` within size limits | -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 `pins` adds `serde_json`. ## Use @@ -91,6 +92,56 @@ 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. +## Pins + +`cargo xtask pdf-deps` checks that pinned dependencies resolve to the pinned version and source, with +the allowed features, and that packages the app forbids are not in the graph. The app enables the +`pins` feature, keeps its own table and passes it with a function that builds its `cargo` command: + +```rust +use craft_xtask::pins::{FeatureRule, Forbidden, Name, Pin, Policy, Scope}; + +const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + +Some("pdf-deps") => { + let source = craft_xtask::pins::git_source("https://github.com/storytold/craft-libs", REV); + let pins = [Pin { name: "craft-pdf", version: "0.1.0", source: &source, features: FeatureRule::Exactly(&["read"]) }]; + let forbidden = [Forbidden { name: Name::Exact("krilla"), scope: Scope::Active }]; + craft_xtask::pins::run(cargo, &Policy { pins: &pins, forbidden: &forbidden }, &Default::default()) + .map_err(|e| e.to_string()) +} +``` + +- `run` runs `cargo metadata --locked --format-version 1` and passes the JSON to `check`. +- Each `Pin` name has exactly one package, with the pinned `version` and `source`. `git_source(url, rev)` + gives the source Cargo writes for a git dependency pinned to a full commit hash, and `CRATES_IO` the + source for crates.io. +- `FeatureRule::Contains` requires the listed features and allows others. `FeatureRule::Exactly` + allows the listed features only. Both read the package's node in `resolve.nodes`. +- `Scope::Active` rejects a forbidden package that has a resolved node, development dependencies + included. `Scope::ProductionFrom(root)` rejects a forbidden package reached from `root` over normal + or build edges; one reached only through development edges is allowed. `Name::Family("hayro")` + matches `hayro` and every `hayro-*` name. +- Packages the policy does not name are allowed, and an empty policy accepts any metadata. +- JSON that does not parse, or lacks a field a rule needs (`resolve.nodes`, a package `id`, a node's + `features` or `deps`, an edge's `dep_kinds`), is an error. +- Cargo merges every target's features into one metadata result. `run_target_features` runs + `cargo tree --target ` from a root package and checks that each line for one package has + exactly the given features; `host_target` reads the host target from `rustc -vV`. +- `Limits` bounds each command's output. More standard output than the limit stops the command and + returns an error. Standard error is read to its end, and its first `stderr_bytes` are kept for the + error message: + + | Limit | Default | + |---|---| + | `metadata_bytes`: the `cargo metadata` JSON, also for JSON passed to `check` | 64 MiB | + | `tree_bytes`: one `cargo tree` output | 64 MiB | + | `version_bytes`: the `rustc -vV` output | 64 KiB | + | `stderr_bytes`: standard error kept for a message | 64 KiB | + +- `pins::Error` tells apart a command that could not start, could not be read, exited without + success or printed too much; output that is not valid; and a `Violation` of the policy. + ## Origin | Part | Source | @@ -99,6 +150,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `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 | +| `pins`: exact feature sets, the production walk over normal and build edges, the per-target `cargo tree` feature check, and their five tests | DeckCraft `xtask/src/pdf_deps.rs` at `aa3a1baa01` | +| `pins`: one package per name with an exact version and source, and its three tests | VectorCraft `xtask/src/pdf_deps.rs` at `34627134fa` | +| `pins`: required features that allow others, and its five tests | DesignCraft `xtask/src/pdf_deps.rs` at `18246dddd2` | +| `pins`: packages forbidden when resolved, and its five tests | EffectCraft `xtask/src/pdf_deps.rs` at `f31a6b0aef` | +| `pins`: the output size limits, an empty feature list in `cargo tree`, and the errors for missing fields, features that are not strings, edges without a kind and packages without a name | written here | ## Migration @@ -108,6 +164,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. | +| DeckCraft, DesignCraft, EffectCraft, VectorCraft | Planned: `xtask/src/pdf_deps.rs` moves to `pins`. Each app keeps its `pdf-deps` command and its table, and runs `cargo xtask pdf-deps` before and after the switch. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..9f08c4b7bd 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,8 @@ //! - `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. +//! - `pins` (feature `pins`): the version, source and features of pinned dependencies, and packages +//! an app forbids, read from `cargo metadata` (`cargo xtask pdf-deps`). //! //! ```no_run //! use std::path::Path; @@ -37,6 +39,8 @@ #[cfg(feature = "lock")] pub mod lock; +#[cfg(feature = "pins")] +pub mod pins; #[cfg(feature = "report")] pub mod report; pub mod runner; diff --git a/crates/xtask/src/pins.rs b/crates/xtask/src/pins.rs new file mode 100644 index 0000000000..0109ae9c20 --- /dev/null +++ b/crates/xtask/src/pins.rs @@ -0,0 +1,1217 @@ +//! Pinned dependencies: the version, source and features of named packages in `cargo metadata`, and +//! packages an app forbids. +//! +//! The app passes a [`Policy`]: one [`Pin`] for each package it pins and one [`Forbidden`] rule for +//! each package (or family of packages) it keeps out. [`run`] runs +//! `cargo metadata --locked --format-version 1` with the app's `cargo` command and passes the JSON to +//! [`check`]: +//! +//! - Each pinned name has exactly one package in `packages`, with the pinned `version` and `source`. +//! The source is compared as text: `git_source(url, rev)` gives the form Cargo writes for a package +//! taken from a git repository at a full commit hash, and [`CRATES_IO`] the form for crates.io. +//! - [`FeatureRule::Contains`] and [`FeatureRule::Exactly`] read the features enabled on the package +//! from its node in `resolve.nodes`. `Contains` allows features beyond the listed ones, and +//! `Exactly` does not. +//! - [`Scope::Active`] rejects a forbidden package that has a node in `resolve.nodes`, development +//! dependencies included. [`Scope::ProductionFrom`] rejects a forbidden package reached from a root +//! package over normal and build edges; a package reached only through development edges is +//! allowed. +//! - Packages the policy does not name are allowed. An empty policy accepts any metadata. +//! +//! A rule that needs `resolve.nodes`, a package `id` or a node's `features` or `deps` returns an +//! [`Error::Output`] when the field is missing, and so does JSON that does not parse. +//! +//! Cargo merges the features of every target into one metadata result. To check the features one +//! target enables, [`run_target_features`] reads `cargo tree` for that target and +//! [`check_target_features`] compares the features of each line for the package; [`host_target`] +//! reads the host target from `rustc -vV`. +//! +//! Every command's output is read within a [`Limits`] size: more standard output than the limit stops +//! the command and returns [`Error::TooLarge`]. Standard error is read to its end while the command +//! runs, and its first [`Limits::stderr_bytes`] bytes are kept for the error message. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::fmt; +use std::io::{self, Read}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::thread::JoinHandle; + +use serde_json::Value; + +/// The `source` Cargo writes for a package from crates.io. +pub const CRATES_IO: &str = "registry+https://github.com/rust-lang/crates.io-index"; + +/// The `source` Cargo writes for a package from the git repository at `url`, pinned with +/// `rev = ""` where `rev` is a full commit hash: `git+?rev=#`. +pub fn git_source(url: &str, rev: &str) -> String { + format!("git+{url}?rev={rev}#{rev}") +} + +/// One pinned package. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pin<'a> { + /// The package name. + pub name: &'a str, + /// The exact `version`. + pub version: &'a str, + /// The exact `source`, for example from [`git_source`] or [`CRATES_IO`]. + pub source: &'a str, + /// Which enabled features are allowed. + pub features: FeatureRule<'a>, +} + +/// How a [`Pin`] checks the package's enabled features. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FeatureRule<'a> { + /// The features are not checked. + Ignore, + /// Each listed feature is enabled; others may be enabled too. + Contains(&'a [&'a str]), + /// The listed features, and no others, are enabled. + Exactly(&'a [&'a str]), +} + +/// Which package names a [`Forbidden`] rule matches. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Name<'a> { + /// This name only. + Exact(&'a str), + /// This name and every name that starts with it followed by `-`: `Family("hayro")` matches + /// `hayro` and `hayro-syntax`. + Family(&'a str), +} + +impl Name<'_> { + /// Whether `name` matches. + pub fn matches(&self, name: &str) -> bool { + match *self { + Name::Exact(n) => name == n, + Name::Family(n) => name.strip_prefix(n).is_some_and(|rest| rest.is_empty() || rest.starts_with('-')), + } + } +} + +impl fmt::Display for Name<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Name::Exact(n) => f.write_str(n), + Name::Family(n) => write!(f, "{n} or {n}-*"), + } + } +} + +/// Where a [`Forbidden`] rule looks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope<'a> { + /// Every package with a node in `resolve.nodes`, development dependencies included. + Active, + /// The packages reached from the named root package over normal and build edges. + ProductionFrom(&'a str), +} + +/// A package, or family of packages, that must not be in the graph. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Forbidden<'a> { + /// The names the rule matches. + pub name: Name<'a>, + /// Where it looks. + pub scope: Scope<'a>, +} + +/// An app's pins and forbidden packages. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Policy<'a> { + /// The pinned packages. + pub pins: &'a [Pin<'a>], + /// The forbidden packages. + pub forbidden: &'a [Forbidden<'a>], +} + +/// Size limits for the commands' output and the JSON [`check`] reads. +#[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 output from one `cargo tree`. Default 64 MiB. + pub tree_bytes: usize, + /// Bytes of output from `rustc -vV`. Default 64 KiB. + pub version_bytes: usize, + /// Bytes of a command's standard error kept for its error message; the rest is read and dropped. + /// Default 64 KiB. + pub stderr_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { metadata_bytes: 64 << 20, tree_bytes: 64 << 20, version_bytes: 64 << 10, stderr_bytes: 64 << 10 } + } +} + +/// A package that breaks the [`Policy`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Violation { + /// A pinned name, or a root, has this many packages instead of one. + Count { + /// The package name. + name: String, + /// The number of packages with that name. + found: usize, + }, + /// A pinned package has another version. + Version { + /// The package name. + name: String, + /// The pinned version. + expected: String, + /// The version in the metadata. + found: String, + }, + /// A pinned package comes from another source. `found` is `None` for a path package. + Source { + /// The package name. + name: String, + /// The pinned source. + expected: String, + /// The source in the metadata. + found: Option, + }, + /// A package lacks required features or has features the rule does not allow. + Features { + /// The package name, or the `cargo tree` package text. + name: String, + /// Required features that are not enabled. + missing: Vec, + /// Enabled features that are not allowed. + extra: Vec, + }, + /// A forbidden package is in the graph. + Forbidden { + /// The package name. + name: String, + /// The rule's names. + rule: String, + /// The root it was reached from, for [`Scope::ProductionFrom`]. + root: Option, + }, +} + +impl fmt::Display for Violation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Violation::Count { name, found } => write!(f, "{name}: expected one resolved package, found {found}"), + Violation::Version { name, expected, found } => write!(f, "{name}: expected version {expected}, found {found}"), + Violation::Source { name, expected, found } => { + write!(f, "{name}: expected source {expected}, found {}", found.as_deref().unwrap_or("a path package")) + } + Violation::Features { name, missing, extra } => { + write!(f, "{name}: ")?; + if !missing.is_empty() { + write!(f, "missing features {}", missing.join(", "))?; + } + if !missing.is_empty() && !extra.is_empty() { + f.write_str("; ")?; + } + if !extra.is_empty() { + write!(f, "features not allowed {}", extra.join(", "))?; + } + Ok(()) + } + Violation::Forbidden { name, rule, root: None } => write!(f, "{name}: forbidden ({rule}) and resolved"), + Violation::Forbidden { name, rule, root: Some(root) } => { + write!(f, "{name}: forbidden ({rule}) and reached from {root} over normal or build dependencies") + } + } + } +} + +/// Why a check stopped. +#[derive(Debug)] +pub enum Error { + /// A command could not start. + Start { + /// The command, for example `cargo metadata`. + command: String, + /// The error starting it. + source: io::Error, + }, + /// A command's output could not be read, or the command could not be waited for. + Read { + /// The command. + command: String, + /// The error reading it. + source: io::Error, + }, + /// A command exited without success. + Exit { + /// The command. + command: String, + /// Its exit status. + status: ExitStatus, + /// The start of its standard error, at most [`Limits::stderr_bytes`]. + stderr: String, + }, + /// A command printed more than its limit, or the JSON given to [`check`] is larger than + /// [`Limits::metadata_bytes`]. + TooLarge { + /// The command. + command: String, + /// The limit in bytes. + limit: usize, + }, + /// A command's output is not what was expected: JSON that does not parse, or lacks a field a + /// rule needs. + Output { + /// The command. + command: String, + /// What is wrong. + why: String, + }, + /// The packages break the policy. + Violation(Violation), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Start { command, source } => write!(f, "{command}: could not start: {source}"), + Error::Read { command, source } => write!(f, "{command}: {source}"), + Error::Exit { command, status, stderr } if stderr.is_empty() => write!(f, "{command}: exited with {status}"), + Error::Exit { command, status, stderr } => write!(f, "{command}: exited with {status}: {stderr}"), + Error::TooLarge { command, limit } => write!(f, "{command}: more than the limit of {limit} bytes of output"), + Error::Output { command, why } => write!(f, "{command}: {why}"), + Error::Violation(v) => v.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Start { source, .. } | Error::Read { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for Error { + fn from(v: Violation) -> Self { + Error::Violation(v) + } +} + +const METADATA: &str = "cargo metadata"; + +/// Runs `cargo metadata --locked --format-version 1` and checks its JSON against `policy`. +/// +/// `cargo` builds the app's `cargo` command (program, folder and environment); the arguments are added +/// to it. +pub fn run(cargo: impl FnOnce() -> Command, policy: &Policy<'_>, limits: &Limits) -> Result<(), Error> { + let json = metadata(cargo, limits)?; + check(&json, policy, limits) +} + +/// The output of `cargo metadata --locked --format-version 1`, read within +/// [`Limits::metadata_bytes`]. +pub fn metadata(cargo: impl FnOnce() -> Command, limits: &Limits) -> Result, Error> { + let mut cmd = cargo(); + cmd.args(["metadata", "--locked", "--format-version", "1"]); + output(cmd, METADATA, limits.metadata_bytes, limits.stderr_bytes) +} + +/// Checks `cargo metadata --format-version 1` JSON against `policy`: the pins first, in order, then +/// the forbidden rules. The first broken rule is returned. +pub fn check(metadata_json: &[u8], policy: &Policy<'_>, limits: &Limits) -> Result<(), Error> { + if metadata_json.len() > limits.metadata_bytes { + return Err(Error::TooLarge { command: METADATA.into(), limit: limits.metadata_bytes }); + } + let meta: Value = serde_json::from_slice(metadata_json).map_err(|e| invalid(format!("not JSON: {e}")))?; + let graph = Graph::new(&meta)?; + for pin in policy.pins { + graph.check_pin(pin)?; + } + for rule in policy.forbidden { + match rule.scope { + Scope::Active => graph.check_active(&rule.name)?, + Scope::ProductionFrom(root) => graph.check_production(&rule.name, root)?, + } + } + Ok(()) +} + +/// The packages and resolved nodes of one metadata result. +struct Graph<'m> { + packages: &'m [Value], + by_id: HashMap<&'m str, &'m Value>, + /// `None` when the JSON has no `resolve.nodes` (`--no-deps`). + nodes: Option>, +} + +impl<'m> Graph<'m> { + fn new(meta: &'m Value) -> Result { + let packages = meta.get("packages").and_then(Value::as_array).ok_or_else(|| invalid("packages is missing"))?; + let mut by_id = HashMap::new(); + for p in packages { + str_field(p, "name", "a package")?; + if let Some(id) = p.get("id").and_then(Value::as_str) + && by_id.insert(id, p).is_some() + { + return Err(invalid(format!("package {id} is listed twice"))); + } + } + let nodes = match meta.pointer("/resolve/nodes").and_then(Value::as_array) { + None => None, + Some(list) => { + let mut nodes = HashMap::new(); + for n in list { + let id = str_field(n, "id", "a resolved node")?; + if nodes.insert(id, n).is_some() { + return Err(invalid(format!("package {id} has two resolved nodes"))); + } + } + Some(nodes) + } + }; + Ok(Graph { packages, by_id, nodes }) + } + + /// The packages named `name`. + fn named(&self, name: &str) -> Vec<&'m Value> { + self.packages.iter().filter(|p| p.get("name").and_then(Value::as_str) == Some(name)).collect() + } + + /// The one package named `name`. + fn one(&self, name: &str) -> Result<&'m Value, Error> { + match self.named(name).as_slice() { + [package] => Ok(package), + other => Err(Violation::Count { name: name.into(), found: other.len() }.into()), + } + } + + fn node(&self, id: &str) -> Result<&'m Value, Error> { + let nodes = self.nodes.as_ref().ok_or_else(|| invalid("resolve.nodes is missing; run cargo metadata without --no-deps"))?; + nodes.get(id).copied().ok_or_else(|| invalid(format!("package {id} has no resolved node"))) + } + + fn check_pin(&self, pin: &Pin<'_>) -> Result<(), Error> { + let package = self.one(pin.name)?; + let version = str_field(package, "version", pin.name)?; + if version != pin.version { + return Err(Violation::Version { name: pin.name.into(), expected: pin.version.into(), found: version.into() }.into()); + } + let source = package.get("source").and_then(Value::as_str); + if source != Some(pin.source) { + return Err(Violation::Source { name: pin.name.into(), expected: pin.source.into(), found: source.map(str::to_owned) }.into()); + } + let (wanted, exact) = match pin.features { + FeatureRule::Ignore => return Ok(()), + FeatureRule::Contains(f) => (f, false), + FeatureRule::Exactly(f) => (f, true), + }; + let node = self.node(str_field(package, "id", pin.name)?)?; + let list = + node.get("features").and_then(Value::as_array).ok_or_else(|| invalid(format!("{}: the resolved node has no features", pin.name)))?; + let mut enabled = BTreeSet::new(); + for f in list { + enabled.insert(f.as_str().ok_or_else(|| invalid(format!("{}: a feature is not a string", pin.name)))?); + } + compare_features(pin.name, wanted, &enabled, exact) + } + + fn check_active(&self, name: &Name<'_>) -> Result<(), Error> { + let nodes = self.nodes.as_ref().ok_or_else(|| invalid("resolve.nodes is missing; run cargo metadata without --no-deps"))?; + for package in self.packages { + let package_name = str_field(package, "name", "a package")?; + if !name.matches(package_name) { + continue; + } + let id = str_field(package, "id", package_name)?; + if nodes.contains_key(id) { + return Err(Violation::Forbidden { name: package_name.into(), rule: name.to_string(), root: None }.into()); + } + } + Ok(()) + } + + fn check_production(&self, name: &Name<'_>, root: &str) -> Result<(), Error> { + let root_id = str_field(self.one(root)?, "id", root)?; + let mut pending = vec![root_id]; + let mut seen = HashSet::new(); + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + let package = self.by_id.get(id).ok_or_else(|| invalid(format!("dependency {id} has no package entry")))?; + let package_name = str_field(package, "name", id)?; + if name.matches(package_name) { + return Err(Violation::Forbidden { name: package_name.into(), rule: name.to_string(), root: Some(root.into()) }.into()); + } + let deps = + self.node(id)?.get("deps").and_then(Value::as_array).ok_or_else(|| invalid(format!("package {id} has no dependency edges")))?; + for dep in deps { + if production_edge(dep, id)? { + pending.push(str_field(dep, "pkg", id)?); + } + } + } + Ok(()) + } +} + +/// Whether a `deps` entry is a normal or build dependency for at least one target. A kind that is not +/// `dev` counts as production, so an unknown kind is followed. +fn production_edge(dep: &Value, from: &str) -> Result { + let kinds = dep.get("dep_kinds").and_then(Value::as_array).ok_or_else(|| invalid(format!("a dependency of {from} has no dep_kinds")))?; + if kinds.is_empty() { + return Err(invalid(format!("a dependency of {from} has no dep_kinds"))); + } + let mut production = false; + for k in kinds { + match k.get("kind") { + Some(Value::Null) => production = true, + Some(Value::String(kind)) => production |= kind != "dev", + _ => return Err(invalid(format!("a dependency of {from} has a dep_kinds entry without a kind"))), + } + } + Ok(production) +} + +fn compare_features(name: &str, wanted: &[&str], enabled: &BTreeSet<&str>, exact: bool) -> Result<(), Error> { + let wanted: BTreeSet<&str> = wanted.iter().copied().collect(); + let missing: Vec = wanted.difference(enabled).map(|f| (*f).to_owned()).collect(); + let extra: Vec = if exact { enabled.difference(&wanted).map(|f| (*f).to_owned()).collect() } else { Vec::new() }; + if missing.is_empty() && extra.is_empty() { Ok(()) } else { Err(Violation::Features { name: name.into(), missing, extra }.into()) } +} + +fn str_field<'v>(v: &'v Value, key: &str, of: &str) -> Result<&'v str, Error> { + v.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("{of}: {key} is missing or not a string"))) +} + +fn invalid(why: impl Into) -> Error { + Error::Output { command: METADATA.into(), why: why.into() } +} + +/// The `cargo tree` call for [`run_target_features`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TargetFeatures<'a> { + /// The workspace package the tree starts from (`--package`). + pub root: &'a str, + /// Levels of dependencies below the root (`--depth`). + pub depth: u32, + /// The package whose features are checked. + pub package: &'a str, + /// The features it must have, and no others, on this target. + pub features: &'a [&'a str], +} + +/// Runs `cargo tree` for one target and checks the features of `spec.package` with +/// [`check_target_features`]. The command is +/// `cargo tree --locked --target --edges normal,build --package --depth +/// --no-dedupe --prefix none --format {p}|{f}`, and its output is read within +/// [`Limits::tree_bytes`]. +pub fn run_target_features(cargo: impl FnOnce() -> Command, target: &str, spec: &TargetFeatures<'_>, limits: &Limits) -> Result<(), Error> { + let command = format!("cargo tree --target {target}"); + let mut cmd = cargo(); + cmd.args(["tree", "--locked", "--target", target, "--edges", "normal,build", "--package", spec.root, "--depth"]) + .arg(spec.depth.to_string()) + .args(["--no-dedupe", "--prefix", "none", "--format", "{p}|{f}"]); + let out = output(cmd, &command, limits.tree_bytes, limits.stderr_bytes)?; + let tree = String::from_utf8(out).map_err(|_| Error::Output { command: command.clone(), why: "not UTF-8".into() })?; + check_target_features(&tree, spec.package, spec.features).map_err(|e| match e { + Error::Output { why, .. } => Error::Output { command, why }, + other => other, + }) +} + +/// Checks `cargo tree --format {p}|{f}` output: every line for `package` (text that starts with +/// ` v`) enables exactly `features`, and at least one line is for `package`. +pub fn check_target_features(tree: &str, package: &str, features: &[&str]) -> Result<(), Error> { + let prefix = format!("{package} v"); + let mut found = 0usize; + for line in tree.lines() { + let Some((text, list)) = line.rsplit_once('|') else { + continue; + }; + if !text.starts_with(&prefix) { + continue; + } + found += 1; + let enabled: BTreeSet<&str> = list.split(',').filter(|f| !f.is_empty()).collect(); + compare_features(text, features, &enabled, true)?; + } + if found == 0 { + return Err(Violation::Count { name: package.into(), found: 0 }.into()); + } + Ok(()) +} + +/// The host target from `rustc -vV` (its `host:` line), read within [`Limits::version_bytes`]. +/// `rustc` builds the app's `rustc` command; `-vV` is added to it. +pub fn host_target(rustc: impl FnOnce() -> Command, limits: &Limits) -> Result { + const COMMAND: &str = "rustc -vV"; + let mut cmd = rustc(); + cmd.arg("-vV"); + let out = output(cmd, COMMAND, limits.version_bytes, limits.stderr_bytes)?; + let text = String::from_utf8(out).map_err(|_| Error::Output { command: COMMAND.into(), why: "not UTF-8".into() })?; + text.lines() + .find_map(|line| line.strip_prefix("host: ")) + .map(|host| host.trim().to_owned()) + .filter(|host| !host.is_empty()) + .ok_or_else(|| Error::Output { command: COMMAND.into(), why: "no host line".into() }) +} + +/// Runs `cmd` and returns its standard output, or an error when it fails or prints more than +/// `limit` bytes. Standard error is read on another thread to its end, so a command that writes a +/// lot there does not stop on a full pipe; its first `stderr_limit` bytes are kept. +fn output(mut cmd: Command, command: &str, limit: usize, stderr_limit: usize) -> Result, Error> { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|source| Error::Start { command: command.into(), source })?; + let stderr = child.stderr.take().map(|pipe| std::thread::spawn(move || read_head(pipe, stderr_limit))); + let read = match child.stdout.take() { + Some(stdout) => read_bounded(stdout, limit), + None => Err(io::Error::other("no output pipe")), + }; + // On an error the stderr thread is left to end when the pipe closes: a process the child started + // may hold the pipe open after the child is stopped. + let stdout = match read { + Ok(Some(stdout)) => stdout, + Ok(None) => { + stop(&mut child); + return Err(Error::TooLarge { command: command.into(), limit }); + } + Err(source) => { + stop(&mut child); + return Err(Error::Read { command: command.into(), source }); + } + }; + let status = child.wait().map_err(|source| Error::Read { command: command.into(), source })?; + if status.success() { + return Ok(stdout); + } + let stderr = stderr.map(join_head).unwrap_or_default(); + Err(Error::Exit { command: command.into(), status, stderr: String::from_utf8_lossy(&stderr).trim().to_owned() }) +} + +/// Everything `reader` gives, or `None` when that is more than `limit` bytes. The read stops one byte +/// past the limit. +fn read_bounded(reader: impl Read, limit: usize) -> io::Result>> { + let mut buf = Vec::new(); + reader.take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1)).read_to_end(&mut buf)?; + Ok((buf.len() <= limit).then_some(buf)) +} + +/// Reads `reader` to its end and returns its first `limit` bytes. +fn read_head(mut reader: impl Read, limit: usize) -> Vec { + let mut head = Vec::new(); + let mut chunk = [0u8; 8192]; + loop { + match reader.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + let room = limit.saturating_sub(head.len()); + head.extend_from_slice(chunk.get(..n.min(room)).unwrap_or_default()); + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + head +} + +fn join_head(handle: JoinHandle>) -> Vec { + handle.join().unwrap_or_default() +} + +/// Ends a child whose output is no longer read. +fn stop(child: &mut Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::{CRATES_IO, Error, FeatureRule, Forbidden, Limits, Name, Pin, Policy, Scope, Violation, check, check_target_features, git_source}; + use serde_json::{Value, json}; + + fn bytes(v: &Value) -> Vec { + serde_json::to_vec(v).unwrap() + } + + fn validate(m: &Value, policy: &Policy<'_>) -> Result<(), Error> { + check(&bytes(m), policy, &Limits::default()) + } + + fn violation(r: Result<(), Error>) -> Violation { + match r { + Err(Error::Violation(v)) => v, + other => panic!("expected a violation, got {other:?}"), + } + } + + fn output_error(r: Result<(), Error>) -> String { + match r { + Err(Error::Output { why, .. }) => why, + other => panic!("expected an output error, got {other:?}"), + } + } + + #[test] + fn an_empty_policy_accepts_any_metadata() { + let policy = Policy::default(); + assert!(validate(&json!({"packages": []}), &policy).is_ok()); + assert!(validate(&json!({"packages": [{"name": "a"}], "resolve": null}), &policy).is_ok()); + } + + #[test] + fn rejects_json_that_does_not_parse_or_lacks_packages() { + let policy = Policy::default(); + assert!(output_error(check(b"{not json", &policy, &Limits::default())).starts_with("not JSON")); + assert!(output_error(validate(&json!({}), &policy)).contains("packages")); + assert!(output_error(validate(&json!({"packages": [{"id": "x"}]}), &policy)).contains("name")); + } + + #[test] + fn rejects_metadata_larger_than_the_limit_before_parsing_it() { + let json = bytes(&json!({"packages": []})); + let limits = Limits { metadata_bytes: json.len() - 1, ..Limits::default() }; + assert!(matches!(check(&json, &Policy::default(), &limits), Err(Error::TooLarge { limit, .. }) if limit == json.len() - 1)); + let limits = Limits { metadata_bytes: json.len(), ..Limits::default() }; + assert!(check(&json, &Policy::default(), &limits).is_ok()); + } + + #[test] + fn family_names_match_the_name_and_its_dash_suffixes_only() { + let family = Name::Family("hayro"); + assert!(family.matches("hayro")); + assert!(family.matches("hayro-syntax")); + assert!(!family.matches("hayrox")); + assert!(!family.matches("not-hayro")); + assert!(Name::Exact("hayro").matches("hayro")); + assert!(!Name::Exact("hayro").matches("hayro-syntax")); + } + + #[test] + fn git_sources_name_the_revision_twice() { + assert_eq!(git_source("https://github.com/o/r", "abc"), "git+https://github.com/o/r?rev=abc#abc"); + } + + #[test] + fn target_features_without_any_enabled_match_an_empty_list() { + assert!(check_target_features("krilla v0.8.2|\n", "krilla", &[]).is_ok()); + assert!(check_target_features("krilla v0.8.2|\n", "krilla", &["rayon"]).is_err()); + // Another package whose name starts the same is not checked. + assert!(check_target_features("krilla v0.8.2|a\nkrilla-svg v0.1.0|b\n", "krilla", &["a"]).is_ok()); + } + + #[test] + fn a_production_root_must_resolve_once() { + let m = json!({"packages": [], "resolve": {"nodes": []}}); + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::ProductionFrom("app") }] }; + assert_eq!(violation(validate(&m, &policy)), Violation::Count { name: "app".into(), found: 0 }); + } + + #[test] + fn an_active_rule_needs_resolved_nodes_even_when_no_package_matches() { + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::Active }] }; + assert!(output_error(validate(&json!({"packages": [{"id": "a", "name": "a"}]}), &policy)).contains("resolve.nodes")); + assert!(validate(&json!({"packages": [{"id": "a", "name": "a"}], "resolve": {"nodes": []}}), &policy).is_ok()); + } + + #[test] + fn rejects_edges_without_a_kind() { + let m = json!({ + "packages": [{"id": "app", "name": "app"}, {"id": "dep", "name": "dep"}], + "resolve": {"nodes": [{"id": "app", "deps": [{"pkg": "dep", "dep_kinds": [{}]}]}, {"id": "dep", "deps": []}]} + }); + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::ProductionFrom("app") }] }; + assert!(output_error(validate(&m, &policy)).contains("kind")); + } + + #[test] + fn rejects_features_that_are_not_strings() { + let m = json!({ + "packages": [{"id": "p", "name": "p", "version": "1.0.0", "source": CRATES_IO}], + "resolve": {"nodes": [{"id": "p", "features": ["std", 1]}]} + }); + let pins = [Pin { name: "p", version: "1.0.0", source: CRATES_IO, features: FeatureRule::Contains(&["std"]) }]; + assert!(output_error(validate(&m, &Policy { pins: &pins, forbidden: &[] })).contains("not a string")); + } + + /// Fixtures and tests from DeckCraft's `xtask/src/pdf_deps.rs`. + mod deckcraft { + use super::super::{CRATES_IO, FeatureRule, Forbidden, Name, Pin, Policy, Scope, Violation, check_target_features, git_source}; + use super::{output_error, validate, violation}; + use serde_json::{Value, json}; + + const SHARED_REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + const FORBIDDEN: &[Forbidden<'static>] = &[Forbidden { name: Name::Family("hayro"), scope: Scope::ProductionFrom("deckcraft-pdf") }]; + + fn source() -> String { + git_source("https://github.com/storytold/craft-libs", SHARED_REV) + } + + fn pins(source: &str) -> [Pin<'_>; 3] { + [ + Pin { name: "craft-pdf", version: "0.1.0", source, features: FeatureRule::Exactly(&["write", "write-simple-text"]) }, + Pin { name: "krilla", version: "0.8.2", source, features: FeatureRule::Exactly(&["raster-images", "rayon", "simple-text"]) }, + Pin { name: "hayro-syntax", version: "0.7.2", source: CRATES_IO, features: FeatureRule::Exactly(&["std"]) }, + ] + } + + fn check(m: &Value) -> Result<(), super::Error> { + let source = source(); + let pins = pins(&source); + validate(m, &Policy { pins: &pins, forbidden: FORBIDDEN }) + } + + fn metadata() -> Value { + let source = source(); + json!({ + "packages": [ + {"id":"app", "name":"deckcraft-pdf"}, + {"id":"writer", "name":"craft-pdf", "version":"0.1.0", "source":source}, + {"id":"backend", "name":"krilla", "version":"0.8.2", "source":source}, + {"id":"parser", "name":"hayro-syntax", "version":"0.7.2", "source":CRATES_IO} + ], + "resolve":{"nodes":[ + {"id":"app", "deps":[{"pkg":"writer", "dep_kinds":[{"kind":null}]}, {"pkg":"parser", "dep_kinds":[{"kind":"dev"}]}]}, + {"id":"writer", "features":["write","write-simple-text"], "deps":[{"pkg":"backend", "dep_kinds":[{"kind":null}]}]}, + {"id":"backend", "features":["raster-images","rayon","simple-text"], "deps":[]}, + {"id":"parser", "features":["std"], "deps":[]} + ]} + }) + } + + #[test] + fn parallel_compression_is_required_only_on_native_targets() { + let serial = "krilla v0.8.2 (pinned)|raster-images,simple-text\n"; + let parallel = "krilla v0.8.2 (pinned)|raster-images,rayon,simple-text\n"; + let native: &[&str] = &["raster-images", "rayon", "simple-text"]; + let wasm: &[&str] = &["raster-images", "simple-text"]; + assert!(check_target_features(serial, "krilla", wasm).is_ok()); + assert!(check_target_features(parallel, "krilla", native).is_ok()); + assert!(check_target_features(serial, "krilla", native).is_err()); + assert!(check_target_features(parallel, "krilla", wasm).is_err()); + assert!(check_target_features("", "krilla", wasm).is_err()); + } + + #[test] + fn rejects_unpinned_or_duplicate_writer_sources() { + assert!(check(&metadata()).is_ok()); + for source in [Value::Null, json!(CRATES_IO), json!("git+https://github.com/storytold/craft-libs#other")] { + let mut m = metadata(); + m["packages"][1]["source"] = source; + assert!(matches!(violation(check(&m)), Violation::Source { .. })); + } + let mut m = metadata(); + let mut duplicate = m["packages"][2].clone(); + duplicate["id"] = json!("backend-2"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert_eq!(violation(check(&m)), Violation::Count { name: "krilla".into(), found: 2 }); + } + + #[test] + fn rejects_import_features_and_missing_text_shaping() { + for (node, features) in [ + (1, json!([])), + (1, json!(["write"])), + (1, json!(["write", "write-simple-text", "write-pdf"])), + (2, json!(["raster-images", "rayon", "simple-text", "pdf"])), + (2, json!(["raster-images"])), + (3, json!(["std", "images"])), + ] { + let mut m = metadata(); + m["resolve"]["nodes"][node]["features"] = features; + assert!(matches!(violation(check(&m)), Violation::Features { .. })); + } + } + + #[test] + fn rejects_dev_parser_promoted_to_production_directly_or_transitively() { + for kind in [Value::Null, json!("build")] { + let mut m = metadata(); + m["resolve"]["nodes"][0]["deps"][1]["dep_kinds"][0]["kind"] = kind; + assert!(matches!(violation(check(&m)), Violation::Forbidden { ref name, .. } if name == "hayro-syntax")); + } + let mut m = metadata(); + m["resolve"]["nodes"][2]["deps"] = json!([{"pkg":"parser", "dep_kinds":[{"kind":null}]}]); + assert!(matches!(violation(check(&m)), Violation::Forbidden { ref name, .. } if name == "hayro-syntax")); + // A dependency that is dev on one target and normal on another is production. + let mut m = metadata(); + m["resolve"]["nodes"][0]["deps"][1]["dep_kinds"] = json!([{"kind":"dev"}, {"kind":null, "target":"cfg(unix)"}]); + assert!(matches!(violation(check(&m)), Violation::Forbidden { .. })); + } + + #[test] + fn rejects_incomplete_dependency_metadata() { + let mut m = metadata(); + m["resolve"]["nodes"][2]["deps"] = json!([{"pkg":"missing", "dep_kinds":[{"kind":null}]}]); + assert!(output_error(check(&m)).contains("missing")); + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(output_error(check(&m)).contains("resolve.nodes")); + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().retain(|p| p["name"] != "hayro-syntax"); + assert_eq!(violation(check(&m)), Violation::Count { name: "hayro-syntax".into(), found: 0 }); + let mut m = metadata(); + m["resolve"]["nodes"][1]["deps"][0]["dep_kinds"] = json!([]); + assert!(output_error(check(&m)).contains("dep_kinds")); + } + } + + /// Fixtures and tests from VectorCraft's `xtask/src/pdf_deps.rs`. + mod vectorcraft { + use super::super::{FeatureRule, Pin, Policy, git_source}; + use super::validate; + use serde_json::{Value, json}; + + const REV: &str = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"; + const PACKAGES: &[(&str, &str)] = &[ + ("craft-pdf", "0.1.0"), + ("krilla", "0.8.2"), + ("hayro-syntax", "0.7.2"), + ("hayro-interpret", "0.7.0"), + ("hayro-jbig2", "0.3.0"), + ("hayro-cmap", "0.1.0"), + ("hayro-postscript", "0.1.0"), + ]; + + fn source(rev: &str) -> String { + git_source("https://github.com/storytold/craft-libs", rev) + } + + fn check(m: &Value) -> Result<(), super::Error> { + let source = source(REV); + let pins: Vec> = + PACKAGES.iter().map(|&(name, version)| Pin { name, version, source: &source, features: FeatureRule::Ignore }).collect(); + validate(m, &Policy { pins: &pins, forbidden: &[] }) + } + + fn metadata() -> Value { + let packages: Vec<_> = PACKAGES.iter().map(|(name, version)| json!({"name":name, "version":version, "source":source(REV)})).collect(); + json!({"packages": packages}) + } + + #[test] + fn accepts_pinned_pdf_packages_without_changing_printer_transport() { + let mut m = metadata(); + m["packages"] + .as_array_mut() + .unwrap() + .push(json!({"name":"craft-print", "version":"0.1.0", "source":source("d991bf6792f8ade99c51358bf3c1d902c8cd96b5")})); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_missing_or_duplicate_pdf_packages() { + for index in 0..PACKAGES.len() { + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().remove(index); + assert!(check(&m).is_err()); + let mut m = metadata(); + let duplicate = m["packages"][index].clone(); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(check(&m).is_err()); + } + } + + #[test] + fn rejects_registry_local_version_and_revision_drift() { + for index in 0..PACKAGES.len() { + for (field, value) in [ + ("source", Value::Null), + ("source", json!("registry+https://github.com/rust-lang/crates.io-index")), + ("source", json!("git+https://github.com/storytold/craft-libs?branch=main#other")), + ("source", json!(source("92d392cff132eaf53e13afff77f38b5c11b73aa0"))), + ("version", json!("0.99.0")), + ] { + let mut m = metadata(); + m["packages"][index][field] = value; + assert!(check(&m).is_err()); + } + } + } + } + + /// Fixtures and tests from DesignCraft's `xtask/src/pdf_deps.rs`. + mod designcraft { + use super::super::{FeatureRule, Pin, Policy, Violation, git_source}; + use super::{validate, violation}; + use serde_json::{Value, json}; + + const REV: &str = "a0916808f7d78bed8c7b90cdf937176015454a7f"; + const PACKAGES: &[(&str, &str)] = &[ + ("craft-pdf", "0.1.0"), + ("krilla", "0.8.2"), + ("hayro", "0.7.1"), + ("hayro-interpret", "0.7.0"), + ("hayro-syntax", "0.7.2"), + ("hayro-jbig2", "0.3.0"), + ("hayro-cmap", "0.1.0"), + ("hayro-postscript", "0.1.0"), + ]; + const FACADE_FEATURES: &[&str] = &["read", "interpret", "raster", "write", "write-pdf"]; + + fn check(m: &Value) -> Result<(), super::Error> { + let source = git_source("https://github.com/storytold/craft-libs", REV); + let pins: Vec> = PACKAGES + .iter() + .map(|&(name, version)| { + let features = if name == "craft-pdf" { FeatureRule::Contains(FACADE_FEATURES) } else { FeatureRule::Ignore }; + Pin { name, version, source: &source, features } + }) + .collect(); + validate(m, &Policy { pins: &pins, forbidden: &[] }) + } + + fn metadata() -> Value { + json!({"packages": PACKAGES.iter().map(|(name, version)| json!({"id":name,"name":name,"version":version, + "source":git_source("https://github.com/storytold/craft-libs", REV)})).collect::>(), "resolve": {"nodes": [{"id": "craft-pdf", "features": ["read", "interpret", "raster", "write", "write-pdf"]}]}}) + } + + #[test] + fn accepts_one_pinned_facade_and_reader() { + assert!(check(&metadata()).is_ok()); + // Features beyond the required ones are allowed. + let mut m = metadata(); + m["resolve"]["nodes"][0]["features"].as_array_mut().unwrap().push(json!("write-simple-text")); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_unpatched_and_local_reader_sources() { + for source in [Value::Null, json!("registry+https://github.com/rust-lang/crates.io-index")] { + let mut m = metadata(); + m["packages"][1]["source"] = source; + assert!(matches!(violation(check(&m)), Violation::Source { .. })); + } + } + + #[test] + fn rejects_missing_duplicate_and_wrong_version_packages() { + for index in 0..PACKAGES.len() { + let mut m = metadata(); + m["packages"][index]["version"] = json!("99.0.0"); + assert!(matches!(violation(check(&m)), Violation::Version { .. })); + let mut m = metadata(); + let mut duplicate = m["packages"][index].clone(); + duplicate["id"] = json!("duplicate"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(matches!(violation(check(&m)), Violation::Count { found: 2, .. })); + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().remove(index); + assert!(matches!(violation(check(&m)), Violation::Count { found: 0, .. })); + } + } + + #[test] + fn rejects_missing_reader_or_writer_features() { + for index in 0..5 { + let mut m = metadata(); + m["resolve"]["nodes"][0]["features"].as_array_mut().unwrap().remove(index); + assert!(matches!(violation(check(&m)), Violation::Features { .. })); + } + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_facade_revision_drift_and_malformed_metadata() { + let mut m = metadata(); + m["packages"][0]["source"] = json!("git+https://github.com/storytold/craft-libs?branch=main#other"); + assert!(check(&m).is_err()); + assert!(check(&json!({})).is_err()); + } + } + + /// Fixtures and tests from EffectCraft's `xtask/src/pdf_deps.rs`. + mod effectcraft { + use super::super::{FeatureRule, Forbidden, Name, Pin, Policy, Scope, Violation, git_source}; + use super::{validate, violation}; + use serde_json::{Value, json}; + + const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; + const FORBIDDEN: &[Forbidden<'static>] = &[ + Forbidden { name: Name::Exact("hayro"), scope: Scope::Active }, + Forbidden { name: Name::Exact("hayro-interpret"), scope: Scope::Active }, + Forbidden { name: Name::Exact("hayro-cmap"), scope: Scope::Active }, + Forbidden { name: Name::Exact("krilla"), scope: Scope::Active }, + ]; + + fn check(m: &Value) -> Result<(), super::Error> { + let source = git_source("https://github.com/storytold/craft-libs", REV); + let pins: Vec> = PACKAGES + .iter() + .map(|&(name, version)| { + let features = match name { + "craft-pdf" => FeatureRule::Exactly(&["read"]), + "hayro-syntax" => FeatureRule::Exactly(&["std"]), + _ => FeatureRule::Ignore, + }; + Pin { name, version, source: &source, features } + }) + .collect(); + validate(m, &Policy { pins: &pins, forbidden: FORBIDDEN }) + } + + fn metadata() -> Value { + let packages: Vec<_> = PACKAGES + .iter() + .map(|(name, version)| json!({"id": name, "name": name, "version": version, "source": git_source("https://github.com/storytold/craft-libs", REV)})) + .collect(); + json!({"packages": packages, "resolve": {"nodes": [ + {"id": "hayro-syntax", "features": ["std"]}, {"id": "craft-pdf", "features": ["read"]} + ]}}) + } + + #[test] + fn accepts_the_pinned_parser_only_graph() { + assert!(check(&metadata()).is_ok()); + // A forbidden package without a resolved node is not active. + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().push(json!({"id": "krilla", "name": "krilla"})); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_unpinned_duplicate_and_missing_parsers() { + let mut m = metadata(); + m["packages"][0]["source"] = json!("registry"); + assert!(check(&m).is_err()); + let mut m = metadata(); + let mut duplicate = m["packages"][0].clone(); + duplicate["id"] = json!("craft-pdf-2"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(check(&m).is_err()); + m["packages"].as_array_mut().unwrap().retain(|p| p["name"] != "hayro-syntax"); + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_shared_reader_source_drift() { + let mut m = metadata(); + m["packages"][0]["source"] = Value::Null; + assert!(matches!(violation(check(&m)), Violation::Source { found: None, .. })); + } + + #[test] + fn rejects_extra_features_and_missing_active_nodes() { + for (index, feature) in [(0, "images"), (1, "write"), (1, "raster")] { + let mut m = metadata(); + m["resolve"]["nodes"][index]["features"].as_array_mut().unwrap().push(json!(feature)); + assert!(matches!(violation(check(&m)), Violation::Features { ref extra, .. } if extra == &[feature.to_owned()])); + } + let mut m = metadata(); + m["resolve"]["nodes"].as_array_mut().unwrap().pop(); + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_backend_asset_features_and_missing_resolution() { + for name in ["hayro", "hayro-interpret", "hayro-cmap", "krilla"] { + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().push(json!({"id": name, "name": name})); + m["resolve"]["nodes"].as_array_mut().unwrap().push(json!({"id": name})); + assert!(matches!(violation(check(&m)), Violation::Forbidden { name: ref found, root: None, .. } if found == name)); + } + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(check(&m).is_err()); + } + } + + /// The commands run as children: the test binary itself, running [`fake_child`]. + mod process { + use super::super::{Error, Limits, TargetFeatures, Violation, host_target, metadata, run_target_features}; + use std::io::Write; + use std::process::Command; + + const MODE: &str = "CRAFT_XTASK_PINS_FAKE"; + + fn fake(mode: &str) -> Command { + let mut cmd = Command::new(std::env::current_exe().unwrap()); + cmd.args(["--ignored", "--exact", "--nocapture", "--test-threads=1", "pins::tests::process::fake_child", "--"]).env(MODE, mode); + cmd + } + + /// Stands in for `cargo` or `rustc` when [`MODE`] is set; does nothing otherwise. The harness + /// reads the arguments the library adds after `--` as more test filters, and with `--exact` + /// none of them selects another test. + #[test] + #[ignore = "a child process for the other process tests"] + fn fake_child() { + let Ok(mode) = std::env::var(MODE) else { + return; + }; + let chunk = [b'x'; 8192]; + match mode.as_str() { + "endless" => { + let mut out = std::io::stdout().lock(); + while out.write_all(&chunk).is_ok() {} + } + "fail" => { + let mut err = std::io::stderr().lock(); + for _ in 0..256 { + let _ = err.write_all(&chunk); + } + std::process::exit(3); + } + "host" => println!("rustc 1.0.0\nhost: fake-target\nrelease: 1.0.0"), + "tree" => println!("app-pdf v0.1.0|\ncraft-pdf v0.1.0|write\nkrilla v0.8.2|raster-images,simple-text"), + _ => {} + } + } + + #[test] + fn target_features_are_read_from_the_tree_command() { + let spec = TargetFeatures { root: "app-pdf", depth: 2, package: "krilla", features: &["raster-images", "simple-text"] }; + assert!(run_target_features(|| fake("tree"), "wasm32-unknown-unknown", &spec, &Limits::default()).is_ok()); + let spec = TargetFeatures { features: &["raster-images", "rayon", "simple-text"], ..spec }; + match run_target_features(|| fake("tree"), "x86_64-unknown-linux-gnu", &spec, &Limits::default()) { + Err(Error::Violation(Violation::Features { missing, extra, .. })) => { + assert_eq!(missing, ["rayon"]); + assert!(extra.is_empty()); + } + other => panic!("expected a feature violation, got {other:?}"), + } + } + + #[test] + fn output_past_the_limit_stops_the_command() { + let limits = Limits { metadata_bytes: 64 << 10, ..Limits::default() }; + match metadata(|| fake("endless"), &limits) { + Err(Error::TooLarge { command, limit }) => { + assert_eq!(command, "cargo metadata"); + assert_eq!(limit, 64 << 10); + } + other => panic!("expected TooLarge, got {other:?}"), + } + } + + #[test] + fn a_failing_command_keeps_the_start_of_a_long_stderr() { + let limits = Limits { stderr_bytes: 1000, ..Limits::default() }; + match metadata(|| fake("fail"), &limits) { + Err(Error::Exit { status, stderr, .. }) => { + assert_eq!(status.code(), Some(3)); + assert_eq!(stderr, "x".repeat(1000)); + } + other => panic!("expected Exit, got {other:?}"), + } + } + + #[test] + fn a_command_that_cannot_start_is_an_error() { + let r = metadata(|| Command::new("craft-xtask-pins-no-such-program"), &Limits::default()); + assert!(matches!(r, Err(Error::Start { .. }))); + } + + #[test] + fn the_host_target_is_read_from_its_line() { + assert_eq!(host_target(|| fake("host"), &Limits::default()).unwrap(), "fake-target"); + let limits = Limits { version_bytes: 4, ..Limits::default() }; + assert!(matches!(host_target(|| fake("host"), &limits), Err(Error::TooLarge { .. }))); + } + } +} From c56151df8428e00c5eec394ab6e07f3e0dc1af44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:12:18 -0800 Subject: [PATCH 04/58] ci: run Shared media, audio and video for changes under crates/testkit The media, audio and video workflows list crates/media-testkit/** in their path filters but not crates/testkit/**, so a change to craft-testkit alone starts none of them. Add crates/testkit/** next to crates/media-testkit/** in the push and pull_request filters of media.yml, audio.yml and video.yml. --- .github/workflows/audio.yml | 4 ++-- .github/workflows/media.yml | 4 ++-- .github/workflows/video.yml | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index d6a7ff5e25..763ae282ec 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -3,9 +3,9 @@ name: Shared audio on: push: branches: [main] - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 4814e35ca8..08188c6e5d 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -3,9 +3,9 @@ name: Shared media on: push: branches: [main] - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index fa667bdfca..582264a37e 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -3,9 +3,9 @@ name: Shared video on: push: branches: [main] - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] workflow_dispatch: permissions: From 7f2e3c09edd04aba6859eb6fcd7044f4bd73c02e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:27:21 -0800 Subject: [PATCH 05/58] ci: put a space after the comma before the next path in the media, audio and video filters --- .github/workflows/audio.yml | 4 ++-- .github/workflows/media.yml | 4 ++-- .github/workflows/video.yml | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 763ae282ec..919b57a3e1 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -3,9 +3,9 @@ name: Shared audio on: push: branches: [main] - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 08188c6e5d..fb3681deb2 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -3,9 +3,9 @@ name: Shared media on: push: branches: [main] - paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: - paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 582264a37e..383f69f98a 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -3,9 +3,9 @@ name: Shared video on: push: branches: [main] - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] workflow_dispatch: permissions: From e1e4ab8a006204e219e6aaeb8cbacb0e85e7935e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:07:40 -0800 Subject: [PATCH 06/58] Share: a late account-link answer asks for nothing, and the docs state the stale-answer rule `receive` asked the service for destinations on every `Linked` answer, including one that arrived after its sheet closed, moved to another document or the account signed out. It now acts only when the open sheet is waiting for that request, and clears it. The sheet keeps every link in flight, since a second destination can be clicked before the first one answers; a refusal of either one is still reported. The share and cloud module docs now say that every answer carries the sequence number or account generation it was asked under, and that one whose request no longer stands is dropped. In the share docs, a withdrawal is named as the one answer applied by share id. A stray "this file." line is removed from the share module docs. --- crates/ui/src/cloud/mod.rs | 8 ++++++- crates/ui/src/share/mod.rs | 35 ++++++++++++++++++++--------- crates/ui/src/share/tests.rs | 43 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/crates/ui/src/cloud/mod.rs b/crates/ui/src/cloud/mod.rs index 2b1cd3d09f..324ca7c6fb 100644 --- a/crates/ui/src/cloud/mod.rs +++ b/crates/ui/src/cloud/mod.rs @@ -6,7 +6,7 @@ //! that says whose storage this is, a Save As page that picks a folder and //! names a file, and a save that refuses to overwrite somebody else's work. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A //! host writes that half. This module never learns what it reaches. That keeps @@ -21,6 +21,12 @@ //! list under a heading reads to a user as a broken window. A feature the //! provider does not have is therefore absent, heading and all. //! +//! Nothing here acts on a stale answer. Every answer carries the account +//! generation its job was issued in, and [`pump`] drops one whose generation +//! is no longer current, so a reply that arrives after a sign-out or a new +//! sign-in is not applied to the session that replaced its own. A new kind of +//! answer follows the same rule. +//! //! The application supplies [`CloudApp`]. That is what it alone can answer. //! What its documents are, how bytes become one and back, and the words it //! shows them in. diff --git a/crates/ui/src/share/mod.rs b/crates/ui/src/share/mod.rs index 05d32e4de6..91c9673e38 100644 --- a/crates/ui/src/share/mod.rs +++ b/crates/ui/src/share/mod.rs @@ -5,12 +5,11 @@ //! look or change, add a note, decide whether an email goes out, and see who //! already has access so one of them can be taken away again. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`ShareBackend`], and //! nothing here reaches the network. A host writes the backend, and this //! module never learns what it talks to. -//! this file. //! //! Nothing here blocks. Answers arrive on a channel and are read once per //! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it @@ -21,6 +20,17 @@ //! false until the service says sharing exists, and an app hides its Share //! control rather than offering a button that fails. Contacts and mail are //! reported separately and are hidden the same way. +//! +//! Nothing here acts on a stale answer. Every request carries a sequence +//! number, and its answer comes back with it. An answer is applied only while +//! the request it answers still stands: an answer to a query the +//! user has typed past, a link granted or an account linked for a sheet that +//! has since closed or moved to another document, and a capabilities answer +//! to a question asked before [`ShareDialog::refresh`], +//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A +//! withdrawal is the one answer applied by share id instead: the share is gone +//! on the service, so it leaves every list that still shows it. A new kind of +//! answer follows the sequence rule. use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; @@ -226,7 +236,9 @@ struct Sheet { /// Where it could be saved. `None` until the answer arrives. destinations: Option>, destinations_seq: Option, - link_seq: Option, + /// Account links in flight, by request. More than one can be: every + /// unlinked destination stays clickable while another one links. + linking: Vec, /// Which one is selected, by id. destination: Option, /// The name typed while the document still has nowhere to live. @@ -248,7 +260,7 @@ impl Sheet { Sheet { destinations: None, destinations_seq: None, - link_seq: None, + linking: Vec::new(), destination: None, save_as: title.clone(), saving: None, @@ -740,10 +752,13 @@ impl ShareDialog { } } Answer::Linked => { + // Only for the sheet that asked: after the sheet closed, moved + // to another document or the account signed out, a late + // answer asks the service for nothing. + let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return }; // An account arrived, so the list is stale. - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } + sheet.linking.retain(|s| *s != seq); + sheet.destinations = None; let seq = self.issue(Request::Destinations); if let Some(sheet) = &mut self.open { sheet.destinations_seq = Some(seq); @@ -799,8 +814,8 @@ impl ShareDialog { sheet.destinations_seq = None; sheet.destinations = Some(Vec::new()); sheet.save_error = Some(reason); - } else if sheet.link_seq == Some(seq) { - sheet.link_seq = None; + } else if sheet.linking.contains(&seq) { + sheet.linking.retain(|s| *s != seq); sheet.save_error = Some(reason); } } @@ -842,7 +857,7 @@ impl ShareDialog { // application's business and not this crate's. let seq = self.issue(Request::Link { destination }); if let Some(sheet) = &mut self.open { - sheet.link_seq = Some(seq); + sheet.linking.push(seq); sheet.error = None; } } diff --git a/crates/ui/src/share/tests.rs b/crates/ui/src/share/tests.rs index 40d653b929..84a4ac2078 100644 --- a/crates/ui/src/share/tests.rs +++ b/crates/ui/src/share/tests.rs @@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); } +fn destinations_asked(backend: &Silent) -> usize { + backend.seen().iter().filter(|r| **r == Request::Destinations).count() +} + +fn last_link(dialog: &ShareDialog) -> u64 { + dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked") +} + +#[test] +fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() { + let (ctx, mut dialog, _) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let first = last_link(&dialog); + // A second destination is clicked before the first one answers. + dialog.apply(&ctx, vec![Act::Link("mail".into())]); + let second = last_link(&dialog); + dialog.receive(&ctx, first, Ok(Answer::Linked)); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again"); + assert_eq!(sheet.linking, [second], "the later link is still in flight"); + dialog.receive(&ctx, second, Err("no account".into())); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.linking.is_empty()); + assert_eq!(sheet.save_error.as_deref(), Some("no account")); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan"); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.signed_out(); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out"); +} + /// Whether one frame of the sheet offers "Get a link" as a button that can /// be pressed, read off the accessibility tree. fn link_button_enabled(dialog: &mut ShareDialog) -> Option { From 6a4dc4c1814c404a6b5f0db52159c68ee417d7d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:21:56 -0800 Subject: [PATCH 07/58] craft-xtask: check_commits keeps a git repository's packages on one commit A pinned name with more than one package already fails as a Count violation, but apps resolve many craft-libs crates they never list in a pin table, each from whatever commit its dependent asked for. check_commits reads the cargo metadata JSON against OneCommit rules: every package whose source is the rule's git repository resolves from one commit (the text after the source's '#'). An Extra names a package allowed at its own commit, for a dependency an app declares at a second revision. A violation lists each commit with the packages resolved from it. Packages from other sources are not checked, and a source of the repository with no commit is an error. --- crates/xtask/README.md | 14 +++- crates/xtask/src/pins.rs | 148 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 159 insertions(+), 3 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index a8afa366db..3c4eb219b0 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -10,7 +10,7 @@ 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` | -| `pins` | `pins` | `run`, `check`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, and packages the app forbids, read from `cargo metadata` within size limits | +| `pins` | `pins` | `run`, `check`, `check_commits`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, packages the app forbids, and one commit per git repository, read from `cargo metadata` within size limits | No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `pins` adds `serde_json`. @@ -207,6 +207,18 @@ Some("pdf-deps") => { or build edges; one reached only through development edges is allowed. `Name::Family("hayro")` matches `hayro` and every `hayro-*` name. - Packages the policy does not name are allowed, and an empty policy accepts any metadata. +- `check_commits` reads the same JSON against `OneCommit` rules. Every package whose source is the + rule's git repository must resolve from one commit, the text after the source's `#`. An `Extra` + names a package allowed at its own commit, for a dependency the app declares at a second revision + (DesignCraft's `craft-xml-dtd = { package = "craft-xml", … }`). A violation lists each commit with + the packages resolved from it: + + ```rust + let json = craft_xtask::pins::metadata(cargo, &limits)?; + let rule = OneCommit { url: "https://github.com/storytold/craft-libs", extra: &[Extra { name: "craft-xml", rev: DTD_REV }] }; + craft_xtask::pins::check_commits(&json, &[rule], &limits)?; + ``` + - JSON that does not parse, or lacks a field a rule needs (`resolve.nodes`, a package `id`, a node's `features` or `deps`, an edge's `dep_kinds`), is an error. - Cargo merges every target's features into one metadata result. `run_target_features` runs diff --git a/crates/xtask/src/pins.rs b/crates/xtask/src/pins.rs index 0109ae9c20..80c365cdc4 100644 --- a/crates/xtask/src/pins.rs +++ b/crates/xtask/src/pins.rs @@ -18,6 +18,10 @@ //! allowed. //! - Packages the policy does not name are allowed. An empty policy accepts any metadata. //! +//! [`check_commits`] reads the same JSON against a list of [`OneCommit`] rules: every package from +//! the rule's git repository resolves from one commit, apart from the [`Extra`] packages the rule +//! names at their own commit. +//! //! A rule that needs `resolve.nodes`, a package `id` or a node's `features` or `deps` returns an //! [`Error::Output`] when the field is missing, and so does JSON that does not parse. //! @@ -30,7 +34,7 @@ //! the command and returns [`Error::TooLarge`]. Standard error is read to its end while the command //! runs, and its first [`Limits::stderr_bytes`] bytes are kept for the error message. -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt; use std::io::{self, Read}; use std::process::{Child, Command, ExitStatus, Stdio}; @@ -127,6 +131,26 @@ pub struct Policy<'a> { pub forbidden: &'a [Forbidden<'a>], } +/// Packages from one git repository that resolve from one commit, for [`check_commits`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OneCommit<'a> { + /// The repository URL as the app's `Cargo.toml` writes it, for example + /// `https://github.com/storytold/craft-libs`. + pub url: &'a str, + /// Packages allowed at another commit. + pub extra: &'a [Extra<'a>], +} + +/// A package a [`OneCommit`] rule allows at a commit other than the one the rest resolve from, for a +/// dependency the app declares at a second revision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Extra<'a> { + /// The package name. + pub name: &'a str, + /// The full commit hash. + pub rev: &'a str, +} + /// Size limits for the commands' output and the JSON [`check`] reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Limits { @@ -193,6 +217,13 @@ pub enum Violation { /// The root it was reached from, for [`Scope::ProductionFrom`]. root: Option, }, + /// Packages from one git repository resolve from more than one commit. + Commits { + /// The repository URL. + url: String, + /// Each commit, in sorted order, with the sorted names of the packages resolved from it. + commits: Vec<(String, Vec)>, + }, } impl fmt::Display for Violation { @@ -220,6 +251,14 @@ impl fmt::Display for Violation { Violation::Forbidden { name, rule, root: Some(root) } => { write!(f, "{name}: forbidden ({rule}) and reached from {root} over normal or build dependencies") } + Violation::Commits { url, commits } => { + write!(f, "{url}: packages resolve from {} commits:", commits.len())?; + for (i, (commit, names)) in commits.iter().enumerate() { + let sep = if i == 0 { " " } else { "; " }; + write!(f, "{sep}{commit} ({})", names.join(", "))?; + } + Ok(()) + } } } } @@ -338,6 +377,49 @@ pub fn check(metadata_json: &[u8], policy: &Policy<'_>, limits: &Limits) -> Resu Ok(()) } +/// Checks `cargo metadata --format-version 1` JSON against `rules`, in order: every package whose +/// `source` is the rule's git repository resolves from one commit, except the packages its +/// [`OneCommit::extra`] list names at their own commit. The commit is the part of the `source` after +/// its `#`. Packages from other sources, path packages included, are not checked. The first broken +/// rule is returned. +pub fn check_commits(metadata_json: &[u8], rules: &[OneCommit<'_>], limits: &Limits) -> Result<(), Error> { + if metadata_json.len() > limits.metadata_bytes { + return Err(Error::TooLarge { command: METADATA.into(), limit: limits.metadata_bytes }); + } + let meta: Value = serde_json::from_slice(metadata_json).map_err(|e| invalid(format!("not JSON: {e}")))?; + let packages = meta.get("packages").and_then(Value::as_array).ok_or_else(|| invalid("packages is missing"))?; + for rule in rules { + let mut commits: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); + for package in packages { + let name = str_field(package, "name", "a package")?; + let Some(source) = package.get("source").and_then(Value::as_str) else { continue }; + let Some(commit) = git_commit(source, rule.url)? else { continue }; + if rule.extra.iter().any(|extra| extra.name == name && extra.rev == commit) { + continue; + } + commits.entry(commit).or_default().insert(name); + } + if commits.len() > 1 { + let commits = commits.into_iter().map(|(commit, names)| (commit.to_owned(), names.into_iter().map(str::to_owned).collect())).collect(); + return Err(Violation::Commits { url: rule.url.into(), commits }.into()); + } + } + Ok(()) +} + +/// The commit of a `source` from the git repository at `url`: the text after its last `#`. `None` +/// for a source from anywhere else. +fn git_commit<'s>(source: &'s str, url: &str) -> Result, Error> { + let Some(rest) = source.strip_prefix("git+").and_then(|s| s.strip_prefix(url)) else { return Ok(None) }; + if !rest.starts_with(['?', '#']) { + return Ok(None); + } + match rest.rsplit_once('#') { + Some((_, commit)) if !commit.is_empty() => Ok(Some(commit)), + _ => Err(invalid(format!("source {source} names no commit"))), + } +} + /// The packages and resolved nodes of one metadata result. struct Graph<'m> { packages: &'m [Value], @@ -629,7 +711,10 @@ fn stop(child: &mut Child) { #[cfg(test)] mod tests { - use super::{CRATES_IO, Error, FeatureRule, Forbidden, Limits, Name, Pin, Policy, Scope, Violation, check, check_target_features, git_source}; + use super::{ + CRATES_IO, Error, Extra, FeatureRule, Forbidden, Limits, Name, OneCommit, Pin, Policy, Scope, Violation, check, check_commits, + check_target_features, git_source, + }; use serde_json::{Value, json}; fn bytes(v: &Value) -> Vec { @@ -726,6 +811,65 @@ mod tests { assert!(output_error(validate(&m, &policy)).contains("kind")); } + const LIBS: &str = "https://github.com/storytold/craft-libs"; + + fn libs_metadata(packages: &[(&str, &str)]) -> Value { + let packages: Vec = packages.iter().map(|(name, source)| json!({"name": name, "source": source})).collect(); + json!({ "packages": packages }) + } + + fn check_libs(m: &Value, extra: &[Extra<'_>]) -> Result<(), Error> { + check_commits(&bytes(m), &[OneCommit { url: LIBS, extra }], &Limits::default()) + } + + #[test] + fn packages_from_one_repository_resolve_from_one_commit() { + let a = git_source(LIBS, "aaa"); + let b = git_source(LIBS, "bbb"); + let ok = libs_metadata(&[("craft-xml", &a), ("craft-zip", &a), ("serde", CRATES_IO), ("app", "")]); + assert!(check_libs(&ok, &[]).is_ok()); + assert!(check_libs(&json!({"packages": [{"name": "app"}]}), &[]).is_ok(), "a path package has no source"); + + let split = libs_metadata(&[("craft-xml", &a), ("craft-zip", &b), ("craft-xml", &b)]); + assert_eq!( + violation(check_libs(&split, &[])), + Violation::Commits { + url: LIBS.into(), + commits: vec![("aaa".into(), vec!["craft-xml".into()]), ("bbb".into(), vec!["craft-xml".into(), "craft-zip".into()])] + } + ); + assert_eq!( + violation(check_libs(&split, &[])).to_string(), + "https://github.com/storytold/craft-libs: packages resolve from 2 commits: aaa (craft-xml); bbb (craft-xml, craft-zip)" + ); + } + + #[test] + fn an_extra_allows_one_package_at_its_own_commit_only() { + let main = git_source(LIBS, "aaa"); + let dtd = git_source(LIBS, "ddd"); + let m = libs_metadata(&[("craft-xml", &main), ("craft-zip", &main), ("craft-xml", &dtd)]); + assert!(check_libs(&m, &[Extra { name: "craft-xml", rev: "ddd" }]).is_ok()); + // The extra names one package at one commit: another package there is still a second commit. + let m = libs_metadata(&[("craft-xml", &main), ("craft-xml", &dtd), ("craft-zip", &dtd)]); + assert!(matches!(violation(check_libs(&m, &[Extra { name: "craft-xml", rev: "ddd" }])), Violation::Commits { .. })); + assert!(matches!(violation(check_libs(&m, &[Extra { name: "craft-xml", rev: "eee" }])), Violation::Commits { .. })); + } + + #[test] + fn a_commit_is_read_from_any_git_source_of_the_repository_only() { + // A branch or tag dependency still names its commit after `#`. + let m = libs_metadata(&[("craft-xml", &git_source(LIBS, "aaa")), ("craft-zip", &format!("git+{LIBS}?branch=main#bbb"))]); + assert!(matches!(violation(check_libs(&m, &[])), Violation::Commits { .. })); + // A repository whose URL only starts the same is another repository. + let m = + libs_metadata(&[("craft-xml", &git_source(LIBS, "aaa")), ("other", &git_source("https://github.com/storytold/craft-libs-extra", "bbb"))]); + assert!(check_libs(&m, &[]).is_ok()); + let m = libs_metadata(&[("craft-xml", &format!("git+{LIBS}?rev=aaa"))]); + assert!(output_error(check_libs(&m, &[])).contains("names no commit")); + assert!(output_error(check_libs(&json!({"packages": [{"source": CRATES_IO}]}), &[])).contains("name")); + } + #[test] fn rejects_features_that_are_not_strings() { let m = json!({ From d376ca2aaad10087f199faa11c4fae965f4533aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:33:18 -0800 Subject: [PATCH 08/58] craft-menu: the minimal macOS app menu takes the app's translations mac::install_app_menu wrote About, Hide and Quit in English with format!() and left Services, Hide Others and Show All to muda's English defaults, so a localized app that installs it to make Cmd+Q ask first got an English app menu in every language. mac::install_app_menu_with takes a LayoutOptions and names the six items through LayoutOptions::label with the keys mac_layout already uses for the same items (About {app}, Services, Hide {app}, Hide Others, Show All, Quit {app}). install_app_menu calls it with English labels, so its menu is unchanged. --- crates/menu/README.md | 9 +++++++++ crates/menu/src/layout.rs | 27 ++++++++++++++++++++++++++ crates/menu/src/lib.rs | 3 ++- crates/menu/src/mac.rs | 29 ++++++++++++++++++++-------- crates/menu/src/tests.rs | 40 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index 063c2d0e40..7d64e35910 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -175,6 +175,15 @@ Hide Others, Show All and Quit, where Quit asks the app first. craft_menu::mac::install_app_menu(&cc.egui_ctx, "WordCraft")?; ``` +Its labels are English. `mac::install_app_menu_with` takes a `LayoutOptions` instead, and its +`label` translates `About {app}`, `Services`, `Hide {app}`, `Hide Others`, `Show All` and +`Quit {app}`, the keys `mac_layout` uses for the same items. + +```rust +#[cfg(target_os = "macos")] +craft_menu::mac::install_app_menu_with(&cc.egui_ctx, &LayoutOptions { label: &translate, ..LayoutOptions::new("WordCraft") })?; +``` + craft-menu owns muda's menu event handler. muda keeps the first one set per process, so the crate sets it once and both `mac::install` and `mac::install_app_menu` use it; a later `mac::install` replaces the minimal app menu, and a second `mac::install` returns `None`. diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index 51f45959e9..41a5a5b909 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -93,6 +93,33 @@ fn english(s: &'static str) -> String { s.into() } +/// The labels of the minimal macOS app menu (`mac::install_app_menu_with`), translated through +/// the keys [`mac_layout`] uses for its own app menu. The menu's title is the app's name. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +pub(crate) struct AppMenuLabels { + pub(crate) title: String, + pub(crate) about: String, + pub(crate) services: String, + pub(crate) hide: String, + pub(crate) hide_others: String, + pub(crate) show_all: String, + pub(crate) quit: String, +} + +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +pub(crate) fn app_menu_labels(options: &LayoutOptions) -> AppMenuLabels { + AppMenuLabels { + title: options.app_name.to_string(), + about: options.text("About {app}"), + services: options.text(Standard::Services.english()), + hide: options.text("Hide {app}"), + hide_others: options.text("Hide Others"), + show_all: options.text(Standard::ShowAll.english()), + quit: options.text("Quit {app}"), + } +} + /// A system or browser shortcut the app also uses for one of its commands. #[derive(Clone, Debug, PartialEq)] pub struct Clash { diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 6e46250c16..897d5da5ad 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -45,7 +45,8 @@ //! ([`LayoutOptions::extra_shortcuts`]). //! //! The labels the layout writes itself are English unless the app passes its translations in -//! [`LayoutOptions::label`]. +//! [`LayoutOptions::label`]. `mac::install_app_menu_with` takes the same translations for the +//! minimal app menu. //! //! **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key, //! which would skip the app's own key rules (a focused text field keeps ⌘C, ⌘V and ⌘Z, dialogs diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index e5bdd306d9..3dfc06a921 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -45,7 +45,9 @@ use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType}; use craft_keymap::{Chord, CommandRef, Key, Mods}; +use crate::LayoutOptions; use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok}; +use crate::layout::app_menu_labels; use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, native_id, structure_key, window_key}; /// Set by [`install`]: there is one full menu bar per process. @@ -117,7 +119,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) -> /// Replace winit's default macOS app menu with a minimal one whose Quit (⌘Q) asks the app first, /// for an app without a [`MenuBar`] of its own: About, Services, Hide, Hide Others, Show All and -/// Quit, labelled in English with `app_name` ("Quit WordCraft"). +/// Quit, labeled in English with `app_name` ("Quit WordCraft"). [`install_app_menu_with`] takes +/// the app's translations. /// /// winit's Quit ends the process without asking, so unsaved work is lost. This Quit has the id /// [`craft_quit::QUIT_MENU_ID`] and runs [`craft_quit::on_menu_event`]: it asks the root window to @@ -128,22 +131,32 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) -> /// Does nothing when this menu or a full menu bar ([`install`]) is already installed. On error /// winit's menu stays: the app still runs, but ⌘Q quits without asking. pub fn install_app_menu(ctx: &egui::Context, app_name: &str) -> Result<(), Box> { + install_app_menu_with(ctx, &LayoutOptions::new(app_name)) +} + +/// [`install_app_menu`] with the app's translations. [`LayoutOptions::label`] names the items +/// through the keys [`crate::mac_layout`] uses for its app menu: `About {app}`, `Services`, +/// `Hide {app}`, `Hide Others`, `Show All` and `Quit {app}`, with `{app}` replaced by +/// [`LayoutOptions::app_name`], which also titles the menu. [`LayoutOptions::extra_shortcuts`] +/// is not used. +pub fn install_app_menu_with(ctx: &egui::Context, options: &LayoutOptions) -> Result<(), Box> { if MainThreadMarker::new().is_none() { return Err("craft_menu::mac::install_app_menu runs on the main thread".into()); } if INSTALLED.load(Ordering::SeqCst) || APP_MENU.with_borrow(Option::is_some) { return Ok(()); } - let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, format!("Quit {app_name}"), true, Some(Accelerator::new(Modifiers::META, Code::KeyQ))); - let app_menu = Submenu::new(app_name, true); + let labels = app_menu_labels(options); + let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, labels.quit, true, Some(Accelerator::new(Modifiers::META, Code::KeyQ))); + let app_menu = Submenu::new(labels.title, true); app_menu.append_items(&[ - &PredefinedMenuItem::about(Some(&format!("About {app_name}")), None), + &PredefinedMenuItem::about(Some(&labels.about), None), &PredefinedMenuItem::separator(), - &PredefinedMenuItem::services(None), + &PredefinedMenuItem::services(Some(&labels.services)), &PredefinedMenuItem::separator(), - &PredefinedMenuItem::hide(Some(&format!("Hide {app_name}"))), - &PredefinedMenuItem::hide_others(None), - &PredefinedMenuItem::show_all(None), + &PredefinedMenuItem::hide(Some(&labels.hide)), + &PredefinedMenuItem::hide_others(Some(&labels.hide_others)), + &PredefinedMenuItem::show_all(Some(&labels.show_all)), &PredefinedMenuItem::separator(), &quit, ])?; diff --git a/crates/menu/src/tests.rs b/crates/menu/src/tests.rs index d0854f7391..2c78e8f604 100644 --- a/crates/menu/src/tests.rs +++ b/crates/menu/src/tests.rs @@ -162,6 +162,46 @@ fn an_untagged_quit_is_craft_quits_and_labels_are_translated() { assert_eq!(ids(&l.bar.menu(MenuRole::Window).unwrap().children), ["", "", "---", "", "---", "doc.0"]); } +/// The minimal app menu is English by default and takes the app's translations through the keys +/// the Mac layout uses for the same items. +#[test] +fn the_minimal_app_menu_labels_are_translated() { + use crate::layout::{AppMenuLabels, app_menu_labels}; + + let english = app_menu_labels(&LayoutOptions::new("Sample")); + let expected = AppMenuLabels { + title: "Sample".into(), + about: "About Sample".into(), + services: "Services".into(), + hide: "Hide Sample".into(), + hide_others: "Hide Others".into(), + show_all: "Show All".into(), + quit: "Quit Sample".into(), + }; + assert_eq!(english, expected); + + let german = |s: &'static str| match s { + "About {app}" => "Über {app}".to_string(), + "Services" => "Dienste".into(), + "Hide {app}" => "{app} ausblenden".into(), + "Hide Others" => "Andere ausblenden".into(), + "Show All" => "Alle einblenden".into(), + "Quit {app}" => "{app} beenden".into(), + other => panic!("no app menu label {other:?}"), + }; + let labels = app_menu_labels(&LayoutOptions { label: &german, ..LayoutOptions::new("Sample") }); + let expected = AppMenuLabels { + title: "Sample".into(), + about: "Über Sample".into(), + services: "Dienste".into(), + hide: "Sample ausblenden".into(), + hide_others: "Andere ausblenden".into(), + show_all: "Alle einblenden".into(), + quit: "Sample beenden".into(), + }; + assert_eq!(labels, expected); +} + /// App commands keep ⌘H, ⌘M, ⌘W and ⌘,: the system items give way, and each clash is reported. #[test] fn clashes_are_resolved_in_the_apps_favour() { From a39059470ef5436856b4c081773c782d9e0b539e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:46:56 -0800 Subject: [PATCH 09/58] atomic: cut temporary names at 64 bytes so long non-Latin names save temp_name kept the first 64 characters of the destination name. With four-byte UTF-8 characters that is 256 bytes before the suffix, over the 255-byte name limit of APFS and ext4, so a save to a valid name such as 62 emoji plus ".json" (253 bytes) failed when the staging file was created. The stem now keeps at most 64 bytes, cut at a character boundary. --- crates/atomic/src/lib.rs | 42 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 08b881e17b..6a80715839 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -588,11 +588,22 @@ fn resolve_links(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } +/// The most bytes of the destination name that a temporary name keeps. +const TEMP_STEM_BYTES: usize = 64; + /// Generates a unique, hidden temporary file name beside `file`. +/// +/// The name keeps at most the first 64 bytes of `file`, cut at a character boundary, so the +/// temporary name stays within the 255-byte name limit of common file systems for any +/// destination name. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let stem: String = file.chars().take(64).collect(); + let mut end = file.len().min(TEMP_STEM_BYTES); + while !file.is_char_boundary(end) { + end -= 1; + } + let stem = &file[..end]; #[cfg(not(target_arch = "wasm32"))] let pid = std::process::id(); #[cfg(target_arch = "wasm32")] @@ -1340,6 +1351,35 @@ mod tests { assert!(name.ends_with(".craft_tmp")); } + #[test] + fn temp_name_keeps_long_non_latin_names_under_the_name_limit() { + // 62 four-byte characters plus ".json" is a valid 253-byte name. + let file = format!("{}.json", "\u{1F600}".repeat(62)); + assert_eq!(file.len(), 253); + let name = temp_name(&file); + assert!(name.len() <= 255, "{} bytes", name.len()); + assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(16)))); + assert!(name.ends_with(".craft_tmp")); + } + + #[test] + fn temp_name_cuts_at_a_character_boundary() { + // 63 ASCII bytes then a two-byte character that would end at byte 65. + let file = format!("{}\u{e9}tail", "a".repeat(63)); + let name = temp_name(&file); + assert!(name.starts_with(&format!(".{}.", "a".repeat(63)))); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn saves_a_long_non_latin_name() { + let d = TempDir::new("long-name"); + let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62))); + assert!(atomic_write(&p, b"saved").is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec())); + assert_no_temp(&d.0); + } + #[cfg(target_arch = "wasm32")] #[test] fn wasm_atomic_write_returns_unsupported() { From e35bdcf8ea5b31173067100342b1b16b20f68b75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:48:48 -0800 Subject: [PATCH 10/58] fonts-build: EmbeddedFace::new and with_index build a face without a struct literal EmbeddedFace has only public fields, so a test or a hand-written table that needs a face writes a struct literal, and every such literal stops compiling when a field is added to the struct. EmbeddedFace::new(family, style, scripts, bytes) returns a face at index 0, and with_index(n) sets the index of a face in a collection. Both are const fn, so they also work in a static table. The README and the type's docs name them for tests and tables written by hand. --- crates/fonts-build/README.md | 5 ++++- crates/fonts-build/src/lib.rs | 20 ++++++++++++++++++++ crates/fonts-build/src/tests.rs | 10 ++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index 941426b3c1..9c91b730f2 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -99,7 +99,10 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names ( `write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts, index, bytes }` literals; any struct with those fields and that name in scope works too. -`EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`. +`EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`. Tests and +tables written by hand build a face with `EmbeddedFace::new(family, style, scripts, bytes)`, +plus `.with_index(n)` for a face in a collection; both are `const fn`. Code that uses `new` +keeps compiling when a field with a default is added; a struct literal does not. ## Document fonts diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index fffd8f0985..724a2bb9ef 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -83,6 +83,26 @@ pub struct EmbeddedFace { } impl EmbeddedFace { + /// A face at index 0 of `bytes`, for tests and for tables written by hand. Code that builds + /// faces with `new` keeps compiling when a field with a default is added; a struct literal + /// does not. + /// + /// ``` + /// use craft_fonts_build::EmbeddedFace; + /// + /// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2); + /// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2)); + /// ``` + pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self { + Self { family, style, scripts, index: 0, bytes } + } + + /// The same face at `index` in a font collection (`.ttc`). + #[must_use] + pub const fn with_index(self, index: u32) -> Self { + Self { index, ..self } + } + /// `"