From 3bf9e30a475cf06c0dba214abe7f5ef10a9174fe Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 16 Nov 2026 15:48:46 -0300 Subject: [PATCH 1/3] feat(gp): name GeoLibre tool outputs with an Output Name field (#2224) GeoLibre tools get the optional 'output' field the built-in tools have. The new layer takes the name given, else the tool's name; a name in use gets a number, said when it was the user's. Language packs don't map their output-file text onto the field. Co-Authored-By: Claude Opus 5.5 --- crates/geolibre/src/langpack.rs | 36 ++++++++++---- crates/geolibre/src/lib.rs | 81 ++++++++++++++++++++++++++++++-- crates/geolibre/src/tests.rs | 83 ++++++++++++++++++++++++++++++++- docs/user-guide/analysis.md | 5 ++ 4 files changed, 188 insertions(+), 17 deletions(-) diff --git a/crates/geolibre/src/langpack.rs b/crates/geolibre/src/langpack.rs index 145b19dc48..6e9f5fe545 100644 --- a/crates/geolibre/src/langpack.rs +++ b/crates/geolibre/src/langpack.rs @@ -265,7 +265,8 @@ fn english_to_pack(pack: &Pack, tools: &[ToolSpec]) -> HashMap { let Some(text) = pack.tools.get(spec.id.trim_start_matches(crate::PREFIX)) else { continue }; put(spec.name, text.name.as_deref()); put(spec.summary, text.description.as_deref()); - for p in spec.params { + // RustGIS's own output name field isn't the manifest's `output` file the pack describes. + for p in spec.params.iter().filter(|p| !crate::is_output_name(p)) { let Some((label, help)) = text.params.get(p.name) else { continue }; put(p.label, label.as_deref()); put(p.help, help.as_deref()); @@ -567,7 +568,10 @@ mod tests { "toolMeta": {"whitebox": {"contours_from_raster": { "name": "Curvas de nível a partir de raster", "description": "Cria polilinhas de curvas de nível.", - "params": {"interval": {"label": "Intervalo", "description": "Equidistância."}} + "params": { + "interval": {"label": "Intervalo", "description": "Equidistância."}, + "output": {"label": "Saída", "description": "Arquivo vetorial de saída."} + } }}}, "whitebox": { "categories": {"vector": "Vetor", "remoteSensingSar": "Sensoriamento remoto - SAR"}, @@ -579,14 +583,24 @@ mod tests { .to_string() } - static PARAMS: [ParamSpec; 1] = [ParamSpec { - name: "interval", - label: "Interval", - kind: ParamKind::Number, - required: false, - default: "", - help: "Contour interval value.", - }]; + static PARAMS: [ParamSpec; 2] = [ + ParamSpec { + name: "interval", + label: "Interval", + kind: ParamKind::Number, + required: false, + default: "", + help: "Contour interval value.", + }, + ParamSpec { + name: crate::OUTPUT, + label: crate::OUTPUT_LABEL, + kind: ParamKind::Text, + required: false, + default: "", + help: crate::OUTPUT_HELP, + }, + ]; fn no_run(_: &dyn rustgis_analysis::Inputs, _: &Value) -> Result { Err("not run".into()) @@ -632,6 +646,8 @@ mod tests { assert_eq!(map.get("Remote Sensing").map(String::as_str), Some("Sensoriamento remoto")); assert!(!map.contains_key("SAR"), "the same as the English, or missing: left out"); assert!(!map.contains_key("SAR Info"), "a tool the pack doesn't name stays in English"); + // RustGIS's output name field isn't the output file the pack describes (#2224). + assert!(!map.contains_key(crate::OUTPUT_LABEL) && !map.contains_key(crate::OUTPUT_HELP), "{map:?}"); } #[test] diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 74068935c9..6867ef0fe7 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -135,6 +135,22 @@ struct Meta { schema: &'static [ParamSpec], category: String, params: Vec, + /// The form has the [`OUTPUT`] field naming the layers the outputs come back as. + names_outputs: bool, +} + +/// The parameter that names a tool's new layers, under the key the built-in tools use (#2224). +pub const OUTPUT: &str = "output"; +/// The [`OUTPUT`] field's label, as on the built-in tools. +const OUTPUT_LABEL: &str = "Output Name"; +/// The [`OUTPUT`] field's help: the same text on every tool, so it can be translated. +const OUTPUT_HELP: &str = "Name of the new layer. Empty: the tool's name. With several outputs, each adds its own name to it. A name already in use gets a number."; +/// The longest layer name [`OUTPUT`] keeps (the engine's longest name). +const MAX_OUTPUT_NAME: usize = 200; + +/// `p` is the [`OUTPUT`] field RustGIS adds, not one of the manifest's parameters. +pub fn is_output_name(p: &ParamSpec) -> bool { + p.name == OUTPUT && p.label == OUTPUT_LABEL && p.kind == ParamKind::Text } static META: Mutex>> = Mutex::new(None); @@ -252,7 +268,8 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> { let optional = !p.get("required").and_then(Value::as_bool).unwrap_or(false); let default = defaults.and_then(|d| d.get(pname)).filter(|v| optional && !v.is_null()).cloned(); meta.push(MetaParam { name: pname.to_string(), role, data, default }); - // Outputs are written to a scratch folder and come back as layers: no form field. + // Outputs are written to a scratch folder and come back as layers: no field of their own + // (the one [`OUTPUT`] field below names the layers). if role == Role::Output { continue; } @@ -306,6 +323,19 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> { help: leak(help), }); } + // One optional field names the new layers. A tool with an option or input of its own called + // `output` keeps it, and its outputs keep the tool's name. + let names_outputs = meta.iter().any(|p| p.role == Role::Output) && !params.iter().any(|p| p.name == OUTPUT); + if names_outputs { + params.push(ParamSpec { + name: OUTPUT, + label: OUTPUT_LABEL, + kind: ParamKind::Text, + required: false, + default: "", + help: OUTPUT_HELP, + }); + } let spec = ToolSpec { id: leak(format!("{PREFIX}{id}")), name: leak(name), @@ -315,7 +345,7 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> { run: rustgis_analysis::external_placeholder, }; let schema = spec.params; - Some((spec, Meta { schema, category, params: meta })) + Some((spec, Meta { schema, category, params: meta, names_outputs })) } /// `g` with every point converted by `f`, or `None` when a point can't be (rather than @@ -626,6 +656,8 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu }; let n_outputs = meta.params.iter().filter(|p| p.role == Role::Output).count(); + let given = if meta.names_outputs { output_name(spec, params, &mut job.notes)? } else { None }; + let base = given.as_deref().unwrap_or(spec.name); for p in &meta.params { match p.role { Role::Input => { @@ -638,9 +670,17 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu Role::Output => { let file = format!("{}.{}", safe(&p.name), output_ext(p, meta)); job.args.push((p.name.clone(), Arg::Files(vec![FileRef::Work(file.clone())]))); - let name = - if n_outputs > 1 { format!("{} {}", spec.name, label_of(&p.name).to_lowercase()) } else { spec.name.to_string() }; - job.outputs.push((file, name)); + let name = if n_outputs > 1 { format!("{base} {}", label_of(&p.name).to_lowercase()) } else { base.to_string() }; + // A name a layer, a table or an earlier output of this run has gets a number, so two + // runs don't give two layers of one name. Said when it was the name given. + let taken = |n: &str| { + inputs.dataset(n).is_some() || inputs.raster(n).is_some() || job.outputs.iter().any(|(_, o)| o.eq_ignore_ascii_case(n)) + }; + let free = numbered(&name, taken); + if given.is_some() && free != name { + job.notes.push(format!("{}: a layer is named '{name}' already, so the new one is '{free}'", spec.name)); + } + job.outputs.push((file, free)); } Role::Option => { let Some(v) = value_of(&p.name).map(|v| option_value(v, p.data)) else { continue }; @@ -658,6 +698,37 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu Ok(job) } +/// The layer name given in [`OUTPUT`], trimmed, or `None` for the tool's own name. Cut to +/// [`MAX_OUTPUT_NAME`] characters, which is said. +fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec) -> Result, String> { + let name = match params.get(OUTPUT) { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(s)) => s.trim(), + Some(_) => return Err(format!("{}: '{OUTPUT}' is the new layer's name and must be text", spec.name)), + }; + if name.is_empty() { + return Ok(None); + } + let n = name.chars().count(); + if n > MAX_OUTPUT_NAME { + notes.push(format!("{}: the output name is cut from {n} to {MAX_OUTPUT_NAME} characters", spec.name)); + } + Ok(Some(name.chars().take(MAX_OUTPUT_NAME).collect())) +} + +/// `base`, or the first of `base 2`, `base 3`… that `taken` doesn't claim, within +/// [`MAX_OUTPUT_NAME`] characters. +fn numbered(base: &str, taken: impl Fn(&str) -> bool) -> String { + let mut name = base.to_string(); + let mut k = 1u64; + while taken(&name) { + k += 1; + let suffix = format!(" {k}"); + name = base.chars().take(MAX_OUTPUT_NAME.saturating_sub(suffix.len())).chain(suffix.chars()).collect(); + } + name +} + /// Coordinates that can't be longitude/latitude (a tool kept the working coordinate system). fn looks_projected(ds: &Dataset) -> bool { let e = ds.extent(); diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index 4edaae74f3..b3be32f4a2 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -95,7 +95,9 @@ fn manifests_become_tool_forms() { // Grouped by the runner's taxonomy; a runner from before it, by the coarse category. assert!(matches!(slope.toolbox, "GeoLibre › Terrain › Derivatives" | "GeoLibre › Raster"), "{}", slope.toolbox); assert_eq!(slope.params.first().map(|p| p.kind), Some(ParamKind::RasterLayer)); - assert!(slope.params.iter().all(|p| p.name != "output"), "outputs are not form fields"); + // Outputs have no field of their own: one optional field names the new layer (#2224). + let outputs: Vec<&ParamSpec> = slope.params.iter().filter(|p| p.name == OUTPUT).collect(); + assert!(matches!(outputs[..], [p] if is_output_name(p) && !p.required && p.default.is_empty()), "{outputs:?}"); let units = slope.params.iter().find(|p| p.name == "units").unwrap(); assert!(matches!(units.kind, ParamKind::Choice(c) if c.contains(&"percent"))); // Defaults are JSON text (as for the built-in tools): the form and the runner parse it. @@ -128,11 +130,88 @@ fn inputs_of_several_layers_are_layer_lists() { ("inputs", ParamKind::RasterLayers), ("vectors", ParamKind::VectorLayers), ("files", ParamKind::Text), - ("dem", ParamKind::RasterLayer) + ("dem", ParamKind::RasterLayer), + ("output", ParamKind::Text) ] ); } +/// The layers a run adds are named by `output`, as for the built-in tools, else by the tool; +/// a name in use gets a number (#2224). +#[test] +fn outputs_are_named_by_the_output_field() { + let f = Fixture::new(); + let one = json!({ + "id": "contours", "display_name": "Contours From Raster", "category": "Raster", "summary": "", + "params": [ + {"name": "input", "io_role": "input", "data_kind": "raster", "required": true, "schema": {"kind": "input"}}, + {"name": "output", "io_role": "output", "data_kind": "vector", "required": false, "schema": {"kind": "output"}} + ] + }); + let (spec, meta) = spec_of(&one).unwrap(); + let field = spec.params.iter().find(|p| p.name == OUTPUT).unwrap(); + assert!(is_output_name(field) && field.label == "Output Name", "{field:?}"); + let job = |params: Value| { + let params = rustgis_analysis::resolve_params(&spec, ¶ms)?; + prepare_with(&spec, &meta, &f, ¶ms) + }; + let named = |params: Value| job(params).map(|j| j.outputs.iter().map(|(_, n)| n.clone()).collect::>()); + // Empty (the form's start), blank or left out: the tool's name, as before. + for p in [json!({"input": "dem"}), json!({"input": "dem", "output": ""}), json!({"input": "dem", "output": " "})] { + assert_eq!(named(p.clone()).unwrap(), ["Contours From Raster"], "{p}"); + } + let given = job(json!({"input": "dem", "output": " Contours 10 m "})).unwrap(); + assert_eq!(given.outputs, [("output.geojson".to_string(), "Contours 10 m".to_string())]); + // The file the runner writes doesn't change: the name is only the layer's. + assert_eq!(given.argv("/work"), ["--input=/work/in0-dem.tif", "--output=/work/output.geojson"]); + assert!(given.notes.is_empty(), "{:?}", given.notes); + // A layer has the name already: numbered, and said. + let taken = job(json!({"input": "dem", "output": "pts"})).unwrap(); + assert_eq!(taken.outputs[0].1, "pts 2"); + assert!(taken.notes.iter().any(|n| n.contains("'pts'") && n.contains("'pts 2'")), "{:?}", taken.notes); + // Too long: cut, and said. + let long = job(json!({"input": "dem", "output": "x".repeat(300)})).unwrap(); + assert_eq!(long.outputs[0].1.chars().count(), MAX_OUTPUT_NAME); + assert!(long.notes.iter().any(|n| n.contains("cut from 300 to 200")), "{:?}", long.notes); + // Not text: an error, not a guess. + let e = job(json!({"input": "dem", "output": 5})).unwrap_err(); + assert!(e.contains("must be text"), "{e}"); + + // Several outputs: each adds its label to the name, and two can't take one name. + let two = json!({ + "id": "flow", "display_name": "Flow", "category": "Hydrology", "summary": "", + "params": [ + {"name": "dem", "io_role": "input", "data_kind": "raster", "required": true}, + {"name": "streams", "io_role": "output", "data_kind": "raster"}, + {"name": "basins", "io_role": "output", "data_kind": "raster"} + ] + }); + let (spec2, meta2) = spec_of(&two).unwrap(); + let names = |params: Value| { + let params = rustgis_analysis::resolve_params(&spec2, ¶ms).unwrap(); + prepare_with(&spec2, &meta2, &f, ¶ms).unwrap().outputs.into_iter().map(|(_, n)| n).collect::>() + }; + assert_eq!(names(json!({"dem": "dem"})), ["Flow streams", "Flow basins"]); + assert_eq!(names(json!({"dem": "dem", "output": "Rio Doce"})), ["Rio Doce streams", "Rio Doce basins"]); + assert_eq!(numbered("a", |n| ["a", "a 2"].contains(&n)), "a 3"); + assert_eq!(numbered(&"y".repeat(200), |n| n.chars().all(|c| c == 'y')).chars().count(), MAX_OUTPUT_NAME); + + // A tool whose own option is called `output` keeps it; its outputs keep the tool's name. + let own = json!({ + "id": "own", "display_name": "Own", "category": "Raster", "summary": "", + "params": [ + {"name": "output", "data_kind": "string", "required": false, "schema": {"kind": "string"}}, + {"name": "result", "io_role": "output", "data_kind": "raster"} + ] + }); + let (spec3, meta3) = spec_of(&own).unwrap(); + assert!(!meta3.names_outputs && spec3.params.iter().filter(|p| p.name == OUTPUT).all(|p| !is_output_name(p))); + let params = rustgis_analysis::resolve_params(&spec3, &json!({"output": "fast"})).unwrap(); + let j = prepare_with(&spec3, &meta3, &f, ¶ms).unwrap(); + assert_eq!(j.outputs[0].1, "Own"); + assert!(j.argv("/work").contains(&"--output=fast".to_string()), "{:?}", j.argv("/work")); +} + #[test] fn composite_bands_legacy_manifest_selects_and_stages_rasters_in_order() { // The input/output subset of `geolibre manifests` in 1.8.0 and 1.8.1 (#1684). diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index fd498dcbec..e5aa2e2615 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1401,6 +1401,11 @@ list syntax, and check the tool's own help for what a weight field left blank me become standalone tables; text reports appear in the tool's messages. - LiDAR and other inputs RustGIS doesn't open as layers take a file path, read like Add Data reads one. Outputs are written to a fresh scratch folder and loaded from there. +- **Output Name** names the new layer, as on the built-in tools; left empty, the layer takes the + tool's name (in English). A tool with several outputs adds each output's name to it + (`Flow streams`, `Flow basins`). A name a layer or table already has gets a number + (`Contours 2`), and a name you typed that gets one is said in the messages. From the command + line it is the same `output` key: `"params":{"input":"dem","output":"Slope 30 m"}`. - Each run is a separate `geolibre` process, so a tool that fails can't take RustGIS down. - From the command line: `gp.run={"tool":"geolibre:slope","params":{"input":"dem"}}`; `gp.tools` lists every tool's parameters, `gp.geolibre` shows the runner in use and From c0e88218f548828703cc3699ae8fffb9713cf3ef Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 16 Nov 2026 15:58:46 -0300 Subject: [PATCH 2/3] fix(gp): keep multi-output names within 200 characters, one notice per kind (#2224) A long Output Name leaves room for each output's own name, so every layer name stays within the limit. Numbered names and a cut name each give one notice for the run, with a count, instead of one per output. Co-Authored-By: Claude Opus 5.5 --- crates/geolibre/src/lib.rs | 16 ++++++++++++++-- crates/geolibre/src/tests.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 6867ef0fe7..c3de9920b8 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -658,6 +658,7 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu let n_outputs = meta.params.iter().filter(|p| p.role == Role::Output).count(); let given = if meta.names_outputs { output_name(spec, params, &mut job.notes)? } else { None }; let base = given.as_deref().unwrap_or(spec.name); + let (mut renamed, mut shortened) = (Vec::new(), false); for p in &meta.params { match p.role { Role::Input => { @@ -670,7 +671,11 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu Role::Output => { let file = format!("{}.{}", safe(&p.name), output_ext(p, meta)); job.args.push((p.name.clone(), Arg::Files(vec![FileRef::Work(file.clone())]))); - let name = if n_outputs > 1 { format!("{base} {}", label_of(&p.name).to_lowercase()) } else { base.to_string() }; + // Each output's own name after the one given, kept whole within the limit. + let suffix = if n_outputs > 1 { format!(" {}", label_of(&p.name).to_lowercase()) } else { String::new() }; + let room = MAX_OUTPUT_NAME.saturating_sub(suffix.chars().count()); + shortened |= given.is_some() && base.chars().count() > room; + let name: String = base.chars().take(room).chain(suffix.chars()).collect(); // A name a layer, a table or an earlier output of this run has gets a number, so two // runs don't give two layers of one name. Said when it was the name given. let taken = |n: &str| { @@ -678,7 +683,7 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu }; let free = numbered(&name, taken); if given.is_some() && free != name { - job.notes.push(format!("{}: a layer is named '{name}' already, so the new one is '{free}'", spec.name)); + renamed.push(format!("'{name}' is now '{free}'")); } job.outputs.push((file, free)); } @@ -695,6 +700,13 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu } } } + // One notice per kind, with a count. + if !renamed.is_empty() { + job.notes.push(format!("{}: {} output name(s) in use already, so numbered: {}", spec.name, renamed.len(), renamed.join(", "))); + } + if shortened { + job.notes.push(format!("{}: the output name is cut to fit each output's own name within {MAX_OUTPUT_NAME} characters", spec.name)); + } Ok(job) } diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index b3be32f4a2..5e04471795 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -45,6 +45,21 @@ impl Inputs for Fixture { } } +/// The fixture, plus layers of these names that hold nothing a tool reads. +struct TakenNames<'a>(&'a Fixture, &'a [&'a str]); + +impl Inputs for TakenNames<'_> { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.0.dataset(layer).or_else(|| self.1.contains(&layer).then_some(&self.0.points)) + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + fn raster(&self, layer: &str) -> Option> { + self.0.raster(layer) + } +} + /// The fixture, or `None` (the test is skipped) when no runner is installed: set /// `RUSTGIS_GEOLIBRE` to a `geolibre` executable, or put one on PATH, to run these. fn setup() -> Option { @@ -168,7 +183,7 @@ fn outputs_are_named_by_the_output_field() { // A layer has the name already: numbered, and said. let taken = job(json!({"input": "dem", "output": "pts"})).unwrap(); assert_eq!(taken.outputs[0].1, "pts 2"); - assert!(taken.notes.iter().any(|n| n.contains("'pts'") && n.contains("'pts 2'")), "{:?}", taken.notes); + assert!(taken.notes.iter().any(|n| n.contains("1 output name(s)") && n.contains("'pts' is now 'pts 2'")), "{:?}", taken.notes); // Too long: cut, and said. let long = job(json!({"input": "dem", "output": "x".repeat(300)})).unwrap(); assert_eq!(long.outputs[0].1.chars().count(), MAX_OUTPUT_NAME); @@ -193,6 +208,20 @@ fn outputs_are_named_by_the_output_field() { }; assert_eq!(names(json!({"dem": "dem"})), ["Flow streams", "Flow basins"]); assert_eq!(names(json!({"dem": "dem", "output": "Rio Doce"})), ["Rio Doce streams", "Rio Doce basins"]); + // A long name leaves room for each output's own: every name within the limit, still apart (review). + let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "x".repeat(200)})).unwrap(); + let long = prepare_with(&spec2, &meta2, &f, ¶ms).unwrap(); + let long_names: Vec<&str> = long.outputs.iter().map(|(_, n)| n.as_str()).collect(); + assert!(long_names.iter().all(|n| n.chars().count() == MAX_OUTPUT_NAME), "{long_names:?}"); + assert!(long_names[0].ends_with("x streams") && long_names[1].ends_with("x basins"), "{long_names:?}"); + assert_eq!(long.notes.iter().filter(|n| n.contains("cut to fit")).count(), 1, "{:?}", long.notes); + // Both names in use: one notice with the count, not one per output (review). + let fg = TakenNames(&f, &["Taken streams", "Taken basins"]); + let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "Taken"})).unwrap(); + let both = prepare_with(&spec2, &meta2, &fg, ¶ms).unwrap(); + assert_eq!(both.outputs.iter().map(|(_, n)| n.as_str()).collect::>(), ["Taken streams 2", "Taken basins 2"]); + let numbered_notes: Vec<&String> = both.notes.iter().filter(|n| n.contains("numbered")).collect(); + assert!(matches!(numbered_notes[..], [n] if n.contains("2 output name(s)")), "{:?}", both.notes); assert_eq!(numbered("a", |n| ["a", "a 2"].contains(&n)), "a 3"); assert_eq!(numbered(&"y".repeat(200), |n| n.chars().all(|c| c == 'y')).chars().count(), MAX_OUTPUT_NAME); From a83aee57a86763e35e93fb5d2e75457dac7a060f Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 16 Nov 2026 16:04:20 -0300 Subject: [PATCH 3/3] fix(gp): number a taken output name after the output's own name (#2224) Near the 200-character limit, numbering cut the output's label (' strea 2'); now only the given name is cut. Co-Authored-By: Claude Opus 5.5 --- crates/geolibre/src/lib.rs | 18 +++++++++++------- crates/geolibre/src/tests.rs | 12 ++++++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index c3de9920b8..afe20cf25a 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -681,7 +681,7 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu let taken = |n: &str| { inputs.dataset(n).is_some() || inputs.raster(n).is_some() || job.outputs.iter().any(|(_, o)| o.eq_ignore_ascii_case(n)) }; - let free = numbered(&name, taken); + let free = numbered(base, &suffix, taken); if given.is_some() && free != name { renamed.push(format!("'{name}' is now '{free}'")); } @@ -728,15 +728,19 @@ fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec) -> Resu Ok(Some(name.chars().take(MAX_OUTPUT_NAME).collect())) } -/// `base`, or the first of `base 2`, `base 3`… that `taken` doesn't claim, within -/// [`MAX_OUTPUT_NAME`] characters. -fn numbered(base: &str, taken: impl Fn(&str) -> bool) -> String { - let mut name = base.to_string(); +/// `base` with `suffix` (one output's own name) after it, or, while `taken` claims that, the +/// first with ` 2`, ` 3`… after the suffix that it doesn't. Each fits [`MAX_OUTPUT_NAME`] +/// characters by cutting `base`, never the suffix or the number. +fn numbered(base: &str, suffix: &str, taken: impl Fn(&str) -> bool) -> String { + let fit = |tail: &str| -> String { + let room = MAX_OUTPUT_NAME.saturating_sub(tail.chars().count()); + base.chars().take(room).chain(tail.chars()).collect() + }; + let mut name = fit(suffix); let mut k = 1u64; while taken(&name) { k += 1; - let suffix = format!(" {k}"); - name = base.chars().take(MAX_OUTPUT_NAME.saturating_sub(suffix.len())).chain(suffix.chars()).collect(); + name = fit(&format!("{suffix} {k}")); } name } diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index 5e04471795..1db227c7f0 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -222,8 +222,16 @@ fn outputs_are_named_by_the_output_field() { assert_eq!(both.outputs.iter().map(|(_, n)| n.as_str()).collect::>(), ["Taken streams 2", "Taken basins 2"]); let numbered_notes: Vec<&String> = both.notes.iter().filter(|n| n.contains("numbered")).collect(); assert!(matches!(numbered_notes[..], [n] if n.contains("2 output name(s)")), "{:?}", both.notes); - assert_eq!(numbered("a", |n| ["a", "a 2"].contains(&n)), "a 3"); - assert_eq!(numbered(&"y".repeat(200), |n| n.chars().all(|c| c == 'y')).chars().count(), MAX_OUTPUT_NAME); + // A long name whose output name is taken: the number goes after the output's name, which is + // kept whole (review). + let long_streams = format!("{} streams", "x".repeat(192)); + let fl = TakenNames(&f, &[long_streams.as_str()]); + let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "x".repeat(200)})).unwrap(); + let near = prepare_with(&spec2, &meta2, &fl, ¶ms).unwrap(); + let first = &near.outputs[0].1; + assert!(first.ends_with("x streams 2") && first.chars().count() == MAX_OUTPUT_NAME, "{first}"); + assert_eq!(numbered("a", "", |n| ["a", "a 2"].contains(&n)), "a 3"); + assert_eq!(numbered(&"y".repeat(200), "", |n| n.chars().all(|c| c == 'y')).chars().count(), MAX_OUTPUT_NAME); // A tool whose own option is called `output` keeps it; its outputs keep the tool's name. let own = json!({