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
18 changes: 17 additions & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,22 @@ fn to_json<T: serde::Serialize>(v: &T) -> Result<Vec<u8>, String> {
serde_json::to_vec(v).map_err(|e| e.to_string())
}

/// A task's file: the task, with `requires` listing what its steps need when they need anything
/// (as a model's file does). A RustGIS that checks `requires` (#2867 on) refuses what it would run
/// without; one that doesn't ignores the key, as it does for any task file today (#2818).
fn task_json(t: &Task) -> Result<Vec<u8>, String> {
// A struct, not a `serde_json::Value`, which would sort the task's keys.
#[derive(serde::Serialize)]
struct TaskFile<'a> {
#[serde(flatten)]
task: &'a Task,
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<&'static str>,
}
let requires = crate::project::task_capabilities(&t.steps);
serde_json::to_vec(&TaskFile { task: t, requires }).map_err(|e| e.to_string())
}

/// Whether command `id` can be added as a task's step (`task.addStep`): a built-in command, and
/// not a task's own (a step doesn't run a task).
pub fn can_be_step(s: &Session, id: &str) -> bool {
Expand Down Expand Up @@ -1907,7 +1923,7 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve
"task" => {
let t = task_mut(s, p)?;
let name = t.name.clone();
let (bytes, report) = crate::durable::output(t, None, to_json)?;
let (bytes, report) = crate::durable::output(t, None, task_json)?;
crate::durable::notify(s, &report);
(name, bytes)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ mod capabilities;
#[path = "project_label_losses.rs"]
pub(crate) mod label_losses;
pub use capabilities::layout_file_bytes;
pub(crate) use capabilities::{layer_file_bytes, map_file_bytes, model_capabilities};
pub(crate) use capabilities::{layer_file_bytes, map_file_bytes, model_capabilities, task_capabilities};

/// A map export cannot keep runtime-only download reservations, even in a larger project.
pub(crate) fn ensure_map_imports_complete(map: &Map) -> Result<(), String> {
Expand Down
13 changes: 13 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,19 @@ impl Project {
}
}

/// What a task saved on its own needs: what a project saves for its tasks' steps (a `model.run`
/// given its graph inline, and a script line, included), in the order its list has them.
pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> {
let mut required: Vec<&'static str> = COMMAND_CAPABILITIES
.iter()
.filter_map(|&(name, uses)| steps.iter().any(|s| command_uses(&uses, &s.command, &s.params)).then_some(name))
.collect();
if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) {
required.push("table-export-order");
}
required
}

type CommandCheck = fn(&str, &Value) -> bool;
const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("slope-percent", command_uses_percent_slope),
Expand Down
73 changes: 73 additions & 0 deletions crates/engine/src/tests/task_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,76 @@ fn a_recorded_task_import_keeps_its_requires_only_when_it_carries_no_credential(
assert!(import(&mut s, &kept).unwrap_err().contains("future-step-key"));
}
}

/// `steps` as a task a project holds, saved with `task.save`: the file's text, and the `requires`
/// the same task has in a project saved on its own (`None`: no header).
fn saved_text(steps: Value) -> (String, Option<Value>) {
let mut doc = serde_json::to_value(Project::default()).unwrap();
doc["tasks"] = json!([{"name": "Lesson", "steps": steps}]);
let project = Project::from_json(&doc.to_string()).unwrap();
let in_a_project = serde_json::to_value(&project).unwrap().get("requires").cloned();
let mut s = Session::new(project);
let file =
TempFile(std::env::temp_dir().join(format!("task-save-2818-{}-{:?}.rgistask", std::process::id(), std::thread::current().id())));
let result = s.run("task.save", &json!({"task": "Lesson", "path": file.0.to_string_lossy()}));
let text = std::fs::read_to_string(&file.0);
result.unwrap();
(text.unwrap(), in_a_project)
}

fn saved(steps: Value) -> (Value, Option<Value>) {
let (text, in_a_project) = saved_text(steps);
(serde_json::from_str(&text).unwrap(), in_a_project)
}

fn step(command: &str, params: Value) -> Value {
json!({"title": "Step", "instructions": "", "command": command, "params": params})
}

#[test]
fn a_saved_task_that_needs_nothing_is_written_as_before() {
let steps = json!([step("map.zoomIn", json!({"scale": 1.5, "label": "Zoom é"}))]);
let (text, _) = saved_text(steps.clone());
let task = crate::project::Task { name: "Lesson".into(), description: String::new(), steps: serde_json::from_value(steps).unwrap() };
assert_eq!(text, serde_json::to_string(&task).unwrap(), "same bytes, keys in the task's own order");
assert!(!text.contains("requires"));
}

#[test]
fn a_saved_task_with_requires_keeps_its_own_keys_in_order() {
let (text, _) = saved_text(json!([step("raster.function", json!({"function": "slope", "units": "percent"}))]));
let at = |key: &str| text.find(&format!("\"{key}\":")).unwrap();
assert!(at("name") < at("description") && at("description") < at("steps") && at("steps") < at("requires"), "{text}");
}

#[test]
fn a_saved_task_lists_what_its_steps_need_once_and_as_a_project_does() {
let slope = || step("raster.function", json!({"function": "slope", "units": "percent"}));
let sorted = step("share.exportTable", json!({"sort": [{"field": "a"}]}));
let script = step("script.run", json!({"script": "# Slope\nraster.function {\"function\": \"slope\", \"units\": \"percent\"}"}));
let inline = |tool: &str, params: Value| {
step("model.run", json!({"graph": {"nodes": [{"id": "n", "kind": "tool", "tool": tool, "params": params}]}}))
};
for (why, steps, expected) in [
("a step", json!([slope()]), json!(["slope-percent"])),
("twice", json!([slope(), step("map.zoomIn", json!({})), slope()]), json!(["slope-percent"])),
("a script line", json!([script]), json!(["slope-percent"])),
("a table export order", json!([sorted]), json!(["table-export-order"])),
("a model given inline", json!([inline("tabulateIntersection", json!({"areaUnit": "ac"}))]), json!(["tabulate-intersection-unit"])),
] {
let (file, in_a_project) = saved(steps);
assert_eq!(file["requires"], expected, "{why}");
assert_eq!(in_a_project, Some(expected), "{why}: the project's own walk");
}
}

#[test]
fn a_saved_task_is_read_back_and_refused_when_its_requires_is_edited() {
let (mut file, _) = saved(json!([step("raster.function", json!({"function": "slope", "units": "percent"}))]));
let mut s = Session::new(Project::default());
import(&mut s, &file.to_string()).unwrap();
assert_eq!(s.project.tasks[0].steps[0].command, "raster.function");
file["requires"] = json!(["slope-percent", "future-step-key"]);
let err = import(&mut s, &file.to_string()).unwrap_err();
assert_eq!(err, "this task needs what this RustGIS can't read: future-step-key. Update RustGIS to open it.");
}
6 changes: 3 additions & 3 deletions docs/maintaining.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ same files. New and changed code follows these rules; not every existing reader
writes it.
- A project, map or layer file, a model or a web tool lists in `requires` each capability it needs
that an older reader would lose or misread: a reader refuses one it doesn't know, naming it.
`task.import` reads a task file this way (#2818), though `task.save` doesn't list anything in one
yet. Presentation and notebook readers, and models inside a task's steps, don't check
`requires` yet. A release reads
A task file does too (#2818): `task.save` lists what its steps need, a `model.run` step's inline
graph included, and `task.import` refuses one it doesn't know. Presentation and notebook readers
don't check `requires` yet. A release reads
`.rgis` format 2 before any writes it (`READ_FORMAT` and `CAPABILITIES` in
`crates/engine/src/project.rs`), so what is added to format 2 after that comes with a capability
name, added to `CAPABILITIES` where it is read.
Expand Down
Loading