Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 7 additions & 9 deletions crates/assistant/src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,20 +238,16 @@ fn redact_script(script: &str) -> String {
.take(rustgis_engine::cmd::workflows::MAX_SCRIPT_LINES)
.map(|line| {
let line = line.trim();
// Display only: a malformed identifier may carry JSON glued after `=`. It must
// not be copied as an id; execution still uses the shared parser unchanged.
let head = line.split(|c: char| c.is_whitespace() || c == '=').next().unwrap_or(line);
let glued = line
.get(head.len()..)
.and_then(|r| r.strip_prefix('='))
.is_some_and(|r| !r.is_empty() && !r.starts_with(char::is_whitespace));
match rustgis_engine::script_line(line) {
None => redact_string(line),
Some(Ok((id, params))) if !glued => {
Some(Ok((id, params))) => {
let id = rustgis_engine::log_identifier(&id);
if params.is_null() { id } else { format!("{id} {}", rustgis_engine::log_params(&params).into_log_value()) }
}
Some(_) => format!("{} [parameters not JSON; withheld]", rustgis_engine::log_identifier(head)),
// The id as Run reads it, never the JSON after it (`split_script_id`).
Some(Err(_)) => {
format!("{} [parameters not JSON; withheld]", rustgis_engine::log_identifier(rustgis_engine::split_script_id(line).0))
}
}
})
.collect::<Vec<_>>()
Expand Down Expand Up @@ -362,6 +358,8 @@ mod tests {
let script = "map.zoomIn= {}\nlayer.addUrl {broken RGSYNTH_bad_20261103\nmap.zoomOut {}";
let logged = redact_script(script);
assert!(logged.starts_with("map.zoomIn {}\nlayer.addUrl [parameters not JSON; withheld]\nmap.zoomOut {}"));
// A line written `id={json}` runs, so it's logged as one that does (#2794).
assert_eq!(redact_script("map.zoomIn={}"), "map.zoomIn {}");
assert!(!logged.contains("RGSYNTH_"));
let comments = "# clean comment\n# https://h.invalid/a?token=RGSYNTH_comment_20261106";
let args = normalized_args("run", &json!({"script": comments}));
Expand Down
5 changes: 3 additions & 2 deletions crates/engine/src/cmd/notebook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,11 @@ fn untrusted_line(s: &Session, script: &str) -> Option<usize> {
if line.is_empty() || line.starts_with('#') {
return None;
}
let (id, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
// The id as `run_script` reads it (`id {json}`, `id= {json}` or `id={json}`).
let (id, rest) = crate::split_script_id(line);
// Malformed params read as none here; `run_script` rejects that line before it runs.
let params: Value = serde_json::from_str(rest.trim()).unwrap_or(Value::Null);
super::items::touches_files(s, id.trim_end_matches('='), &params).then_some(n + 1)
super::items::touches_files(s, id, &params).then_some(n + 1)
})
}

Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub use peer::Peer;
pub(crate) use roles::{Document, ParamRole, Role};
mod parameters;
pub mod project_log;
pub use parameters::{params_envelope, script_line};
pub use parameters::{params_envelope, script_line, split_script_id};
pub use project_log::{LogCopy, log_identifier, log_params};
pub mod s3_connections;
pub mod s3_keys;
Expand Down
31 changes: 29 additions & 2 deletions crates/engine/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ pub fn params_envelope(params: Option<&Value>) -> Result<Value, String> {
}
}

/// A script line's command id and the text after it: the id ends at the first space or `=`,
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
/// which no command id holds, so `id {json}`, `id= {json}` and `id={json}` (the command line's
/// form) all name `id` (#2794). The rest starts after that space or `=`. The Script pane colours
/// and completes a line by the same rule.
pub fn split_script_id(line: &str) -> (&str, &str) {
match line.char_indices().find(|&(_, c)| c.is_whitespace() || c == '=') {
Some((i, c)) => (&line[..i], &line[i + c.len_utf8()..]),
None => (line, ""),
}
}

/// One executable script line, preserving the executor's `id[=] {json}` grammar. Unlike an
/// adapter envelope, a script's JSON value is passed as written; no parameters means null.
/// Blank and comment lines have no command. Errors are annotated with line numbers by callers.
Expand All @@ -27,8 +38,7 @@ pub fn script_line(line: &str) -> Option<Result<(String, Value), String>> {
if line.is_empty() || line.starts_with('#') {
return None;
}
let (id, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let id = id.trim_end_matches('=');
let (id, rest) = split_script_id(line);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
let params = if rest.trim().is_empty() {
Value::Null
} else {
Expand Down Expand Up @@ -66,6 +76,23 @@ mod tests {
assert!(script_line("script.run {}").unwrap().is_err());
}

/// A command id ends at its first space or `=`, so `id={json}`, the command line's form and
/// the one the user guide writes, runs as `id {json}` does (#2794).
#[test]
fn a_command_id_ends_at_a_space_or_an_equals_sign() {
let read = |line: &str| script_line(line).unwrap();
assert_eq!(
read(r#"layer.ramp={"ramp": "Phosphor Frostfire"}"#).unwrap(),
("layer.ramp".into(), json!({"ramp": "Phosphor Frostfire"}))
);
assert_eq!(read(r#"gp.threads={"threads":8}"#).unwrap(), ("gp.threads".into(), json!({"threads": 8})));
assert_eq!(read("map.zoomIn=").unwrap(), ("map.zoomIn".into(), Value::Null));
assert!(read("map.zoomIn={bad").is_err(), "not JSON");
assert!(read("script.run={}").is_err_and(|e| e.contains("can't run in a script")), "refused by its id");
// A space before the `=` leaves it in the parameters, as before.
assert!(read("map.zoomIn = {}").is_err());
}

/// A landing page with collections retains the constructed map-template fallback. Supplied
/// collections and an explicit final template keep its Session notice checks network-free.
#[test]
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/roles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,8 @@ pub(crate) fn script(source: &str, depth: usize) -> (Option<String>, Report) {
}
Some(Err(_)) if suspicious(&Value::String(line.into())) => {
report.withheld = report.withheld.saturating_add(1);
let id = line.trim_start().split(char::is_whitespace).next().unwrap_or("");
// The id as Run reads it (`id {json}`, `id= {json}` or `id={json}`).
let id = crate::split_script_id(line.trim_start()).0;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
let public_id = identifier(id, &mut report);
Some(format!("{} {WITHHELD}{ending}", public_id.as_deref().unwrap_or(id)))
}
Expand Down
29 changes: 29 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3304,6 +3304,35 @@ fn unique_values_by_expression_keep_their_classes_and_say_scales() {
assert_eq!(kept.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["overview"]);
}

/// A script runs a line written `id={json}`, as the command line and the user guide write it
/// (#2794), and refuses a script inside it written so.
#[test]
fn a_script_runs_a_line_with_its_parameters_after_an_equals_sign() {
let mut s = numbered_points(&[1]);
s.run("script.run", &json!({"script": r#"layer.rename={"layer":"Herds","name":"Cows"}"#})).unwrap();
assert!(s.map().layer_by_name("Cows").is_some(), "renamed");
let refused = s.run("script.run", &json!({"script": r#"script.run={"script":""}"#})).unwrap_err();
assert!(refused.contains("can't run in a script"), "{refused}");
}

/// A notebook from a file reads a cell's `id={json}` line as a script does (#2794): one that
/// stays in the session runs, and one that writes a file is still refused.
#[test]
fn a_notebook_from_a_file_reads_a_line_with_its_parameters_after_an_equals_sign() {
let mut s = numbered_points(&[1]);
let png = std::env::temp_dir().join(format!("rustgis-2794-{}.png", std::process::id()));
let _ = std::fs::remove_file(&png);
let cells = [r#"layer.rename={"layer":"Herds","name":"Cows"}"#.to_string(), format!("share.exportMap={}", json!({"path": png}))];
let cells: Vec<Value> = cells.iter().map(|c| json!({"cell_type": "code", "source": c})).collect();
let text = json!({"nbformat": 4, "metadata": {"language_info": {"name": "rustgis"}}, "cells": cells}).to_string();
s.run("notebook.open", &json!({"text": text})).unwrap();
let name = s.project.notebooks.last().unwrap().name.clone();
let r = s.run("notebook.run", &json!({"notebook": name})).unwrap();
assert_eq!(r["error"], 1, "{r}");
assert!(s.map().layer_by_name("Cows").is_some(), "the first cell ran");
assert!(!png.exists(), "the second wrote nothing");
}

/// A layer of points read from GeoJSON, one for each value given, in that order: the integer
/// field `n` holds it, the text field `code` its digits, the text field `name` "h" and them.
fn numbered_points(values: &[i64]) -> Session {
Expand Down
11 changes: 11 additions & 0 deletions crates/engine/src/tests/credential_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,17 @@ fn durable_future_documents_keep_their_exact_text_unchecked() {
assert_eq!((report.withheld, report.unchecked), (1, 0));
}

/// A script line that doesn't read and holds a secret keeps only its command id, read as Run
/// reads it: a line written `id={…` with no space keeps `id`, not the secret after the `=` (#2794).
#[test]
fn a_withheld_script_line_keeps_only_its_command_id() {
let secret = "RGSYNTH_glued_20261123";
let (clean, report) = crate::roles::script(&format!(r#"layer.rename={{"token":"{secret}""#), 0);
let clean = clean.unwrap();
assert_eq!(clean, "layer.rename [parameters withheld]");
assert_eq!(report.withheld, 1);
}

#[test]
fn durable_formatter_errors_unwinds_and_apply_failures_restore_whole_fields() {
use durable::{Durable, FieldMut, Leaf, Owner, Prepare};
Expand Down
39 changes: 21 additions & 18 deletions crates/ui-egui/src/scriptcolor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,15 @@ pub fn spans(script: &str, unknown: &[String]) -> Vec<Span> {
out
}

/// The command id of a script line, as `script_commands` reads it: its first word (to the first
/// space), less a trailing `=`. So `labels.style= {…}` names `labels.style`, while
/// `labels.style={…}` names `labels.style={…` as Run does, which no command has. None for a blank
/// or comment line.
/// The command id of a script line, as `script_commands` reads it (`split_script_id`): to its
/// first space or `=`, so `labels.style {…}`, `labels.style= {…}` and `labels.style={…}` all name
/// `labels.style`. None for a blank or comment line.
pub fn line_id(line: &str) -> Option<&str> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let id = line.split_once(char::is_whitespace).map_or(line, |(id, _)| id);
Some(id.trim_end_matches('='))
Some(rustgis_engine::split_script_id(line).0)
}

fn line_spans(script: &str, range: Range<usize>, unknown: &[String], out: &mut Vec<Span>) {
Expand All @@ -91,8 +89,9 @@ fn line_spans(script: &str, range: Range<usize>, unknown: &[String], out: &mut V
return;
}
plain(start..start + lead, out);
let word = body.split_once(char::is_whitespace).map_or(body, |(w, _)| w);
let id = word.trim_end_matches('=');
let id = rustgis_engine::split_script_id(body).0;
// The `=` that ends an id is drawn apart; a space ending it stays with the parameters.
let word = if body[id.len()..].starts_with('=') { &body[..id.len() + 1] } else { id };
// Read as `script_commands` reads it: the JSON once, and the engine's own rule for the ids a
// script refuses.
let rest = &body[word.len()..];
Expand Down Expand Up @@ -474,15 +473,19 @@ mod tests {
assert!(k.contains(&("-2e3".to_string(), Kind::Num, false)));
}

/// The id is the first word as Run reads it (`script_commands`): a trailing `=` is dropped, but
/// `id={json}` with no space is one word, which no command has.
/// The id is read as Run reads it (`script_commands`): to its first space or `=`, so
/// `id= {json}` and `id={json}` (#2794) both name `id`, the `=` drawn apart and the JSON
/// coloured; an unknown id is still marked.
#[test]
fn an_id_is_the_first_word_as_run_reads_it() {
let k = kinds(r#"labels.style= {"size": 12}"#, &[]);
assert_eq!(k[..2], [("labels.style".to_string(), Kind::Id, false), ("=".to_string(), Kind::Punct, false)]);
let glued = r#"labels.style={"size": 12}"#;
assert_eq!(line_id(glued), Some(r#"labels.style={"size":"#));
assert_eq!(kinds(glued, &[r#"labels.style={"size":"#])[0].1, Kind::BadId);
fn an_id_is_read_as_run_reads_it() {
let parts = [("labels.style".to_string(), Kind::Id, false), ("=".to_string(), Kind::Punct, false)];
for line in [r#"labels.style= {"size": 12}"#, r#"labels.style={"size": 12}"#] {
let k = kinds(line, &[]);
assert_eq!(k[..2], parts, "{line}");
assert!(k.contains(&(r#""size""#.to_string(), Kind::Key, false)), "{line}: {k:?}");
assert_eq!(line_id(line), Some("labels.style"), "{line}");
}
assert_eq!(kinds(r#"nosuch.cmd={"a": 1}"#, &["nosuch.cmd"])[0].1, Kind::BadId);
assert_eq!((line_id(" # x"), line_id(" "), line_id("map.zoomFull")), (None, None, Some("map.zoomFull")));
}

Expand Down Expand Up @@ -514,8 +517,8 @@ mod tests {
fn unknown_ids_are_the_ones_no_command_has() {
let app = crate::RustGisApp::with_sample();
let script = "nope.cmd {}\nmap.zoomFull\n# x.y\nnope.cmd\nplugin:none/cmd {}\nlabels.style= {}\nlabels.style={}";
// `labels.style={}` is one word, as Run reads it: no command has that id.
assert_eq!(super::unknown_ids(&app.session, script), ["labels.style={}", "nope.cmd", "plugin:none/cmd"]);
// `labels.style={}` names `labels.style`, as Run reads it (#2794).
assert_eq!(super::unknown_ids(&app.session, script), ["nope.cmd", "plugin:none/cmd"]);
}

/// The Script pane draws its coloured box, and the text in it is the script as typed.
Expand Down
14 changes: 13 additions & 1 deletion crates/ui-egui/src/scriptcomplete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ pub fn word_at(script: &str, at: usize, asked: bool) -> Option<(usize, String)>
let line = before.rsplit('\n').next().unwrap_or_default();
let word = line.trim_start();
let fewest = if asked { 0 } else { MIN_TYPED };
if word.chars().count() < fewest || word.chars().any(char::is_whitespace) || word.starts_with('#') {
// A space or `=` ends a line's id (`split_script_id`): past one, the cursor is in its parameters.
if word.chars().count() < fewest || word.chars().any(|c| c.is_whitespace() || c == '=') || word.starts_with('#') {
return None;
}
Some((at - word.chars().count(), word.to_string()))
Expand Down Expand Up @@ -1768,6 +1769,7 @@ mod tests {
fn only_a_lines_first_word_at_the_cursor_is_completed() {
let none = |s: &str, at: usize| offer(s, at, &ids()).is_none();
assert!(none("labels.style {\"la", 17), "in the JSON");
assert!(none("labels.style={\"la", 17), "in the JSON after an equals sign (#2794)");
assert!(none("# labels", 8), "in a comment");
assert!(none("l", 1), "one character");
assert!(none("labels.st", 4), "the cursor mid-word");
Expand Down Expand Up @@ -2687,6 +2689,15 @@ mod tests {
assert_eq!(o.of, Some(super::Of::CommandKeys("map.goToXY".into())));
}

/// Keys are offered in a line written `id={json}` as in `id {json}` (#2794).
#[test]
fn keys_are_offered_after_an_equals_sign() {
let app = crate::RustGisApp::with_sample();
let keys = |s: &str| unasked(s, s.chars().count(), &[], &app.session).map(|o| o.items).unwrap_or_default();
assert_eq!(keys(r#"map.goToXY={"la"#), keys(r#"map.goToXY {"la"#));
assert!(keys(r#"map.goToXY={"la"#).contains(&"lat".to_string()));
}

/// The key under the cursor, closed or not, doesn't count as given; the same key given
/// elsewhere on the line does.
#[test]
Expand Down Expand Up @@ -2755,6 +2766,7 @@ mod tests {
assert_eq!(at("labels.style "), None, "before the brace");
assert_eq!(at("# labels.style {"), None, "a comment");
assert_eq!(at(r#"labels.style {"a": {"b": 1"#), Some((0, "labels.style".into())), "nested");
assert_eq!(at(r#"labels.style={"si"#), Some((0, "labels.style".into())), "after an equals sign (#2794)");
assert!(hint_at("x", 99).is_none(), "a cursor past the text");
}

Expand Down
2 changes: 1 addition & 1 deletion docs/user-guide/analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -1791,7 +1791,7 @@ on a grid of any coordinate system, cell size and extent, and Polygons to Raster
(`raster.rasterize`) burns polygons onto the same grids; Raster Functions › Resample matches a
target raster's grid.

The **Script** pane runs commands from text, one per line (`id {json}`); its box grows with the script down to the bottom of the pane,
The **Script** pane runs commands from text, one per line (`id {json}`, or `id={json}` as on the command line); its box grows with the script down to the bottom of the pane,
short of the buttons, and then scrolls, so **Run** stays in view; Ctrl+Enter (⌘+Enter on macOS)
in the box runs the script too. Above a run's results, a line tells its number, how long it took
and when it started (`Run #2 (0.84 s)`, and `14:04 UTC` on the right), so a run made again by
Expand Down
2 changes: 1 addition & 1 deletion docs/user-guide/layouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,7 @@ previews, edits and plays it.

**Analyze › New Notebook** starts a notebook of text and command cells; **Add and Open** opens a
RustGIS (`.rgisnb`) or Jupyter (`.ipynb`) notebook. A command cell runs one command per line
(`id {json}`, as in scripts) and shows each command's result beneath it. Notebooks save in
(`id {json}` or `id={json}`, as in scripts) and shows each command's result beneath it. Notebooks save in
either format. The Notebook pane opens beside the map, on half of the room right of the left
pane (at least 320 points where the window allows); drag its edge to give the notebook or the
map more room.
Expand Down
Loading