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 7ed9fad394..565d01a1b0 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
@@ -175,8 +178,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; `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 ae0419958a..facdaa1c45 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; 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
new file mode 100644
index 0000000000..4ce54d8516
--- /dev/null
+++ b/xtask/src/attribution.rs
@@ -0,0 +1,187 @@
+//! `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`
+//! (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 (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;
+
+/// The extensions of image, icon and font files.
+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 {
+ 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)
+}
+
+/// 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 `.` 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.
+ attribution
+ .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('*')) && !t.contains(' ')))
+ .map(|t| (t.trim_end_matches('/'), t.contains('/')))
+ .filter(|(t, _)| !t.is_empty())
+ .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| 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) }
+ })
+ })
+ .collect()
+}
+
+/// 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; 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| {
+ 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),
+ }
+}
+
+/// 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> = names(&listed)?.into_iter().filter(|f| 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\
+ | 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\
+ | Root logo (`logo.svg`) | 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",
+ ];
+ 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 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]
+ 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",
+ "iconsx/a.png",
+ ];
+ 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"));
+ // A name that is no image or font is none of this check's business, however it is spelt.
+ 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());
+ }
+
+ #[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]
+ 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"));
+ 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..1816876ce9 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() {
@@ -332,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");
@@ -367,6 +373,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 c0dd063eee..9c5cd20862 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] | commands | test-hygiene | notices [--check] | schema [--check] | web-pwa `
+//! `cargo xtask ci | changed [--list] [base] | layers | attribution | memory [--cli ] [--update] | rows [--update] [--list] | commands | 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`).
@@ -21,12 +23,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)] = &[
@@ -50,14 +54,58 @@ 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: 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();
+ 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());
+ // 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()
+ .flatten()
+ .filter(|d| d["kind"].is_null())
+ .filter_map(|d| d["name"].as_str().map(str::to_string))
+ .collect();
+ out.push((dir.replace('\\', "/"), 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-")
@@ -68,12 +116,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> {
@@ -82,14 +125,15 @@ 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
-/// 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"])
.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))
}
@@ -216,6 +260,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::>()),
@@ -245,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,
@@ -313,4 +358,81 @@ 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_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(&[]);
+ 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());
+ }
}