From d81110ebb12d04544434da58b2ec8408ad6c67dd Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 16:12:51 -0600 Subject: [PATCH 1/7] xtask: read every dependency table in `layers`, and check image and font attribution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo xtask layers` read only `[dependencies]` of 13 hand-listed crates. It now reads `cargo metadata`, so a dependency under `[target.…]` counts, a renamed one is seen under its package name, and a crate under `crates/` without a layer in `LAYERS` fails. Dev- and build-dependencies stay out. `cargo xtask attribution` fails an image or font file (png, jpg, gif, webp, ico, svg, ttf, otf, woff) that no row of ATTRIBUTION.md names by path, directory or pattern. CI runs it in the `select` job. --- .github/workflows/ci.yml | 3 + AGENTS.md | 7 +- docs/contributing.md | 3 +- xtask/src/attribution.rs | 117 +++++++++++++++++++++++++++++++++ xtask/src/changed.rs | 14 ++-- xtask/src/main.rs | 138 +++++++++++++++++++++++++++++++++++---- 6 files changed, 261 insertions(+), 21 deletions(-) create mode 100644 xtask/src/attribution.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a55b933a0..b94fbd4e94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -366,6 +366,9 @@ jobs: # (reuses the xtask already built above, #2289). - name: Test hygiene run: cargo run --locked -q -p xtask -- test-hygiene + # Every image and font file has a row in ATTRIBUTION.md. + - name: Attribution rows + run: cargo run --locked -q -p xtask -- attribution plan: name: Platforms diff --git a/AGENTS.md b/AGENTS.md index cc1e04852f..cd639b8c76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,7 +118,9 @@ measures. catalogs in `crates/ui-egui/src/i18n/*.tsv`: a missing entry shows in English, and the maintainer translates them before each release (format in `docs/i18n.md`). Command ids, data and the CLI are never translated. -- **Layering** is enforced by `cargo xtask layers`: nothing below L6 depends on egui/eframe/rfd. +- **Layering** is enforced by `cargo xtask layers`: nothing below L6 depends on egui/eframe/rfd, a crate + depends only on lower layers (`[target.…]` dependencies count, dev- and build-dependencies don't), and a + new crate under `crates/` gets its layer in `LAYERS` (`xtask/src/main.rs`). - **The expression language has one vocabulary**: a new function, variable or keyword goes in the catalogs in `crates/data/src/query.rs` (`Func::spec`, `VARS`, `Kw`), which the parser reads, and in `docs/user-guide/expressions.md`; the `query` tests fail when the guide misses @@ -139,7 +141,8 @@ the pull request which of these it reaches and why the rest don't apply: ## Assets - No third-party vendor icons, images, styles, fonts, help text or code. Icons are drawn in - code (`icons.rs`). Every asset file has a row in `ATTRIBUTION.md`. + code (`icons.rs`). Every asset file has a row in `ATTRIBUTION.md`; `cargo xtask attribution` (in CI) fails an image or + font file that no row names, by path, directory or pattern. - Never copy or translate code from GPL, LGPL or other copyleft projects (such as GRASS, QGIS or GEOS) into RustGIS, by hand or with an AI tool. Implementing a published algorithm is fine: cite the paper or standard. Name in the pull request any project whose code you followed (see diff --git a/docs/contributing.md b/docs/contributing.md index ae0419958a..1f8524a78a 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -107,7 +107,8 @@ Other workspace tasks: | Task | Purpose | | --- | --- | | `cargo xtask changed [--list] [base]` | Run the `cargo xtask ci` checks on only the packages your branch changes and those that depend on them: a quicker check while you work. A file outside every package that no package includes, such as `Cargo.lock`, checks the whole workspace. `--list` prints the packages without checking them | -| `cargo xtask layers` | Check crate dependency direction and keep UI dependencies out of lower layers | +| `cargo xtask layers` | Check crate dependency direction (target-specific dependencies included) and keep UI dependencies out of lower layers; a new crate under `crates/` needs a layer in `LAYERS` | +| `cargo xtask attribution` | Check that every image and font file has a row in `ATTRIBUTION.md` (its path, a directory above it or a pattern in backticks) | | `cargo xtask notices` | Regenerate the shipped `THIRD-PARTY-LICENSES.txt` files after changing dependencies, or after adding code or data from another project to `INCLUDED` in `xtask/src/notices.rs` (with its licence text in `third-party/`); requires `cargo-about` | | `cargo xtask notices --check` | Check the notices without writing them; stale notices warn in CI but block releases | | `cargo xtask web-pwa ` | Generate the service worker in a Trunk build output directory, such as `dist/web` | diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs new file mode 100644 index 0000000000..2dd745a16f --- /dev/null +++ b/xtask/src/attribution.rs @@ -0,0 +1,117 @@ +//! `cargo xtask attribution`: every image and font file in the repository has a row in +//! `ATTRIBUTION.md`. +//! +//! AGENTS.md says every asset file has a row. The table also lists test data and fixtures, but +//! not by any rule that a program could apply to every file, so this checks the classes the rule +//! names: images, icons and fonts. A file is covered when a backticked path in `ATTRIBUTION.md` +//! names it, names a directory above it, matches it as a pattern (`*` stands for any characters, +//! `/` included), or, with no `/`, names it or matches it by its file name alone. + +use std::path::Path; + +/// The extensions of image, icon and font files. +const ASSET_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "icns", "svg", "ttf", "otf", "ttc", "woff", "woff2"]; + +/// Whether `text` matches `pattern`, in which `*` stands for any run of characters. +fn wildcard(pattern: &str, text: &str) -> bool { + let parts: Vec<&str> = pattern.split('*').collect(); + let [first, rest @ ..] = parts.as_slice() else { return false }; + let Some(mut at) = text.strip_prefix(first) else { return false }; + let Some((last, middle)) = rest.split_last() else { return at.is_empty() }; + for part in middle { + let Some(found) = at.find(part) else { return false }; + at = &at[found + part.len()..]; + } + at.ends_with(last) && at.len() >= last.len() +} + +/// The paths and patterns `ATTRIBUTION.md` names: everything in backticks that looks like a file +/// or a directory, with a trailing `/` taken off. +fn named(attribution: &str) -> Vec<&str> { + attribution + .split('`') + .skip(1) + .step_by(2) + .filter(|t| !t.is_empty() && !t.contains(char::is_whitespace) && (t.contains('/') || t.contains('.'))) + .map(|t| t.trim_end_matches('/')) + .collect() +} + +/// The asset files in `files` that no row of `attribution` covers. +fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { + let named = named(attribution); + files + .iter() + .copied() + .filter(|f| f.rsplit_once('.').is_some_and(|(_, ext)| ASSET_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))) + .filter(|f| { + let name = f.rsplit('/').next().unwrap_or(f); + !named.iter().any(|n| if n.contains('/') { f.starts_with(&format!("{n}/")) || wildcard(n, f) } else { wildcard(n, name) }) + }) + .collect() +} + +/// Runs `cargo xtask attribution`: fails listing each image or font file that is tracked (or new +/// and not ignored) without a row. +pub fn run(root: &Path) -> Result<(), String> { + let attribution = std::fs::read_to_string(root.join("ATTRIBUTION.md")).map_err(|e| format!("ATTRIBUTION.md: {e}"))?; + let listed = super::changed::git(root, &["ls-files", "--cached", "--others", "--exclude-standard", "-z"])?; + // A file removed from the working tree but not yet from the index doesn't need a row. + let files: Vec<&str> = listed.split('\0').filter(|f| !f.is_empty() && root.join(f).is_file()).collect(); + let missing = uncovered(&files, &attribution); + if missing.is_empty() { + println!("attribution: ok"); + return Ok(()); + } + Err(format!( + "{}\nattribution: the files above are images or fonts with no row in ATTRIBUTION.md. Add a row \ + that names each one (or its directory, or a pattern like `dir/*.png`) in backticks, with its author or source and its licence", + missing.iter().map(|f| format!("{f}: no row in ATTRIBUTION.md")).collect::>().join("\n") + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TABLE: &str = "| Icon (`assets/logo.png`) | us | MIT |\n\ + | Fonts (`assets/fonts/*.otf`) | a foundry | OFL |\n\ + | Test corpus (`crates/map/testdata/generated/`: styles and sample data) | us | MIT |\n\ + | Test images (`crates/x/tests/a.png`, `b.png`) | us | MIT |\n"; + + #[test] + fn a_file_a_row_names_is_covered() { + let files = [ + "assets/logo.png", + "assets/fonts/hack.otf", + "crates/map/testdata/generated/data/marker.png", + "crates/x/tests/a.png", + "crates/y/tests/b.png", + ]; + assert_eq!(uncovered(&files, TABLE), Vec::<&str>::new()); + } + + #[test] + fn an_image_or_font_without_a_row_is_found() { + let files = + ["assets/new-logo.png", "assets/fonts/hack.ttf", "assets/icon.SVG", "crates/map/testdata/other/marker.png", "docs/shot.webp"]; + assert_eq!(uncovered(&files, TABLE), files.to_vec()); + } + + #[test] + fn other_files_and_lookalike_directories_are_not_asset_files() { + let files = ["crates/data/src/lib.rs", "crates/data/tests/data.geojson", "README.md", "crates/map/testdata/generated-more/x.png"]; + assert_eq!(uncovered(&files, TABLE), vec!["crates/map/testdata/generated-more/x.png"]); + } + + #[test] + fn a_pattern_matches_the_whole_path() { + assert!(wildcard("a/*.png", "a/b/c.png")); + assert!(wildcard("a/b*", "a/b")); + assert!(!wildcard("a/*.png", "a/b.png.bak")); + assert!(!wildcard("a/*.png", "b/a/c.png")); + assert!(wildcard("x*y*z", "x1y2z")); + assert!(!wildcard("x*y*z", "x1z")); + assert!(!wildcard("ab*b", "ab")); + } +} diff --git a/xtask/src/changed.rs b/xtask/src/changed.rs index e4a259195e..4386ef3a20 100644 --- a/xtask/src/changed.rs +++ b/xtask/src/changed.rs @@ -228,7 +228,7 @@ pub(crate) fn compile_time_reads(root: &Path, packages: &[Package]) -> Result Result { +pub(crate) fn git(root: &Path, args: &[&str]) -> Result { let out = Command::new("git").args(args).current_dir(root).output().map_err(|e| format!("git: {e}"))?; if !out.status.success() { return Err(format!("git {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); @@ -266,8 +266,8 @@ fn base(root: &Path, asked: Option<&str>) -> Result<(String, String, usize), Str best.ok_or_else(|| "no base: name one, as in `cargo xtask changed upstream/main`".into()) } -/// The workspace's packages, from `cargo metadata`. -fn packages(root: &Path) -> Result, String> { +/// The workspace's packages with their dependencies, as `cargo metadata` gives them. +pub(crate) fn metadata(root: &Path) -> Result { let out = Command::new(env!("CARGO")) .args(["metadata", "--format-version", "1", "--no-deps", "--locked"]) .current_dir(root) @@ -276,7 +276,12 @@ fn packages(root: &Path) -> Result, String> { if !out.status.success() { return Err(format!("cargo metadata failed: {}", String::from_utf8_lossy(&out.stderr).trim())); } - let meta: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: {e}"))?; + serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: {e}")) +} + +/// The workspace's packages, from `cargo metadata`. +fn packages(root: &Path) -> Result, String> { + let meta = metadata(root)?; let workspace = PathBuf::from(meta["workspace_root"].as_str().unwrap_or_default()); let mut list = Vec::new(); for p in meta["packages"].as_array().into_iter().flatten() { @@ -367,6 +372,7 @@ pub fn run(root: &Path, args: &[String]) -> Result<(), String> { .and_then(|_| super::cargo(&clippy)) .and_then(|_| super::cargo(&test)) .and_then(|_| super::layers()) + .and_then(|_| super::attribution::run(root)) // Counted across the workspace: a change anywhere can add a direct use. .and_then(|_| super::rows::run(root, &[])) // The project schema is generated from types in rustgis-engine and below, so any diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a71f008c54..e84918b446 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,6 +1,8 @@ -//! `cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa ` +//! `cargo xtask ci | changed [--list] [base] | layers | attribution | memory [--cli ] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa ` //! -//! - `layers`: enforces the crate layering (nothing below L6 may depend on egui/eframe/rfd). +//! - `layers`: enforces the crate layering (nothing below L6 may depend on egui/eframe/rfd, a +//! crate may only depend on lower layers, and every crate under `crates/` has a layer). +//! - `attribution`: every image and font file has a row in `ATTRIBUTION.md` (see `attribution.rs`). //! - `memory [--cli ] [--update]`: the command line's peak memory on generated data, per //! workflow and as a multiple of loading alone, checked against `xtask/memory-limits.txt` //! (Linux; see `memory.rs`). @@ -18,12 +20,14 @@ //! - `web-pwa `: writes the web app's service worker into a `trunk build` output directory //! (`dist/web`) from the template `apps/rustgis-web/sw.js`, listing the built files to cache. +mod attribution; mod changed; mod memory; mod notices; mod rows; mod test_hygiene; +use serde_json::Value; use std::process::{Command, ExitCode}; const LAYERS: &[(&str, u8)] = &[ @@ -47,14 +51,56 @@ fn root() -> std::path::PathBuf { std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().map(|p| p.to_path_buf()).unwrap_or_default() } +/// `cargo xtask layers`: the layering of the crates under `crates/`, read from `cargo metadata`. fn layers() -> Result<(), String> { + let errs = layer_errors(&crate_deps(&changed::metadata(&root())?)); + if errs.is_empty() { + println!("layers: ok"); + Ok(()) + } else { + Err(errs.join("\n")) + } +} + +/// Each package under `crates/` as (its directory name, the packages it depends on). A dependency +/// counts whatever its target (`[target.'cfg(…)'.dependencies]`) and whether or not it is optional; +/// dev- and build-dependencies don't, as AGENTS.md's rule is about what a crate is built from. +fn crate_deps(meta: &Value) -> Vec<(String, Vec)> { + let workspace = std::path::Path::new(meta["workspace_root"].as_str().unwrap_or_default()); + let mut out = Vec::new(); + for package in meta["packages"].as_array().into_iter().flatten() { + let manifest = std::path::Path::new(package["manifest_path"].as_str().unwrap_or_default()); + let dir = manifest.parent().and_then(|d| d.strip_prefix(workspace).ok()).and_then(|d| d.strip_prefix("crates").ok()); + let Some(dir) = dir.and_then(|d| d.to_str()).filter(|d| !d.is_empty() && !d.contains(['/', '\\'])) else { continue }; + let deps = package["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["kind"].is_null()) + .filter_map(|d| d["name"].as_str().map(str::to_string)) + .collect(); + out.push((dir.to_string(), deps)); + } + out +} + +/// What is wrong with the layering of `crates`: a crate with no layer in [`LAYERS`] (a new crate +/// must be given one), a layer for a crate that isn't there, a UI crate below L6, and a crate that +/// depends on one at or above its own layer. +fn layer_errors(crates: &[(String, Vec)]) -> Vec { let mut errs = Vec::new(); + for (dir, _) in crates { + if !LAYERS.iter().any(|(k, _)| k == dir) { + errs.push(format!("crates/{dir} has no layer: add it to LAYERS in xtask/src/main.rs")); + } + } for (krate, level) in LAYERS { - let text = std::fs::read_to_string(root().join("crates").join(krate).join("Cargo.toml")).map_err(|e| e.to_string())?; - let deps = text.split("[dependencies]").nth(1).unwrap_or("").split("\n[").next().unwrap_or(""); - for line in deps.lines() { - let name = line.split(['=', ' ']).next().unwrap_or("").trim(); - if *level < 6 && UI_ONLY.contains(&name) { + let Some((_, deps)) = crates.iter().find(|(dir, _)| dir == krate) else { + errs.push(format!("LAYERS has {krate}, but there is no crates/{krate}: take it out of xtask/src/main.rs")); + continue; + }; + for name in deps { + if *level < 6 && UI_ONLY.contains(&name.as_str()) { errs.push(format!("{krate} (L{level}) depends on UI crate {name}")); } if let Some(dep) = name.strip_prefix("rustgis-") @@ -65,12 +111,7 @@ fn layers() -> Result<(), String> { } } } - if errs.is_empty() { - println!("layers: ok"); - Ok(()) - } else { - Err(errs.join("\n")) - } + errs } fn cargo(args: &[&str]) -> Result<(), String> { @@ -79,7 +120,7 @@ fn cargo(args: &[&str]) -> Result<(), String> { if st.success() { Ok(()) } else { Err(format!("cargo {} failed", args.join(" "))) } } -/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering, direct row +/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering, attribution rows, direct row /// uses and the project schema check, on the whole workspace. fn ci() -> Result<(), String> { test_hygiene::run(&root())?; @@ -87,6 +128,7 @@ fn ci() -> Result<(), String> { .and_then(|_| cargo(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"])) .and_then(|_| cargo(&["test", "--workspace", "-q"])) .and_then(|_| layers()) + .and_then(|_| attribution::run(&root())) .and_then(|_| rows::run(&root(), &[])) .and_then(|_| schema(true)) } @@ -206,6 +248,7 @@ fn main() -> ExitCode { let task = std::env::args().nth(1).unwrap_or_default(); let r = match task.as_str() { "layers" => layers(), + "attribution" => attribution::run(&root()), "test-hygiene" => test_hygiene::run(&root()), "rows" => rows::run(&root(), &std::env::args().skip(2).collect::>()), "memory" => memory::run(&root(), &std::env::args().skip(2).collect::>()), @@ -302,4 +345,71 @@ mod tests { assert!(web_shell(&dir, "sw").is_err()); let _ = std::fs::remove_dir_all(&dir); } + + /// A dependency as (name, kind, target), as `cargo metadata` gives them. + type Dep<'a> = (&'a str, Option<&'a str>, Option<&'a str>); + + /// A `cargo metadata` document with one package under `crates/` for each (directory, dependencies), + /// a dependency being (name, kind, target). + fn metadata(crates: &[(&str, &[Dep])]) -> Value { + let packages: Vec = crates + .iter() + .map(|(dir, deps)| { + let deps: Vec = deps.iter().map(|(name, kind, target)| serde_json::json!({"name": name, "kind": kind, "target": target})).collect(); + serde_json::json!({"name": format!("rustgis-{dir}"), "manifest_path": format!("/w/crates/{dir}/Cargo.toml"), "dependencies": deps}) + }) + .collect(); + serde_json::json!({"workspace_root": "/w", "packages": packages}) + } + + /// Every crate in [`LAYERS`], with no dependencies, plus these changes. + fn all_crates(changes: &[(&str, &[Dep])]) -> Value { + let mut crates: Vec<(&str, &[Dep])> = LAYERS.iter().map(|(k, _)| (*k, &[][..])).collect(); + for (dir, deps) in changes { + crates.retain(|(k, _)| k != dir); + crates.push((dir, deps)); + } + metadata(&crates) + } + + #[test] + fn layers_accepts_the_layering_as_it_is() { + let ok = all_crates(&[("engine", &[("rustgis-data", None, None), ("serde", None, None)]), ("ui-egui", &[("egui", None, None)])]); + assert_eq!(layer_errors(&crate_deps(&ok)), Vec::::new()); + } + + #[test] + fn layers_reads_dependencies_that_are_only_for_some_targets() { + let plain = all_crates(&[("engine", &[("rfd", None, None)])]); + let targeted = all_crates(&[("engine", &[("rfd", None, Some("cfg(not(target_arch = \"wasm32\"))"))])]); + for meta in [plain, targeted] { + assert_eq!(layer_errors(&crate_deps(&meta)), vec!["engine (L4) depends on UI crate rfd".to_string()]); + } + let upward = all_crates(&[("data", &[("rustgis-engine", None, Some("cfg(windows)"))])]); + assert_eq!(layer_errors(&crate_deps(&upward)), vec!["data (L1) depends on engine (L4)".to_string()]); + } + + #[test] + fn layers_leaves_dev_and_build_dependencies_out() { + let meta = all_crates(&[("geom", &[("egui_kittest", Some("dev"), None), ("rustgis-engine", Some("build"), None)])]); + assert_eq!(layer_errors(&crate_deps(&meta)), Vec::::new()); + } + + #[test] + fn layers_refuses_a_crate_without_a_layer_and_a_layer_without_a_crate() { + let mut crates: Vec<(&str, &[Dep])> = LAYERS.iter().filter(|(k, _)| *k != "keychain").map(|(k, _)| (*k, &[][..])).collect(); + crates.push(("newcomer", &[])); + let errs = layer_errors(&crate_deps(&metadata(&crates))); + assert_eq!(errs.len(), 2, "{errs:?}"); + assert!(errs.iter().any(|e| e.starts_with("crates/newcomer has no layer"))); + assert!(errs.iter().any(|e| e.starts_with("LAYERS has keychain, but there is no crates/keychain"))); + } + + #[test] + fn layers_ignores_packages_outside_crates() { + let mut meta = all_crates(&[]); + let app = serde_json::json!({"name": "rustgis", "manifest_path": "/w/apps/rustgis/Cargo.toml", "dependencies": [{"name": "egui", "kind": null, "target": null}]}); + meta["packages"].as_array_mut().unwrap().push(app); + assert_eq!(layer_errors(&crate_deps(&meta)), Vec::::new()); + } } From 5cd221d1b6c40aab0a75a800fbb9e05479e37fc7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 16:56:22 -0600 Subject: [PATCH 2/7] xtask: a bare name covers no asset, spaces in a path, and `changed` checks attribution-only edits A row now covers a file only by a path with a `/` (the file, a directory above it, or a pattern): a bare file name matched same-named files anywhere. A path may hold spaces, and a top-level directory such as `icons/` covers what is under it. `cargo xtask changed` runs the attribution check when only non-code files changed, which is how ATTRIBUTION.md alone can break it. A package nested below a crate's directory is reported as having no layer instead of being skipped. --- AGENTS.md | 4 ++-- xtask/src/attribution.rs | 51 ++++++++++++++++++++++++++-------------- xtask/src/changed.rs | 3 ++- xtask/src/main.rs | 19 +++++++++++---- 4 files changed, 53 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cd639b8c76..3a682a3983 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,8 +169,8 @@ removes a limit against its base (a new memory scenario is fine). A maintainer a raise by commenting on the pull request with the line the failure prints for it, on a line of its own (``), then re-runs the job. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes -and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers` and -`rows` when packages are checked), or everything when a +and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers`, +`attribution` and `rows` when packages are checked), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it. A new dependency must have a licence `deny.toml` allows (CI runs `cargo deny check licenses`); after changing dependencies, run `cargo xtask notices` to refresh the `THIRD-PARTY-LICENSES.txt` files the diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs index 2dd745a16f..cfd12a6ec5 100644 --- a/xtask/src/attribution.rs +++ b/xtask/src/attribution.rs @@ -4,13 +4,15 @@ //! AGENTS.md says every asset file has a row. The table also lists test data and fixtures, but //! not by any rule that a program could apply to every file, so this checks the classes the rule //! names: images, icons and fonts. A file is covered when a backticked path in `ATTRIBUTION.md` -//! names it, names a directory above it, matches it as a pattern (`*` stands for any characters, -//! `/` included), or, with no `/`, names it or matches it by its file name alone. +//! (one with a `/`) names it, names a directory above it (a trailing `/` is optional), or matches +//! it as a pattern, in which `*` stands for any characters, `/` included. A bare file name covers +//! nothing, so a row can't cover a same-named file somewhere else. use std::path::Path; /// The extensions of image, icon and font files. -const ASSET_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "icns", "svg", "ttf", "otf", "ttc", "woff", "woff2"]; +const ASSET_EXTENSIONS: &[&str] = + &["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "icns", "svg", "ttf", "otf", "ttc", "woff", "woff2", "eot"]; /// Whether `text` matches `pattern`, in which `*` stands for any run of characters. fn wildcard(pattern: &str, text: &str) -> bool { @@ -22,18 +24,19 @@ fn wildcard(pattern: &str, text: &str) -> bool { let Some(found) = at.find(part) else { return false }; at = &at[found + part.len()..]; } - at.ends_with(last) && at.len() >= last.len() + at.ends_with(last) } -/// The paths and patterns `ATTRIBUTION.md` names: everything in backticks that looks like a file -/// or a directory, with a trailing `/` taken off. -fn named(attribution: &str) -> Vec<&str> { +/// The paths and patterns `ATTRIBUTION.md` names: everything in backticks with a `/` in it (the +/// path of a file may hold spaces), and whether it ends in `/`, which marks a directory. +fn named(attribution: &str) -> Vec<(&str, bool)> { attribution .split('`') .skip(1) .step_by(2) - .filter(|t| !t.is_empty() && !t.contains(char::is_whitespace) && (t.contains('/') || t.contains('.'))) - .map(|t| t.trim_end_matches('/')) + .filter(|t| t.contains('/') && !t.starts_with('/') && !t.contains(['\n', '\t'])) + .map(|t| (t.trim_end_matches('/'), t.ends_with('/'))) + .filter(|(t, _)| !t.is_empty()) .collect() } @@ -44,10 +47,7 @@ fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { .iter() .copied() .filter(|f| f.rsplit_once('.').is_some_and(|(_, ext)| ASSET_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))) - .filter(|f| { - let name = f.rsplit('/').next().unwrap_or(f); - !named.iter().any(|n| if n.contains('/') { f.starts_with(&format!("{n}/")) || wildcard(n, f) } else { wildcard(n, name) }) - }) + .filter(|f| !named.iter().any(|(n, _)| *f == *n || f.starts_with(&format!("{n}/")) || wildcard(n, f))) .collect() } @@ -76,17 +76,22 @@ mod tests { const TABLE: &str = "| Icon (`assets/logo.png`) | us | MIT |\n\ | Fonts (`assets/fonts/*.otf`) | a foundry | OFL |\n\ + | Spaced (`assets/fonts/My Font.ttf`) | a foundry | OFL |\n\ + | Top level (`icons/`) | us | MIT |\n\ | Test corpus (`crates/map/testdata/generated/`: styles and sample data) | us | MIT |\n\ - | Test images (`crates/x/tests/a.png`, `b.png`) | us | MIT |\n"; + | Test images (`crates/x/tests/a.png`, `b.png`) | us | MIT |\n\ + | Prose (`cargo xtask notices`, `tl!(\"x\")`, `/etc/hosts`) | n/a | n/a |\n"; #[test] fn a_file_a_row_names_is_covered() { let files = [ "assets/logo.png", "assets/fonts/hack.otf", + "assets/fonts/My Font.ttf", + "icons/a.svg", + "icons/deep/b.png", "crates/map/testdata/generated/data/marker.png", "crates/x/tests/a.png", - "crates/y/tests/b.png", ]; assert_eq!(uncovered(&files, TABLE), Vec::<&str>::new()); } @@ -98,10 +103,22 @@ mod tests { assert_eq!(uncovered(&files, TABLE), files.to_vec()); } + #[test] + fn a_bare_file_name_covers_nothing() { + // `b.png` is named in a row, but only its directory's row can cover `crates/y/tests/b.png`. + assert_eq!(uncovered(&["crates/y/tests/b.png", "b.png"], TABLE), vec!["crates/y/tests/b.png", "b.png"]); + } + #[test] fn other_files_and_lookalike_directories_are_not_asset_files() { - let files = ["crates/data/src/lib.rs", "crates/data/tests/data.geojson", "README.md", "crates/map/testdata/generated-more/x.png"]; - assert_eq!(uncovered(&files, TABLE), vec!["crates/map/testdata/generated-more/x.png"]); + let files = [ + "crates/data/src/lib.rs", + "crates/data/tests/data.geojson", + "README.md", + "crates/map/testdata/generated-more/x.png", + "iconsx/a.png", + ]; + assert_eq!(uncovered(&files, TABLE), vec!["crates/map/testdata/generated-more/x.png", "iconsx/a.png"]); } #[test] diff --git a/xtask/src/changed.rs b/xtask/src/changed.rs index 4386ef3a20..1816876ce9 100644 --- a/xtask/src/changed.rs +++ b/xtask/src/changed.rs @@ -337,7 +337,8 @@ pub fn run(root: &Path, args: &[String]) -> Result<(), String> { } Selection::NoPackages => { println!("changed: only non-code files changed; no Rust packages need checking"); - Ok(()) + // ATTRIBUTION.md is one of them: dropping a row must not pass here. + super::attribution::run(root) } Selection::All(_) if list => { println!("all"); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index e84918b446..4bd93a6510 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -71,7 +71,8 @@ fn crate_deps(meta: &Value) -> Vec<(String, Vec)> { for package in meta["packages"].as_array().into_iter().flatten() { let manifest = std::path::Path::new(package["manifest_path"].as_str().unwrap_or_default()); let dir = manifest.parent().and_then(|d| d.strip_prefix(workspace).ok()).and_then(|d| d.strip_prefix("crates").ok()); - let Some(dir) = dir.and_then(|d| d.to_str()).filter(|d| !d.is_empty() && !d.contains(['/', '\\'])) else { continue }; + // A package nested below a crate's directory is kept, with its path: it has no layer. + let Some(dir) = dir.and_then(|d| d.to_str()).filter(|d| !d.is_empty()) else { continue }; let deps = package["dependencies"] .as_array() .into_iter() @@ -79,7 +80,7 @@ fn crate_deps(meta: &Value) -> Vec<(String, Vec)> { .filter(|d| d["kind"].is_null()) .filter_map(|d| d["name"].as_str().map(str::to_string)) .collect(); - out.push((dir.to_string(), deps)); + out.push((dir.replace('\\', "/"), deps)); } out } @@ -120,8 +121,8 @@ fn cargo(args: &[&str]) -> Result<(), String> { if st.success() { Ok(()) } else { Err(format!("cargo {} failed", args.join(" "))) } } -/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering, attribution rows, direct row -/// uses and the project schema check, on the whole workspace. +/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering, attribution +/// rows, direct row uses and the project schema check, on the whole workspace. fn ci() -> Result<(), String> { test_hygiene::run(&root())?; cargo(&["fmt", "--all", "--check"]) @@ -405,6 +406,16 @@ mod tests { assert!(errs.iter().any(|e| e.starts_with("LAYERS has keychain, but there is no crates/keychain"))); } + #[test] + fn layers_sees_a_package_nested_below_a_crate() { + let mut crates: Vec<(&str, &[Dep])> = LAYERS.iter().map(|(k, _)| (*k, &[][..])).collect(); + crates.push(("data/inner", &[])); + assert_eq!( + layer_errors(&crate_deps(&metadata(&crates))), + vec!["crates/data/inner has no layer: add it to LAYERS in xtask/src/main.rs".to_string()] + ); + } + #[test] fn layers_ignores_packages_outside_crates() { let mut meta = all_crates(&[]); From 4f18c8baa9b7f064f0a97208cf542ceb3ccbaa3c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 17:36:35 -0600 Subject: [PATCH 3/7] xtask: a bare name covers a file at the repository root, and the docs say where attribution runs A row naming `logo.png` covers the root's `logo.png` and no same-named file below it, so a root asset can be covered. The `changed` line in AGENTS.md says attribution also runs when only non-code files change, and the comment on `crate_deps` says why dev- and build-dependencies stay out. --- AGENTS.md | 4 ++-- xtask/src/attribution.rs | 29 +++++++++++++++++++---------- xtask/src/main.rs | 5 +++-- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3a682a3983..0a6ba174be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,8 +169,8 @@ removes a limit against its base (a new memory scenario is fine). A maintainer a raise by commenting on the pull request with the line the failure prints for it, on a line of its own (``), then re-runs the job. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes -and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers`, -`attribution` and `rows` when packages are checked), or everything when a +and those that depend on them (and `test-hygiene` on the whole workspace, `attribution` also when only +non-code files change, and formatting, `layers` and `rows` when packages are checked), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it. A new dependency must have a licence `deny.toml` allows (CI runs `cargo deny check licenses`); after changing dependencies, run `cargo xtask notices` to refresh the `THIRD-PARTY-LICENSES.txt` files the diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs index cfd12a6ec5..5771f094bd 100644 --- a/xtask/src/attribution.rs +++ b/xtask/src/attribution.rs @@ -5,8 +5,9 @@ //! not by any rule that a program could apply to every file, so this checks the classes the rule //! names: images, icons and fonts. A file is covered when a backticked path in `ATTRIBUTION.md` //! (one with a `/`) names it, names a directory above it (a trailing `/` is optional), or matches -//! it as a pattern, in which `*` stands for any characters, `/` included. A bare file name covers -//! nothing, so a row can't cover a same-named file somewhere else. +//! it as a pattern, in which `*` stands for any characters, `/` included. A bare file name (or a +//! pattern with no `/`) covers only a file at the repository root, so a row can't cover a +//! same-named file somewhere else. use std::path::Path; @@ -27,15 +28,17 @@ fn wildcard(pattern: &str, text: &str) -> bool { at.ends_with(last) } -/// The paths and patterns `ATTRIBUTION.md` names: everything in backticks with a `/` in it (the -/// path of a file may hold spaces), and whether it ends in `/`, which marks a directory. +/// The paths and patterns `ATTRIBUTION.md` names: everything in backticks that has a `/` in it (the +/// path of a file may hold spaces) or is a single word with a `.` (a file at the root), each with +/// a trailing `/` taken off and whether it had a `/` at all. fn named(attribution: &str) -> Vec<(&str, bool)> { attribution .split('`') .skip(1) .step_by(2) - .filter(|t| t.contains('/') && !t.starts_with('/') && !t.contains(['\n', '\t'])) - .map(|t| (t.trim_end_matches('/'), t.ends_with('/'))) + .filter(|t| !t.contains(['\n', '\t']) && !t.starts_with('/')) + .filter(|t| t.contains('/') || (t.contains('.') && !t.contains(' '))) + .map(|t| (t.trim_end_matches('/'), t.contains('/'))) .filter(|(t, _)| !t.is_empty()) .collect() } @@ -47,7 +50,11 @@ fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { .iter() .copied() .filter(|f| f.rsplit_once('.').is_some_and(|(_, ext)| ASSET_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))) - .filter(|f| !named.iter().any(|(n, _)| *f == *n || f.starts_with(&format!("{n}/")) || wildcard(n, f))) + .filter(|f| { + !named.iter().any(|(n, path)| { + if *path { f == n || f.starts_with(&format!("{n}/")) || wildcard(n, f) } else { !f.contains('/') && wildcard(n, f) } + }) + }) .collect() } @@ -80,6 +87,7 @@ mod tests { | Top level (`icons/`) | us | MIT |\n\ | Test corpus (`crates/map/testdata/generated/`: styles and sample data) | us | MIT |\n\ | Test images (`crates/x/tests/a.png`, `b.png`) | us | MIT |\n\ + | Root logo (`logo.svg`) | us | MIT |\n\ | Prose (`cargo xtask notices`, `tl!(\"x\")`, `/etc/hosts`) | n/a | n/a |\n"; #[test] @@ -104,9 +112,10 @@ mod tests { } #[test] - fn a_bare_file_name_covers_nothing() { - // `b.png` is named in a row, but only its directory's row can cover `crates/y/tests/b.png`. - assert_eq!(uncovered(&["crates/y/tests/b.png", "b.png"], TABLE), vec!["crates/y/tests/b.png", "b.png"]); + fn a_bare_file_name_covers_only_a_file_at_the_root() { + // `b.png` and `logo.svg` are named in rows: they cover the root's files, not same-named ones below. + let files = ["crates/y/tests/b.png", "b.png", "logo.svg", "assets/logo.svg", "other.svg"]; + assert_eq!(uncovered(&files, TABLE), vec!["crates/y/tests/b.png", "assets/logo.svg", "other.svg"]); } #[test] diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 4bd93a6510..4918145634 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -63,8 +63,9 @@ fn layers() -> Result<(), String> { } /// Each package under `crates/` as (its directory name, the packages it depends on). A dependency -/// counts whatever its target (`[target.'cfg(…)'.dependencies]`) and whether or not it is optional; -/// dev- and build-dependencies don't, as AGENTS.md's rule is about what a crate is built from. +/// counts whatever its target (`[target.'cfg(…)'.dependencies]`) and whether or not it is optional. +/// Dev- and build-dependencies don't: neither is in what the crate ships, and AGENTS.md's rule +/// ("nothing below L6 depends on egui/eframe/rfd") doesn't clearly cover them. fn crate_deps(meta: &Value) -> Vec<(String, Vec)> { let workspace = std::path::Path::new(meta["workspace_root"].as_str().unwrap_or_default()); let mut out = Vec::new(); From ffa7996aff353a474d6afed97ea163520765ffdb Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 18:21:16 -0600 Subject: [PATCH 4/7] xtask: refuse a non-UTF-8 file name in the attribution check, and pair backticks per line A name that git lists with bytes that aren't UTF-8 was decoded lossily, no longer matched a file, and was skipped without a word; it is now an error that names it. A stray backtick in ATTRIBUTION.md can't shift the pairing of the rows below it. The docs say where attribution runs and that a bare name covers a root file. --- AGENTS.md | 4 ++-- docs/contributing.md | 2 +- xtask/src/attribution.rs | 31 +++++++++++++++++++++++++++---- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0a6ba174be..23bfe90ace 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,8 +169,8 @@ removes a limit against its base (a new memory scenario is fine). A maintainer a raise by commenting on the pull request with the line the failure prints for it, on a line of its own (``), then re-runs the job. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes -and those that depend on them (and `test-hygiene` on the whole workspace, `attribution` also when only -non-code files change, and formatting, `layers` and `rows` when packages are checked), or everything when a +and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers`, +`attribution` and `rows` when packages are checked; `attribution` also when only non-code files change), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it. A new dependency must have a licence `deny.toml` allows (CI runs `cargo deny check licenses`); after changing dependencies, run `cargo xtask notices` to refresh the `THIRD-PARTY-LICENSES.txt` files the diff --git a/docs/contributing.md b/docs/contributing.md index 1f8524a78a..facdaa1c45 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -108,7 +108,7 @@ Other workspace tasks: | --- | --- | | `cargo xtask changed [--list] [base]` | Run the `cargo xtask ci` checks on only the packages your branch changes and those that depend on them: a quicker check while you work. A file outside every package that no package includes, such as `Cargo.lock`, checks the whole workspace. `--list` prints the packages without checking them | | `cargo xtask layers` | Check crate dependency direction (target-specific dependencies included) and keep UI dependencies out of lower layers; a new crate under `crates/` needs a layer in `LAYERS` | -| `cargo xtask attribution` | Check that every image and font file has a row in `ATTRIBUTION.md` (its path, a directory above it or a pattern in backticks) | +| `cargo xtask attribution` | Check that every image and font file has a row in `ATTRIBUTION.md` (its path, a directory above it or a pattern in backticks; a bare name covers a file at the repository root) | | `cargo xtask notices` | Regenerate the shipped `THIRD-PARTY-LICENSES.txt` files after changing dependencies, or after adding code or data from another project to `INCLUDED` in `xtask/src/notices.rs` (with its licence text in `third-party/`); requires `cargo-about` | | `cargo xtask notices --check` | Check the notices without writing them; stale notices warn in CI but block releases | | `cargo xtask web-pwa ` | Generate the service worker in a Trunk build output directory, such as `dist/web` | diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs index 5771f094bd..5013563f02 100644 --- a/xtask/src/attribution.rs +++ b/xtask/src/attribution.rs @@ -32,10 +32,10 @@ fn wildcard(pattern: &str, text: &str) -> bool { /// path of a file may hold spaces) or is a single word with a `.` (a file at the root), each with /// a trailing `/` taken off and whether it had a `/` at all. fn named(attribution: &str) -> Vec<(&str, bool)> { + // Backticks pair up within a line, so a stray one can't shift the pairing of every later row. attribution - .split('`') - .skip(1) - .step_by(2) + .lines() + .flat_map(|line| line.split('`').skip(1).step_by(2)) .filter(|t| !t.contains(['\n', '\t']) && !t.starts_with('/')) .filter(|t| t.contains('/') || (t.contains('.') && !t.contains(' '))) .map(|t| (t.trim_end_matches('/'), t.contains('/'))) @@ -58,13 +58,23 @@ fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { .collect() } +/// The names in `git ls-files -z` output, or an error naming one that isn't valid UTF-8: the +/// output was decoded lossily, so such a file would otherwise look missing and be skipped. +fn names(listed: &str) -> Result, String> { + let names: Vec<&str> = listed.split('\0').filter(|f| !f.is_empty()).collect(); + match names.iter().find(|f| f.contains('\u{FFFD}')) { + Some(bad) => Err(format!("attribution: `{bad}` is not a valid UTF-8 file name, so it can't be checked: rename it")), + None => Ok(names), + } +} + /// Runs `cargo xtask attribution`: fails listing each image or font file that is tracked (or new /// and not ignored) without a row. pub fn run(root: &Path) -> Result<(), String> { let attribution = std::fs::read_to_string(root.join("ATTRIBUTION.md")).map_err(|e| format!("ATTRIBUTION.md: {e}"))?; let listed = super::changed::git(root, &["ls-files", "--cached", "--others", "--exclude-standard", "-z"])?; // A file removed from the working tree but not yet from the index doesn't need a row. - let files: Vec<&str> = listed.split('\0').filter(|f| !f.is_empty() && root.join(f).is_file()).collect(); + let files: Vec<&str> = names(&listed)?.into_iter().filter(|f| root.join(f).is_file()).collect(); let missing = uncovered(&files, &attribution); if missing.is_empty() { println!("attribution: ok"); @@ -130,6 +140,19 @@ mod tests { assert_eq!(uncovered(&files, TABLE), vec!["crates/map/testdata/generated-more/x.png", "iconsx/a.png"]); } + #[test] + fn a_file_name_that_is_not_utf8_is_an_error_not_a_skip() { + assert_eq!(names("a/b.png\0c.otf\0").unwrap(), vec!["a/b.png", "c.otf"]); + let lossy = String::from_utf8_lossy(b"a/ok.png\0a/bad\xff.png\0"); + assert!(names(&lossy).unwrap_err().contains("bad\u{FFFD}.png")); + } + + #[test] + fn a_stray_backtick_does_not_shift_later_rows() { + let table = "| Odd ` row | x |\n| Icon (`assets/logo.png`) | us |\n"; + assert_eq!(uncovered(&["assets/logo.png", "assets/other.png"], table), vec!["assets/other.png"]); + } + #[test] fn a_pattern_matches_the_whole_path() { assert!(wildcard("a/*.png", "a/b/c.png")); From 26dec6d725f2701388fe6c5d9becb8ecf268f2e0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 19:06:53 -0600 Subject: [PATCH 5/7] xtask: refuse a non-UTF-8 name only when it could be an asset, and accept root wildcards A file that isn't an image or font no longer fails the check for a name that isn't valid UTF-8. A row naming `logo*` covers the root's `logo.png` (and nothing below the root). --- xtask/src/attribution.rs | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs index 5013563f02..2664050a93 100644 --- a/xtask/src/attribution.rs +++ b/xtask/src/attribution.rs @@ -29,7 +29,7 @@ fn wildcard(pattern: &str, text: &str) -> bool { } /// The paths and patterns `ATTRIBUTION.md` names: everything in backticks that has a `/` in it (the -/// path of a file may hold spaces) or is a single word with a `.` (a file at the root), each with +/// path of a file may hold spaces) or is a single word with a `.` or `*` (a file at the root), each with /// a trailing `/` taken off and whether it had a `/` at all. fn named(attribution: &str) -> Vec<(&str, bool)> { // Backticks pair up within a line, so a stray one can't shift the pairing of every later row. @@ -37,7 +37,7 @@ fn named(attribution: &str) -> Vec<(&str, bool)> { .lines() .flat_map(|line| line.split('`').skip(1).step_by(2)) .filter(|t| !t.contains(['\n', '\t']) && !t.starts_with('/')) - .filter(|t| t.contains('/') || (t.contains('.') && !t.contains(' '))) + .filter(|t| t.contains('/') || ((t.contains('.') || t.contains('*')) && !t.contains(' '))) .map(|t| (t.trim_end_matches('/'), t.contains('/'))) .filter(|(t, _)| !t.is_empty()) .collect() @@ -49,7 +49,7 @@ fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { files .iter() .copied() - .filter(|f| f.rsplit_once('.').is_some_and(|(_, ext)| ASSET_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))) + .filter(|f| is_asset(f)) .filter(|f| { !named.iter().any(|(n, path)| { if *path { f == n || f.starts_with(&format!("{n}/")) || wildcard(n, f) } else { !f.contains('/') && wildcard(n, f) } @@ -58,11 +58,19 @@ fn uncovered<'a>(files: &[&'a str], attribution: &str) -> Vec<&'a str> { .collect() } -/// The names in `git ls-files -z` output, or an error naming one that isn't valid UTF-8: the -/// output was decoded lossily, so such a file would otherwise look missing and be skipped. +/// Whether the file's extension is one of an image or a font. +fn is_asset(file: &str) -> bool { + file.rsplit_once('.').is_some_and(|(_, ext)| ASSET_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())) +} + +/// The names in `git ls-files -z` output, or an error naming an image or font one that isn't valid +/// UTF-8: the output was decoded lossily, so such a file would otherwise look missing and be +/// skipped. (A name whose bad bytes are in its extension can't be told from an asset, so it counts.) fn names(listed: &str) -> Result, String> { let names: Vec<&str> = listed.split('\0').filter(|f| !f.is_empty()).collect(); - match names.iter().find(|f| f.contains('\u{FFFD}')) { + let unreadable = + |f: &str| f.contains('\u{FFFD}') && (is_asset(f) || f.rsplit_once('.').is_none_or(|(_, ext)| ext.contains('\u{FFFD}'))); + match names.iter().copied().find(|f| unreadable(f)) { Some(bad) => Err(format!("attribution: `{bad}` is not a valid UTF-8 file name, so it can't be checked: rename it")), None => Ok(names), } @@ -145,6 +153,15 @@ mod tests { assert_eq!(names("a/b.png\0c.otf\0").unwrap(), vec!["a/b.png", "c.otf"]); let lossy = String::from_utf8_lossy(b"a/ok.png\0a/bad\xff.png\0"); assert!(names(&lossy).unwrap_err().contains("bad\u{FFFD}.png")); + // A name that is no image or font is none of this check's business, however it is spelt. + assert_eq!(names(&String::from_utf8_lossy(b"src/bad\xff.rs\0")).unwrap().len(), 1); + assert!(names(&String::from_utf8_lossy(b"a/b.p\xffg\0")).is_err()); + } + + #[test] + fn a_root_pattern_without_a_dot_covers_only_root_files() { + let table = "| Logos (`logo*`) | us |\n"; + assert_eq!(uncovered(&["logo.png", "logo-dark.svg", "assets/logo.png"], table), vec!["assets/logo.png"]); } #[test] From 06d03a48fb6ec3f4c99df26dc463b0cbf691c038 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 19:53:02 -0600 Subject: [PATCH 6/7] xtask: a name with no extension is no asset in the non-UTF-8 refusal The extension is read from the file name alone, so `bin/bad\xff` and `a.d/bad\xff` pass. --- xtask/src/attribution.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/xtask/src/attribution.rs b/xtask/src/attribution.rs index 2664050a93..4ce54d8516 100644 --- a/xtask/src/attribution.rs +++ b/xtask/src/attribution.rs @@ -65,11 +65,13 @@ fn is_asset(file: &str) -> bool { /// The names in `git ls-files -z` output, or an error naming an image or font one that isn't valid /// UTF-8: the output was decoded lossily, so such a file would otherwise look missing and be -/// skipped. (A name whose bad bytes are in its extension can't be told from an asset, so it counts.) +/// skipped. (A name whose bad bytes are in its extension can't be told from an asset, so it counts; one with no extension is no asset.) fn names(listed: &str) -> Result, String> { let names: Vec<&str> = listed.split('\0').filter(|f| !f.is_empty()).collect(); - let unreadable = - |f: &str| f.contains('\u{FFFD}') && (is_asset(f) || f.rsplit_once('.').is_none_or(|(_, ext)| ext.contains('\u{FFFD}'))); + let unreadable = |f: &str| { + let file = f.rsplit('/').next().unwrap_or(f); + f.contains('\u{FFFD}') && (is_asset(f) || file.rsplit_once('.').is_some_and(|(_, ext)| ext.contains('\u{FFFD}'))) + }; match names.iter().copied().find(|f| unreadable(f)) { Some(bad) => Err(format!("attribution: `{bad}` is not a valid UTF-8 file name, so it can't be checked: rename it")), None => Ok(names), @@ -154,7 +156,9 @@ mod tests { let lossy = String::from_utf8_lossy(b"a/ok.png\0a/bad\xff.png\0"); assert!(names(&lossy).unwrap_err().contains("bad\u{FFFD}.png")); // A name that is no image or font is none of this check's business, however it is spelt. - assert_eq!(names(&String::from_utf8_lossy(b"src/bad\xff.rs\0")).unwrap().len(), 1); + for name in [&b"src/bad\xff.rs"[..], b"bin/bad\xff", b"a.d/bad\xff", b".github/bad\xff"] { + assert_eq!(names(&String::from_utf8_lossy(name)).unwrap().len(), 1, "{}", String::from_utf8_lossy(name)); + } assert!(names(&String::from_utf8_lossy(b"a/b.p\xffg\0")).is_err()); } From eba536fb49e87f3a6b5f0fd50534a9aec824857f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 20:53:25 -0600 Subject: [PATCH 7/7] xtask: list attribution in the usage line --- xtask/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 98f11d060e..9c5cd20862 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -290,7 +290,7 @@ fn main() -> ExitCode { Some(other) => Err(format!("unknown argument {other}: usage: cargo xtask schema [--check]")), }, "web-pwa" => web_pwa(std::env::args().nth(2)), - _ => Err("usage: cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | rows [--update] [--list] | commands | test-hygiene | notices [--check] | schema [--check] | web-pwa ".into()), + _ => Err("usage: cargo xtask ci | changed [--list] [base] | layers | attribution | memory [--cli ] [--update] | rows [--update] [--list] | commands | test-hygiene | notices [--check] | schema [--check] | web-pwa ".into()), }; match r { Ok(()) => ExitCode::SUCCESS,