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
7 changes: 3 additions & 4 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,9 @@ A result is right, or RustGIS says what it lost or assumed
error-cell losses for XLSX; other loss kinds remain.
XLSM shares the XLSX parser; macros are untested.
Exports are checked by `never_silent_roundtrip.rs` _(open)_.
- Loss notices classified by code so scheduled jobs can detect them (the engine carries codes
through reader and tool results today; the remaining notices are to migrate). Then
`rustgis-cli run --strict`, which exits non-zero on a disallowed loss, and the codes exposed
to Python and MCP ([#2371](https://github.com/opengeos/RustGIS/issues/2371)).
- The remaining loss notices classified by code (the engine carries codes through reader and
tool results today), so `rustgis-cli run --strict` stops at them, and the codes exposed to
Python and MCP ([#2371](https://github.com/opengeos/RustGIS/issues/2371)).
- NTv2 grid shifts named in a file's own definition (a WKT or PROJ string that binds NAD27 to
WGS 84 through a `.gsb` grid), which are said but not applied today (the grids PROJ's
operations use are applied when present and downloaded on request). _Coordinate first_ (needs
Expand Down
136 changes: 120 additions & 16 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! --cmd 'gp.run={"tool":"buffer","params":{"input":"Cities","distance":100}}' \
//! --cmd 'share.exportMap={"path":"out.png"}' [--save out.rgis]
//! rustgis-cli run … --use-saved-secrets # use what the desktop app saved in the system keychain
//! rustgis-cli run … --strict [--allow dropped.ring] # exit 3 when a command loses data (see the guide's loss codes)
//! rustgis-cli run … --threads 4 # the most threads one piece of work uses (default: the cores, up to 16)
//! rustgis-cli ask [--sample | --project p.rgis | --data f.geojson …] "Which cities have over 10 million people?" \
//! [--provider anthropic|openai|chatgpt|gemini|openrouter|ollama|custom|requesty|trustedrouter|opper] [--model M] [--base-url URL] [--yes] [--save out.rgis] [--trace log.txt]
Expand Down Expand Up @@ -42,13 +43,14 @@ macro_rules! out {
}

use rustgis_assistant::{Config, provider};
use rustgis_engine::data::loss::{LossCode, LossKind};
use rustgis_engine::data::secrets::SecretStore;
use rustgis_engine::{Project, Session};
use serde_json::{Map, Value, json};

fn usage() -> ExitCode {
eprintln!(
"usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install <file|folder> | uninstall <id> | enable <id> | disable <id> | browse | get <id> | prepare <id>] [--registry URL]\n rustgis-cli skills [add <SKILL.md|folder|.zip> | remove <name> | enable <name> | disable <name>]\n rustgis-cli info <data>\n rustgis-cli logo <out.png|out.ico|out.bmp> [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render <data|project> <out.png> [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--image PICTURE]… [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]"
"usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install <file|folder> | uninstall <id> | enable <id> | disable <id> | browse | get <id> | prepare <id>] [--registry URL]\n rustgis-cli skills [add <SKILL.md|folder|.zip> | remove <name> | enable <name> | disable <name>]\n rustgis-cli info <data>\n rustgis-cli logo <out.png|out.ico|out.bmp> [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render <data|project> <out.png> [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--strict [--allow KIND|CODE]…] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--image PICTURE]… [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]"
);
ExitCode::from(2)
}
Expand Down Expand Up @@ -111,6 +113,99 @@ fn prepare_env(id: &str) -> Result<String, String> {
Ok(python.display().to_string())
}

/// The exit status of a run `--strict` stopped because a command lost data it doesn't allow.
const LOSS_EXIT: u8 = 3;

/// `run --strict`: the run stops after the first command that reports a loss of a kind or code
/// no `--allow` accepts, before the commands after it and the final save.
struct Strict {
allow: Vec<String>,
/// Whether a loss stopped the run, so it exits with [`LOSS_EXIT`].
stopped: std::cell::Cell<bool>,
}

impl Strict {
/// Reads `--strict` and each `--allow <kind or code>`: `None` without `--strict`.
fn from_args(cmd: &str, args: &[String]) -> Result<Option<Strict>, String> {
if args.iter().any(|a| a.starts_with("--strict=")) {
return Err("--strict takes no value; accept losses with --allow".into());
}
let strict = args.iter().any(|a| a == "--strict");
let mut allow = Vec::new();
// `--allow X`, or `--allow=X` as `--threads=N` is read.
for (i, a) in args.iter().enumerate() {
let v = match a.strip_prefix("--allow=") {
Some(v) => Some(v),
None if a == "--allow" => args.get(i + 1).map(String::as_str).filter(|v| !v.starts_with("--")),
None => continue,
};
let Some(v) = v.filter(|v| !v.is_empty()) else {
return Err("--allow needs a loss kind or code, such as dropped or dropped.ring".into());
};
if LossKind::from_id(v).is_none() && LossCode::from_id(v).is_none() {
let kinds: Vec<&str> = LossKind::ALL.iter().map(|k| k.id()).collect();
return Err(format!("--allow {v}: not a loss kind ({}) or code (listed in the command line guide)", kinds.join(", ")));
}
allow.push(v.to_string());
}
if (strict || !allow.is_empty()) && cmd != "run" {
return Err("--strict and --allow apply to run".into());
}
if !strict {
return if allow.is_empty() { Ok(None) } else { Err("--allow needs --strict".into()) };
}
Ok(Some(Strict { allow, stopped: std::cell::Cell::new(false) }))
}

/// Whether an `--allow` names this code or its kind (`dropped` allows `dropped.ring`).
fn allows(&self, code: LossCode) -> bool {
let spec = code.spec();
self.allow.iter().any(|a| a == spec.id || a == spec.kind.id())
}

/// Stops the run when `id` reported a loss this run doesn't allow: `before` is
/// [`Session::losses_given`] from before it ran, so no loss escapes however much it said.
fn check(&self, s: &Session, before: &[(LossCode, u64)], id: &str) -> Result<(), String> {
let lost: Vec<(LossCode, u64)> = s
.losses_given()
.iter()
.filter(|(code, _)| !self.allows(*code))
.filter_map(|&(code, n)| {
let was = before.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n);
(n > was).then_some((code, n - was))
})
.collect();
if lost.is_empty() {
return Ok(());
}
self.stopped.set(true);
let mut said = format!("--strict: stopped after {id}, which reported a loss no --allow accepts:");
for (code, n) in lost {
let spec = code.spec();
// A counted notice says how many it lost in its text; this counts the notices.
let notices = if n == 1 { "1 notice".to_string() } else { format!("{n} notices") };

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 stop report counts notices, not occurrences. A counted notice aggregates occurrences in its text, so one notice saying "2 omitted legends" prints as dropped.legend (1 notice). The doc's "how many notices reported it" is literally true, but a job reading the report would take it as a count of lost items. Consider wording such as "(1 notice; see its text for the count)", or counting occurrences if that is available here.

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 2f1241b: the guide now says the report counts notices and each notice says how much it lost. The CLI has a comment saying the same.

said.push_str(&format!("\n {} ({notices}): {}", spec.id, spec.action));
}
Err(said)
}
}

/// [`run`], then [`Strict::check`] when the run is strict: after a failure too, as a failed
/// command still reports the losses that outlive its rollback (a counted omission).
fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result<Value, String> {
let before = strict.map(|_| s.losses_given().to_vec());
let out = run(s, id, p);
if let (Some(strict), Some(before)) = (strict, before)
&& let Err(said) = strict.check(s, &before, id)
{
return Err(match out {
Err(e) => format!("{e}\n{said}"),
Ok(_) => said,
});
}
out
}

fn is_project(path: &str) -> bool {
rustgis_engine::project::opens_as_project(path)
}
Expand All @@ -119,28 +214,29 @@ fn num(args: &[String], name: &str) -> Option<f64> {
opt(args, name).and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite())
}

fn load(s: &mut Session, path: &str) -> Result<(), String> {
/// Opens a project, or adds any other file as a layer; `strict` only from `run`.
fn load(s: &mut Session, strict: Option<&Strict>, path: &str) -> Result<(), String> {
if is_project(path) {
run(s, "project.open", json!({"path": path}))?;
run_strict(s, strict, "project.open", json!({"path": path}))?;
} else {
run(s, "layer.addData", json!({"path": path}))?;
run_strict(s, strict, "layer.addData", json!({"path": path}))?;
}
Ok(())
}

/// Opens `--sample`, `--project` and every `--data`.
fn open_inputs(s: &mut Session, args: &[String]) -> Result<(), String> {
fn open_inputs(s: &mut Session, strict: Option<&Strict>, args: &[String]) -> Result<(), String> {
if args.iter().any(|a| a == "--sample") {
run(s, "project.sample", Value::Null)?;
run_strict(s, strict, "project.sample", Value::Null)?;
}
if let Some(p) = opt(args, "--project") {
load(s, p)?;
load(s, strict, p)?;
}
for (i, a) in args.iter().enumerate() {
if a == "--data"
&& let Some(p) = args.get(i + 1)
{
load(s, p)?;
load(s, strict, p)?;
}
}
Ok(())
Expand Down Expand Up @@ -743,6 +839,13 @@ fn cli() -> ExitCode {
}
let args: Vec<String> = std::env::args().skip(1).collect();
let Some(cmd) = args.first().map(|s| s.as_str()) else { return usage() };
let strict = match Strict::from_args(cmd, &args) {
Ok(strict) => strict,
Err(e) => {
eprintln!("rustgis-cli: {e}");
return ExitCode::from(2);
}
};
if !args.iter().any(|a| a == "--no-plugins") {
for e in rustgis_engine::cmd::plugins::load_installed() {
eprintln!("rustgis-cli: warning: {e}");
Expand Down Expand Up @@ -870,7 +973,7 @@ fn cli() -> ExitCode {
}
"info" => {
let path = args.get(1).ok_or("info needs a file")?;
load(&mut s, path)?;
load(&mut s, None, path)?;
print(&run(&mut s, "info.project", Value::Null)?);
Ok(())
}
Expand Down Expand Up @@ -917,7 +1020,7 @@ fn cli() -> ExitCode {
}
"render" => {
let (Some(input), Some(out)) = (args.get(1), args.get(2)) else { return Err("render needs <input> <out.png>".into()) };
load(&mut s, input)?;
load(&mut s, None, input)?;
if let Some(b) = opt(&args, "--basemap") {
run(&mut s, "map.basemap", json!({"name": b}))?;
}
Expand All @@ -936,7 +1039,7 @@ fn cli() -> ExitCode {
Ok(())
}
"ask" => {
open_inputs(&mut s, &args)?;
open_inputs(&mut s, None, &args)?;
// What the assistant did is saved even when it couldn't finish.
let asked = ask(&mut s, &args, saved.as_ref(), &Environment::process());
if let Some(p) = opt(&args, "--save")
Expand All @@ -948,7 +1051,7 @@ fn cli() -> ExitCode {
}
"mcp" => {
if !args.iter().any(|a| a == "--attach") {
open_inputs(&mut s, &args)?;
open_inputs(&mut s, None, &args)?;
}
mcp(&mut s, &args)
}
Expand All @@ -959,7 +1062,8 @@ fn cli() -> ExitCode {
// calling it may have a timeout, and keeps the caps.
s.long_runs = Some(progress);
s.stoppable = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
open_inputs(&mut s, &args)?;
let strict = strict.as_ref();
open_inputs(&mut s, strict, &args)?;
for (i, a) in args.iter().enumerate() {
if a == "--cmd"
&& let Some(c) = args.get(i + 1)
Expand All @@ -968,14 +1072,14 @@ fn cli() -> ExitCode {
Some((id, json)) => (id, serde_json::from_str(json).map_err(|e| format!("{id}: bad JSON: {e}"))?),
None => (c.as_str(), Value::Null),
};
let out = run(&mut s, id, p)?;
let out = run_strict(&mut s, strict, id, p)?;

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.

When a strict stop fires, run_strict returns Err and the ? skips print(&out) for the command that stopped the run. Its result never reaches stdout, even though its effect already happened. For example, share.exportMap can write the PNG and the path is never printed. The stop message names the code but not that result. Suggest printing the stopping command's output before returning the stop error, so a job can still find what the command wrote.

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.

Printing the stopping command's result before the stop report would help a job find what it wrote. Left for the release quality pass.

if !out.is_null() {
print(&out);
}
}
}
if let Some(p) = opt(&args, "--save") {
run(&mut s, "project.saveAs", json!({"path": p}))?;
run_strict(&mut s, strict, "project.saveAs", json!({"path": p}))?;
}
Ok(())
}
Expand All @@ -985,7 +1089,7 @@ fn cli() -> ExitCode {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("rustgis-cli: {e}");
ExitCode::FAILURE
if strict.is_some_and(|strict| strict.stopped.get()) { ExitCode::from(LOSS_EXIT) } else { ExitCode::FAILURE }
}
}
}
Expand Down
1 change: 1 addition & 0 deletions apps/rustgis-cli/tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
mod memory_override;
mod reproducible_exports;
mod saved_secrets;
mod strict;
mod threads;
Loading
Loading