Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ whose two sides are the same tokens; prefer completion or progress signals, and
(`wgs84_distance_m`, `wgs84_length_m`, `wgs84_step_m`, `wgs84_ring_perimeter_area_m2`), and a call kept on
the sphere, for another body or a comparison it can't change, says why in its
`#[expect(clippy::disallowed_methods, reason = "…")]`.
The engine test `command_surface_matches_the_snapshot` fails on any difference between the registered
commands and `crates/engine/command-surface.txt` (each command id with its parameter keys and optional
marks, not the help text): a pull request that adds, removes or renames a command or a parameter runs
`cargo xtask commands` and commits the file. A removal or rename is a coordinate-first change.
`cargo xtask memory` (in CI on Linux) fails when a command line workflow's peak memory grows past
its limit in `xtask/memory-limits.txt`; a change that lowers one commits the lower limit with it.
`cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly
Expand Down
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ something on the roadmap (or not on it) interests you, propose it and open a pul
- changes the data model (`Feature`, `Coord`, `Renderer`);
- adds a dependency or a crate;
- changes the `.rgis` project format, or an existing command's id or parameters (the CLI,
Python, MCP and saved scripts call commands by id);
Python, MCP and saved scripts call commands by id; `crates/engine/command-surface.txt` lists
them, and a test fails until a pull request that changes one commits the new file);
- changes the plugin interface;
- falls under _Exploratory_ in the roadmap.

Expand Down
2 changes: 0 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ features build on.
already are refused, [#1364](https://github.com/opengeos/RustGIS/pull/1364)); packages
(`.rgispkg`) that hold everything or say what stayed linked; projects written to disk as they
save, not built in memory first.
- A snapshot test of command ids and parameters, so a removal is always deliberate (the project
file's JSON Schema, its fixtures and the files past releases saved are checked today).
- A compressed encoding of today's project JSON, read one release before it is written.
_Coordinate first_: an issue is needed.
- A system for the data a project refers to: named connections, copies that remember their
Expand Down
603 changes: 603 additions & 0 deletions crates/engine/command-surface.txt

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions crates/engine/examples/command_surface.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! Writes the command surface snapshot (`rustgis_engine::surface::PATH`) from the registry.
//! Run through `cargo xtask commands`.

use std::path::Path;
use std::process::ExitCode;

use rustgis_engine::{cmd, surface};

/// Rewrites the snapshot file; fails when it can't be written.
fn main() -> ExitCode {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").join(surface::PATH);
let commands = cmd::all();
match std::fs::write(&path, surface::text(&commands)) {
Ok(()) => {
println!("wrote {} ({} commands)", surface::PATH, commands.len());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{}: {e}", surface::PATH);
ExitCode::FAILURE
}
}
}
1 change: 1 addition & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub mod schema;
pub mod service_logins;
pub mod service_tokens;
pub mod sources;
pub mod surface;
#[cfg(test)]
mod tests;
mod undo_memory;
Expand Down
134 changes: 134 additions & 0 deletions crates/engine/src/surface.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//! The command surface: every registered command id with the parameters it names, kept in
//! [`PATH`] so a removed or renamed command or parameter is a deliberate change in a pull request.
//! The command line, Python, the Assistant and MCP, saved scripts and plugins call commands by id
//! and by parameter key, and a change there breaks them without a compile error.
//!
//! The registry is checked against the file by `command_surface_matches_the_snapshot` (an engine
//! test, so it runs in `cargo xtask ci`); `cargo xtask commands` rewrites the file.

use crate::{CommandSpec, Quotes, param_entries};

/// Where the snapshot is kept, from the repository's root.
pub const PATH: &str = "crates/engine/command-surface.txt";

/// The snapshot of `commands`: one line per command, sorted by id, `id key key? …`. A key ends in
/// `?` when it may be left out. The declared types are left out: they are prose (`power?: 2`,
/// `"name": the layer's name`), so rewording a description would change the file. Neither is the
/// help text. A command that takes no parameters, or describes them without keys, is its id alone.
pub fn text(commands: &[CommandSpec]) -> String {
let mut lines: Vec<String> = commands.iter().map(line).collect();
lines.sort();
let mut out = lines.join("\n");
out.push('\n');
out
}

/// One command's line of the snapshot: every key the parameter object names, as `param_keys`
/// reads them, so `"lon" | "x": degrees` records both.
fn line(c: &CommandSpec) -> String {
let mut line = c.id.to_string();
param_entries(inputs(c.params), |key, optional| {
line.push(' ');
line.push_str(key);
if optional {
line.push('?');
}
});
line
}

/// The parameter object at the start of a description, up to its closing brace: the result that
/// some descriptions give after it (`{"layer"?: name} → {"kind": …}`) is not parameters. A
/// description that isn't an object is returned as it is.
fn inputs(desc: &str) -> &str {
if !desc.trim_start().starts_with('{') {
return desc;
}
let (mut depth, mut quotes) = (0usize, Quotes::default());
for (at, c) in desc.char_indices() {
if !quotes.read(c) {
continue;
}
match c {
'{' => depth += 1,
'}' => {
depth = depth.saturating_sub(1);
if depth == 0 {
return desc.get(..=at).unwrap_or(desc);
}
}
_ => {}
}
}
desc
}

/// The differences between two snapshots, one message per command that was removed, added or
/// whose parameters changed (empty when they agree).
pub fn differences(saved: &str, current: &str) -> Vec<String> {
let id = |line: &str| line.split(' ').next().unwrap_or("").to_string();
let by_id = |text: &str| text.lines().map(|l| (id(l), l.to_string())).collect::<std::collections::BTreeMap<_, _>>();
let (saved, current) = (by_id(saved), by_id(current));
let mut out = Vec::new();
for (id, line) in &saved {
match current.get(id) {
None => out.push(format!("removed: {line}")),
Some(now) if now != line => out.push(format!("changed: was `{line}`, now `{now}`")),
Some(_) => {}
}
}
out.extend(current.iter().filter(|(id, _)| !saved.contains_key(*id)).map(|(_, line)| format!("added: {line}")));
out
}

#[cfg(test)]
mod tests {
use super::*;

/// A removed, renamed or reshaped command or parameter fails here, so it is a decision in the
/// pull request that makes it: the command line, Python, MCP, saved scripts and plugins call
/// commands by id and key. An added command fails too, so the file never goes stale.
#[test]
fn command_surface_matches_the_snapshot() {
let commands = crate::cmd::all();
let mut seen = std::collections::HashSet::new();
let twice: Vec<_> = commands.iter().filter(|c| !seen.insert(c.id)).map(|c| c.id).collect();
assert!(twice.is_empty(), "registered twice: {twice:?}");
let (saved, current) = (include_str!("../command-surface.txt"), text(&commands));

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 snapshot test compares raw bytes, so a Windows checkout with core.autocrlf fails it. include_str! yields the file as checked out. Nothing at the root pins crates/engine/command-surface.txt to LF, so with CRLF line endings saved == current is false on every push to main, which runs every platform. differences uses str::lines, which strips the \r, so the failure says "a repeated id or another order" when the real cause is line endings. The repo already handles this elsewhere: crates/analysis/src/tools.rs normalises \r\n on read, and crates/engine/testdata/releases/.gitattributes pins -text.

Confidence is medium: I'm relying on the usual Git for Windows default of core.autocrlf=true on the runner, not on checking its config. Either fix works. Normalising here keeps it self-contained:

Suggested change
let (saved, current) = (include_str!("../command-surface.txt"), text(&commands));
let (saved, current) = (include_str!("../command-surface.txt").replace("\r\n", "\n"), text(&commands));

Alternatively, add crates/engine/.gitattributes with command-surface.txt text eol=lf.

Category: bug

let diff = differences(saved, &current);
// Equal ids and keys but another text: a repeated id, or lines out of order.
assert!(
saved == current,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"the registered commands differ from {PATH}:\n{}\nIf that is intended, run `cargo xtask commands` and commit the file (a removal or \
rename breaks scripts, the command line and plugins that call it)",
if diff.is_empty() { "the same ids and keys, but a repeated id or another order".to_string() } else { diff.join("\n") }
);
}

/// A key written as an alternative (`"lon" | "x": degrees`) is in the snapshot like any other,
/// and the result a description gives after its parameters is not.
#[test]
fn the_snapshot_lists_the_parameters_only() {
let line_of = |params: &'static str| line(&crate::CommandSpec::new("a.go", "Go", "", |_, _| Ok(Default::default())).params(params));
assert_eq!(line_of(r#"{"lon" | "x": degrees, "n"?: number}"#), "a.go lon x n?");
assert_eq!(line_of(r#"{"a"?: "x {y}" (a note)} → {"b": y, "c": {"d"}}"#), "a.go a?");
assert_eq!(line_of("a GeoJSON text"), "a.go");
}

/// The differences name what moved: a command gone, a key gone, a key made required and a command new.
#[test]
fn differences_name_each_change() {
let saved = "a.gone x\na.keep x y?\na.keys x y\na.required x y?\n";
let now = "a.keep x y?\na.keys x\na.new\na.required x y\n";
assert_eq!(
differences(saved, now),
[
"removed: a.gone x",
"changed: was `a.keys x y`, now `a.keys x`",
"changed: was `a.required x y?`, now `a.required x y`",
"added: a.new"
]
);
assert!(differences(saved, saved).is_empty());
}
}
15 changes: 13 additions & 2 deletions xtask/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
//! `cargo xtask ci | changed [--list] [base] | layers | memory [--cli <path>] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa <dir>`
//! `cargo xtask ci | changed [--list] [base] | layers | memory [--cli <path>] [--update] | rows [--update] [--list] | commands | test-hygiene | notices [--check] | schema [--check] | web-pwa <dir>`
//!
//! - `layers`: enforces the crate layering (nothing below L6 may depend on egui/eframe/rfd).
//! - `memory [--cli <path>] [--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`).
//! - `rows [--update] [--list]`: direct uses of a layer's rows outside `rustgis-data`, which
//! may not rise above the count in `xtask/row-uses.txt` (see `rows.rs`).
//! - `commands`: writes the snapshot of command ids and parameters
//! (`crates/engine/command-surface.txt`) from the registry; an engine test fails when the
//! committed file and the registry disagree.
//! - `test-hygiene`: timer waits in tests need same-line reasons; ignored tests need reasons.
//! - `ci`: test hygiene, fmt, clippy -D warnings, tests, layering, direct row uses and the
//! project schema check.
Expand Down Expand Up @@ -202,13 +205,21 @@ fn schema(check: bool) -> Result<(), String> {
cargo(&args)
}

/// Writes the command surface snapshot from the registry (`crates/engine/command-surface.txt`).
/// The engine's `command_surface_matches_the_snapshot` test, which `cargo xtask ci` runs, is the
/// check.
fn commands() -> Result<(), String> {
cargo(&["run", "-q", "--locked", "-p", "rustgis-engine", "--example", "command_surface"])
}

fn main() -> ExitCode {
let task = std::env::args().nth(1).unwrap_or_default();
let r = match task.as_str() {
"layers" => layers(),
"test-hygiene" => test_hygiene::run(&root()),
"rows" => rows::run(&root(), &std::env::args().skip(2).collect::<Vec<_>>()),
"memory" => memory::run(&root(), &std::env::args().skip(2).collect::<Vec<_>>()),
"commands" => commands(),
"ci" => ci(),
"changed" => changed::run(&root(), &std::env::args().skip(2).collect::<Vec<_>>()),
"notices" => {
Expand All @@ -234,7 +245,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 <path>] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa <dir>".into()),
_ => Err("usage: cargo xtask ci | changed [--list] [base] | layers | memory [--cli <path>] [--update] | rows [--update] [--list] | commands | test-hygiene | notices [--check] | schema [--check] | web-pwa <dir>".into()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Expand Down
Loading