Skip to content
Merged
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 (`<!-- ratchet-raise-approved: xtask/row-uses.txt count=790 -->`), then re-runs the job.
While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sentence now lists attribution among the checks that run "when packages are checked", but changed also runs it on the no-packages path (xtask/src/changed.rs, the Selection::NoPackages branch, added in this PR) and in the whole-workspace path through ci(). Someone reading this would expect a README-only change to skip it, which is no longer the case. Suggest: "and test-hygiene on the whole workspace; attribution also runs when only non-code files change; formatting, layers and rows run when packages are checked".

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f18c8b: the sentence says attribution also runs when only non-code files change, and formatting, layers and rows when packages are checked.

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
Expand Down
3 changes: 2 additions & 1 deletion docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir>` | Generate the service worker in a Trunk build output directory, such as `dist/web` |
Expand Down
187 changes: 187 additions & 0 deletions xtask/src/attribution.rs
Original file line number Diff line number Diff line change
@@ -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] =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extension list has no tif or tiff, so an unattributed TIFF image passes cargo xtask attribution silently. GeoTIFFs under testdata are data and can stay out, but TIFF is an image format and the check claims "images". The same goes for heic, psd, emf and wmf if they are meant to count. Either add them, or say in the doc comment that TIFF is left out on purpose, with a test that pins it.

Confidence: medium. The mechanism is clear from the list. Whether TIFF images are wanted here is a scope call.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass. TIFF is data in this repository (GeoTIFF rasters under testdata), and the list is the formats AGENTS.md names for icons, images and fonts; whether more raster or vector image formats belong in it is a scope call for the maintainers.

&["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) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A directory row written with a wildcard and a trailing /, such as `crates/*/testdata/`, doesn't cover the files below it. Here n is crates/*/testdata with the slash trimmed, so the starts_with arm looks for the literal * and wildcard(n, f) only matches a path that ends at testdata. The check then reports crates/x/testdata/a.png: no row in ATTRIBUTION.md even though the row names its directory, which the module doc and the thread on trailing slashes say it should cover. It fails loudly, so nothing is lost silently, but a correct row is rejected.

Suggested fix: add the directory-wildcard form to the path arm. A test with `crates/*/testdata/` covering crates/x/testdata/a/b.png would pin it.

Suggested change
if *path { f == n || f.starts_with(&format!("{n}/")) || wildcard(n, f) } else { !f.contains('/') && wildcard(n, f) }
if *path { f == n || f.starts_with(&format!("{n}/")) || wildcard(n, f) || wildcard(&format!("{n}/*"), f) } else { !f.contains('/') && wildcard(n, f) }

Confidence: high on the mechanism (traced through wildcard), low on how often a row is written this way today.

Category: bug

})
})
.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<Vec<&str>, String> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

names() refuses a non-UTF-8 name in any tracked file, not only the image and font files this check covers. A repository with one stray non-UTF-8 name in a source or data file would fail cargo xtask attribution and every changed run with "rename it", even though that file needs no row. Filtering to ASSET_EXTENSIONS before the UTF-8 check would keep the "never silent" guarantee for assets and stop the false failure for everything else. Confidence: medium that this matters in practice (the repo has none I can see), high on the mechanism.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 26dec6d: the UTF-8 refusal applies to a name that is an image or font, or whose extension is itself damaged (it can't be told from one). src/bad\xff.rs passes; a/b.p\xffg and bad\xff.png are errors. Tests cover each.

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::<Vec<_>>().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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A backticked name with no / is matched by file name alone across the whole repository, so one row that mentions icon.png covers every icon.png in every crate, and a row that mentions *.svg covers every SVG. That matches the rule as the PR documents it, but it means a new asset can pass the check just because a same-named file appears in another row. A row can be narrowed to its directory, which is what the table already does for the existing files. Consider requiring a / for a row to cover a file, or stating the basename rule as a deliberate weakness in the doc comment.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5cd221d: a bare file name covers nothing now; a row covers a file only by a path with a / (the file, a directory above it, or a pattern). A test covers a row naming b.png beside a same-named file elsewhere.

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"));
}
}
17 changes: 12 additions & 5 deletions xtask/src/changed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ pub(crate) fn compile_time_reads(root: &Path, packages: &[Package]) -> Result<BT
}

/// The output of `git args` in `root`.
fn git(root: &Path, args: &[&str]) -> Result<String, String> {
pub(crate) fn git(root: &Path, args: &[&str]) -> Result<String, String> {
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()));
Expand Down Expand Up @@ -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<Vec<Package>, String> {
/// The workspace's packages with their dependencies, as `cargo metadata` gives them.
pub(crate) fn metadata(root: &Path) -> Result<Value, String> {
let out = Command::new(env!("CARGO"))
.args(["metadata", "--format-version", "1", "--no-deps", "--locked"])
.current_dir(root)
Expand All @@ -276,7 +276,12 @@ fn packages(root: &Path) -> Result<Vec<Package>, 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<Vec<Package>, 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() {
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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
Expand Down
Loading
Loading