Skip to content
36 changes: 35 additions & 1 deletion apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! ```text
//! rustgis-cli commands # list command ids and parameters
//! rustgis-cli tools # list geoprocessing tools
//! rustgis-cli explain changed.rounded # what a loss code means and what to do, offline
//! rustgis-cli info data.geojson # layer summary as JSON
//! rustgis-cli render data.geojson out.png [--basemap ocean] [--tiles URL] [--width 1600 --height 900]
//! rustgis-cli run [--sample | --project p.rgis | --data f.geojson …] \
Expand Down Expand Up @@ -50,11 +51,27 @@ 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] [--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]"
"usage:\n rustgis-cli commands | tools\n rustgis-cli explain [CODE]\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)
}

/// `explain [CODE]`: what a loss code means and what to do about it, from the text built into
/// RustGIS, so it reads offline, as a compiler explains its error codes; with no code, every code.
fn explain(code: Option<&str>) -> Result<(), String> {
let Some(id) = code else {
for code in LossCode::ALL {
let spec = code.spec();
out!("{:<28} {}", spec.id, spec.meaning);
}
return Ok(());
};
let code = LossCode::from_id(id).ok_or_else(|| format!("explain {id}: not a loss code (`rustgis-cli explain` lists them)"))?;
let spec = code.spec();
out!("{}: {}\n\n{}\n\nWhat to do: {}\n\nMore: {}", spec.id, spec.kind.id(), spec.meaning, spec.action, code.doc_url());
Ok(())
}

/// The value after `name`. A flag that takes one is in [`VALUE_FLAGS`], which [`check_values`]
/// checks before anything runs, so the value is there and isn't another option.
fn opt<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
Expand Down Expand Up @@ -1048,6 +1065,23 @@ fn cli() -> ExitCode {
print(&out);
Ok(())
}
"explain" => {
// The common options (`--threads 2`, `--use-saved-secrets`) are taken, and their values.
let mut words = Vec::new();
let mut rest = args.iter().skip(1);
while let Some(arg) = rest.next() {
if VALUE_FLAGS.contains(&arg.as_str()) {
rest.next();
} else if !arg.starts_with("--") {
words.push(arg.as_str());
}
}
match words.as_slice() {
[] => explain(None),
[code] => explain(Some(code)),
_ => Err("explain takes one loss code, or none to list them all".into()),
}
}
"skills" => skills(&args),
"mcp-register" => mcp_register(&args),
"commands" => {
Expand Down
19 changes: 19 additions & 0 deletions apps/rustgis-cli/tests/integration/strict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,22 @@ fn allow_takes_a_known_kind_or_code_and_needs_strict() {
assert!(err.contains(said), "{args:?}: {err}");
}
}

#[test]
fn explain_says_what_a_code_means_and_what_to_do_offline() {
let explain = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_rustgis-cli")).arg("explain").args(args).output().unwrap();
let out = explain(&["dropped.ring"]);
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{text}");
assert!(text.starts_with("dropped.ring: dropped\n\nA polygon ring was left out."), "{text}");
assert!(text.contains("What to do: Correct the unreadable polygon ring"), "{text}");
assert!(text.contains("More: https://rustgis.app/user-guide/loss-codes/#dropped.ring"), "{text}");
// Every code, one line each, starting with the code.
let all = String::from_utf8_lossy(&explain(&[]).stdout).into_owned();
for code in ["dropped.legend", "changed.rounded", "assumed.encoding"] {
assert!(all.lines().any(|line| line.starts_with(code)), "{all}");
}
let unknown = explain(&["dropped.everything"]);
assert!(!unknown.status.success());
assert!(String::from_utf8_lossy(&unknown.stderr).contains("not a loss code"));
}
64 changes: 59 additions & 5 deletions crates/data/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,13 @@ pub enum Filter {
Warnings,
Info,
Network,
/// Messages that report lost data, with a loss code.
Losses,
}

impl Filter {
/// Whether the pane's filter shows `record`: by severity, as a network failure, or as a message
/// that reports lost data (one with a loss code).
pub fn matches(self, record: &Record) -> bool {
match self {
Self::All => true,
Expand All @@ -56,6 +60,7 @@ impl Filter {
Self::Info => record.severity == Severity::Info,
// The note that further servers' absences go unlisted belongs with the absences.
Self::Network => record.network.is_some() || record.source == "Network",
Self::Losses => record.loss.is_some(),
}
}
}
Expand Down Expand Up @@ -98,8 +103,29 @@ pub struct Record {
pub message: String,
pub details: String,
pub network: Option<Network>,
/// The loss the message reports, if any: the pane links to its entry in the guide.
/// The loss the message reports, if any: the pane explains it and links to its entry in the guide.
pub loss: Option<crate::loss::LossCode>,
/// The command run that said it, when a command did.
pub run: Option<Run>,
}

/// One run of a command, as the messages it said remember it: the pane groups them by it and can
/// take the project back to before it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
/// Counts the session's runs, so the messages of one run are told from the next one's.
pub id: u64,
/// The top-level command that started the run: a message a nested step said is still the run's.
pub command: String,
/// The project's state before the run (`Session::state` in the engine).
pub before: u64,
/// The state the run left the project in, once it has finished: another than `before` when it
/// changed the project. A change makes a state no other change has, so the history finds the
/// run's own step by it, even after an Undo and another edit from the same state before.
pub after: Option<u64>,
/// What the run worked on, as its parameters name it (a layer, a table, an input or a map;
/// never a file path), redacted as a message is.
pub target: Option<String>,
}

#[derive(Default)]
Expand Down Expand Up @@ -207,13 +233,21 @@ impl History {
details: bounded(details, MAX_DETAILS_BYTES),
network: None,
loss: None,
run: None,
});
}

/// [`History::push`] for a message already through [`redact`] (a notice the session redacted
/// for its status bar): it is only bounded, so a notice isn't redacted again for each copy.
/// Only a [`Redacted`], which `redact` alone makes, gets this path.
pub fn push_redacted(&self, severity: Severity, source: &str, message: &Redacted, loss: Option<crate::loss::LossCode>) {
pub fn push_redacted(
&self,
severity: Severity,
source: &str,
message: &Redacted,
loss: Option<crate::loss::LossCode>,
run: Option<Run>,
) {
self.retain(Record {
id: 0,
timestamp_ms: timestamp_ms(),
Expand All @@ -223,13 +257,29 @@ impl History {
details: String::new(),
network: None,
loss,
run,
});
}

fn retain(&self, record: Record) {
store(&mut lock(&self.0), record);
}

/// Records the state the run `id` left the project in ([`Run::after`]) on the messages it said,
/// which are the newest ones with a run.
pub fn finish_run(&self, id: u64, after: u64) {
let mut state = lock(&self.0);
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
// A changed record: a snapshot taken before it shows the run as unfinished.
state.generation = state.generation.wrapping_add(1);
for record in state.records.iter_mut().rev() {
match &mut record.run {
Some(run) if run.id == id => run.after = Some(after),
Some(_) => break,
None => {}
}
}
}

/// Oldest first; both the count and every string in this independent snapshot are bounded.
pub fn records(&self) -> Vec<Record> {
lock(&self.0).records.iter().cloned().collect()
Expand Down Expand Up @@ -326,6 +376,7 @@ impl Capture {
details: String::new(),
network: None,
loss: None,
run: None,
},
);
guard.absences_overflow_said = Some(id);
Expand All @@ -344,6 +395,7 @@ impl Capture {
details: String::new(),
network: Some(Network { url, method: known_method(method), status: Some(status), duration_ms: None, kind: NetworkKind::Http }),
loss: None,
run: None,
};
let id = store(&mut guard, record);
guard.absences_said.push((server, id));
Expand Down Expand Up @@ -384,6 +436,7 @@ impl Capture {
details: bounded(details, MAX_DETAILS_BYTES),
network: Some(network),
loss: None,
run: None,
};
let mut state = lock(&state);
if once
Expand Down Expand Up @@ -1828,7 +1881,7 @@ mod tests {
fn text_already_redacted_is_only_bounded() {
let history = History::default();
let long = "word ".repeat(1000);
history.push_redacted(Severity::Info, "Application", &Redacted::new(&long), None);
history.push_redacted(Severity::Info, "Application", &Redacted::new(&long), None, None);
history.push(Severity::Info, "Application", &long, "");
let records = history.records();
assert_eq!(records[0].message, records[1].message);
Expand All @@ -1841,13 +1894,14 @@ mod tests {
fn a_loss_keeps_its_code_and_the_report_gives_its_guide_entry() {
let history = History::default();
let code = crate::loss::LossCode::DroppedRing;
history.push_redacted(Severity::Warning, "layer.addData", &Redacted::new("1 ring left out"), Some(code));
history.push_redacted(Severity::Info, "layer.addData", &Redacted::new("added"), None);
history.push_redacted(Severity::Warning, "layer.addData", &Redacted::new("1 ring left out"), Some(code), None);
history.push_redacted(Severity::Info, "layer.addData", &Redacted::new("added"), None, None);
let records = history.records();
assert_eq!(records.iter().map(|r| r.loss).collect::<Vec<_>>(), [Some(code), None]);
let report = history.report(Filter::All);
assert!(report.contains("Loss: dropped.ring (https://rustgis.app/user-guide/loss-codes/#dropped.ring)"), "{report}");
assert_eq!(report.matches("Loss: ").count(), 1, "{report}");
assert_eq!(records.iter().filter(|r| Filter::Losses.matches(r)).count(), 1);
}

#[test]
Expand Down
Loading
Loading