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
162 changes: 148 additions & 14 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ fn usage() -> ExitCode {
ExitCode::from(2)
}

/// 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> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(|s| s.as_str())
}
Expand Down Expand Up @@ -210,6 +212,86 @@ fn is_project(path: &str) -> bool {
rustgis_engine::project::opens_as_project(path)
}

/// The options that take exactly one value. Left out: `--allow` (checked by [`Strict::from_args`],
/// just before), `--attach` (its port is optional) and the `--threads=N` form, which has no separate
/// value. `--threads`, `--image` ([`ask_pictures`]) and `mcp-register`'s `--client`, `--name` and
/// `--port` keep their checks further on, as guards for what a value may be.
const VALUE_FLAGS: &[&str] = &[
"--project",
"--data",
"--cmd",
"--save",
"--plugin",
"--registry",
"--worldview",
"--worldview-detail",
"--basemap",
"--tiles",
"--width",
"--height",
"--dpi",
"--provider",
"--model",
"--base-url",
"--trace",
"--account",
"--remove-account",
"--size",
"--canvas",
"--at",
"--token-file",
"--timeout",
"--threads",
"--image",
"--client",
"--name",
"--port",
];

/// Refuses an option from [`VALUE_FLAGS`] with no value, an empty one, or another option where the
/// value goes (`run --save --cmd x` would save a project named `--cmd`), and a `render` size that
/// isn't a finite number above 0. Every occurrence is checked, as `--data` and `--cmd` repeat.
fn check_values(cmd: &str, args: &[String]) -> Result<(), String> {
for (i, flag) in args.iter().enumerate() {
if !VALUE_FLAGS.contains(&flag.as_str()) {
continue;
}
let value = match args.get(i + 1).map(String::as_str) {
None | Some("") => return Err(format!("{cmd} {flag}: expected a value")),
Some(next) if next.starts_with("--") => return Err(format!("{cmd} {flag}: expected a value, found the option {next}")),
Some(value) => value,
};
if cmd == "render"
&& matches!(flag.as_str(), "--width" | "--height" | "--dpi")
&& !value.parse::<f64>().is_ok_and(|v| v.is_finite() && v > 0.0)
{
return Err(format!("{cmd} {flag} {value}: expected a positive number"));
}
}
Ok(())
}

/// A `render` size in points (pixels at 96 DPI): `--width` or `--height`, else `default`, kept
/// within 16 to 8000. One moved is said, as a notice that is also printed. [`check_values`] has
/// seen that a given one is a positive number.
fn side(s: &mut Session, args: &[String], name: &str, default: f64) -> f64 {
let (Some(given), Some(text)) = (num(args, name), opt(args, name)) else { return default };
let kept = given.clamp(16.0, 8000.0);
let which = if kept > given {
"least"
} else if kept < given {
"most"
} else {
return kept;
};
let mark = s.notice_mark();
s.notify(format!("{name} {text}: using {kept} points, the {which} a side takes (16 to 8000)"), false);

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.

side emits one notice per side that is moved, so --width 100000 --height 8 prints two notices. Each names its flag, so this reads fine. AGENTS.md asks for one notice per kind with a count, though, so either combine the two sides into one line, or say in the PR why separate lines are right here.

Category: quality

for n in s.notices_since(mark) {
eprintln!("rustgis-cli: {}", n.text);
}
kept
}

fn num(args: &[String], name: &str) -> Option<f64> {
opt(args, name).and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite())
}
Expand All @@ -232,10 +314,8 @@ fn open_inputs(s: &mut Session, strict: Option<&Strict>, args: &[String]) -> Res
if let Some(p) = opt(args, "--project") {
load(s, strict, p)?;
}
for (i, a) in args.iter().enumerate() {
if a == "--data"
&& let Some(p) = args.get(i + 1)
{
for (a, p) in args.iter().zip(args.iter().skip(1)) {
if a == "--data" {
load(s, strict, p)?;
}
}
Expand Down Expand Up @@ -846,15 +926,18 @@ fn cli() -> ExitCode {
return ExitCode::from(2);
}
};
// Before plugins load or anything is read or downloaded.
if let Err(e) = check_values(cmd, &args) {
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}");
}
}
for (i, a) in args.iter().enumerate() {
if a == "--plugin"
&& let Some(p) = args.get(i + 1)
{
for (a, p) in args.iter().zip(args.iter().skip(1)) {
if a == "--plugin" {
let loaded =
rustgis_engine::plugins::Package::from_path(std::path::Path::new(p)).and_then(|pkg| rustgis_engine::plugins::load(pkg, p));
if let Err(e) = loaded {
Expand Down Expand Up @@ -1028,8 +1111,8 @@ fn cli() -> ExitCode {
if let Some(u) = opt(&args, "--tiles") {
run(&mut s, "map.addTiles", json!({"url": u}))?;
}
let w = num(&args, "--width").unwrap_or(1600.0).clamp(16.0, 8000.0);
let h = num(&args, "--height").unwrap_or(900.0).clamp(16.0, 8000.0);
let w = side(&mut s, &args, "--width", 1600.0);
let h = side(&mut s, &args, "--height", 900.0);
s.view_size = (w, h);
if !is_project(input) {
run(&mut s, "map.zoomFull", Value::Null)?;
Expand Down Expand Up @@ -1064,10 +1147,8 @@ fn cli() -> ExitCode {
s.stoppable = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
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)
{
for (a, c) in args.iter().zip(args.iter().skip(1)) {
if a == "--cmd" {
let (id, p) = match c.split_once('=') {
Some((id, json)) => (id, serde_json::from_str(json).map_err(|e| format!("{id}: bad JSON: {e}"))?),
None => (c.as_str(), Value::Null),
Expand Down Expand Up @@ -1166,6 +1247,59 @@ mod tests {
list.iter().map(|a| a.to_string()).collect()
}

#[test]
fn check_values_refuses_a_missing_value_an_option_in_its_place_and_a_bad_size() {
let check = |list: &[&str]| check_values(list.first().copied().unwrap_or(""), &args(list));
for (list, said) in [
(&["run", "--save"][..], "run --save: expected a value"),
(&["run", "--save", ""], "run --save: expected a value"),
(&["run", "--save", "--cmd", "x"], "run --save: expected a value, found the option --cmd"),
(&["run", "--data", "a.geojson", "--data"], "run --data: expected a value"),
(&["run", "--plugin"], "run --plugin: expected a value"),
(&["run", "--threads"], "run --threads: expected a value"),
(&["ask", "x", "--image"], "ask --image: expected a value"),
(&["mcp-register", "--client", "--name", "x"], "mcp-register --client: expected a value, found the option --name"),
(&["mcp-register", "--name"], "mcp-register --name: expected a value"),
(&["mcp-register", "--port"], "mcp-register --port: expected a value"),
(&["mcp", "--attach", "5000", "--timeout"], "mcp --timeout: expected a value"),
(&["render", "a", "b.png", "--width", "abc"], "render --width abc: expected a positive number"),
(&["render", "a", "b.png", "--height", "1e400"], "render --height 1e400: expected a positive number"),
(&["render", "a", "b.png", "--dpi", "0"], "render --dpi 0: expected a positive number"),
(&["render", "a", "b.png", "--dpi", "-5"], "render --dpi -5: expected a positive number"),
(&["render", "a", "b.png", "--width", "NaN"], "render --width NaN: expected a positive number"),
] {
assert_eq!(check(list).unwrap_err(), said);
}
// Well-formed input, an option that isn't this check's, a lone `--attach`, a value with one dash,
// and a size where the subcommand doesn't read one.
for list in [
&["run", "--save", "out.rgis", "--cmd", "gp.threads", "--cmd", "gp.threads"][..],
&["render", "a", "b.png", "--width", "64.5", "--dpi", "96"],
&["logo", "l.png", "--canvas", "10x10", "--at", "-5,-5"],
&["mcp", "--attach"],
&["run", "--threads=4"],
&["run", "--allow"],
&["run", "--width", "abc"],
] {
assert_eq!(check(list), Ok(()), "{list:?}");
}
}

#[test]
fn every_option_read_with_opt_is_checked_by_check_values() {
let source = include_str!("main.rs");
let mut missing = Vec::new();
for call in ["opt(&args, \"", "opt(args, \""] {

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.

This completeness check only scans opt( calls. num( calls read values too, and the test won't notice a new num(&args, "--flag") that is missing from VALUE_FLAGS. Today every num call (--dpi) is already listed, so this is a gap for later, not a current failure. Adding the num( patterns closes it:

Suggested change
for call in ["opt(&args, \"", "opt(args, \""] {
for call in ["opt(&args, \"", "opt(args, \"", "num(&args, \"", "num(args, \""] {

Category: quality

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.

This PR adds a second way to read a value flag that the scan misses: side(&mut s, &args, "--width", …) passes the flag name to side, which calls num/opt with a variable, so a new side(…, "--flag", …) call missing from VALUE_FLAGS passes this test. Both --width and --height are listed today, so this is a gap for later, not a current failure. The earlier thread's num( patterns don't cover it. Adding the side( pattern alongside them closes it:

Suggested change
for call in ["opt(&args, \"", "opt(args, \""] {
for call in ["opt(&args, \"", "opt(args, \"", "num(&args, \"", "side(&mut s, &args, \""] {

Category: quality

for part in source.split(call).skip(1) {
let flag = format!("--{}", part.trim_start_matches('-').split('"').next().unwrap_or(""));
if !VALUE_FLAGS.contains(&flag.as_str()) {
missing.push(flag);
}
}
}
assert!(missing.is_empty(), "read with opt but not in VALUE_FLAGS: {missing:?}");
}

/// An environment with no keys.
fn bare() -> Environment {
fn config(provider: &str) -> Config {
Expand Down
141 changes: 141 additions & 0 deletions apps/rustgis-cli/tests/integration/flag_values.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
//! A flag that takes a value and gets none, and a `render` size that isn't a number, are refused
//! with status 2 instead of being ignored (#2917).

use std::path::PathBuf;
use std::process::{Command, Output};

/// A temporary folder the program runs in, removed even when an assertion fails.
struct TempDir(PathBuf);

impl TempDir {
fn new(name: &str) -> TempDir {
let dir = std::env::temp_dir().join(format!("rustgis-cli-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
}

impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}

fn cli(dir: &TempDir, args: &[&str]) -> Output {
// The program's settings, plugins, data and cache folders are the test's own, so no installed
// plugin or setting of the person running the test is read, and `RUSTGIS_WORLDVIEW` doesn't
// choose a view to download. (`--no-plugins` would sit where `render` and `logo` read their
// first argument.)
Command::new(env!("CARGO_BIN_EXE_rustgis-cli"))
.current_dir(&dir.0)
.env("RUSTGIS_CONFIG_DIR", dir.0.join("config"))
.env("RUSTGIS_PLUGINS_DIR", dir.0.join("plugins"))
.env("RUSTGIS_APP_DATA_DIR", dir.0.join("data"))
.env("RUSTGIS_CACHE_DIR", dir.0.join("cache"))
.env_remove("RUSTGIS_WORLDVIEW")
.args(args)
.output()
.unwrap()
}

fn said(out: &Output) -> String {
String::from_utf8_lossy(&out.stderr).into_owned()
}

#[test]
fn a_flag_without_its_value_is_refused_not_ignored() {
let dir = TempDir::new("flag-values");
let cases: [(&[&str], &str); 11] = [
(&["run", "--cmd", "gp.threads", "--save"], "run --save: expected a value"),
(&["run", "--cmd", "gp.threads", "--save", "--cmd", "gp.threads"], "run --save: expected a value, found the option --cmd"),
(&["run", "--data"], "run --data: expected a value"),
(&["run", "--cmd"], "run --cmd: expected a value"),
(&["run", "--plugin"], "run --plugin: expected a value"),
(&["run", "--worldview"], "run --worldview: expected a value"),
(&["run", "--save", ""], "run --save: expected a value"),
(&["render", "a.geojson", "o.png", "--basemap"], "render --basemap: expected a value"),
(&["logo", "l.png", "--size"], "logo --size: expected a value"),
(&["mcp", "--attach", "5000", "--timeout"], "mcp --timeout: expected a value"),
(&["plugins", "list", "--registry"], "plugins --registry: expected a value"),
];
for (args, want) in cases {
let out = cli(&dir, args);
let err = said(&out);
assert_eq!(out.status.code(), Some(2), "{args:?}: {err}");
assert!(err.contains(want), "{args:?}: {err}");
}
// The flag that followed `--save` was never taken as the file to save.
assert!(!dir.0.join("--cmd").exists(), "a project was saved as --cmd");
}

#[test]
fn the_flags_with_a_check_further_on_are_refused_up_front_too() {
let dir = TempDir::new("flag-values-late");
// These once passed the up-front check: `mcp-register` refused them with status 1 after
// plugins loaded, and `--threads` and `--image` only after plugins loaded and a worldview
// may have been downloaded.
let cases: [(&[&str], &str); 9] = [
(&["mcp-register", "--client"], "mcp-register --client: expected a value"),
(&["mcp-register", "--name"], "mcp-register --name: expected a value"),
(&["mcp-register", "--port"], "mcp-register --port: expected a value"),
(&["mcp-register", "--client", "--name", "x"], "mcp-register --client: expected a value, found the option --name"),
(&["run", "--threads"], "run --threads: expected a value"),
(&["render", "a.geojson", "o.png", "--threads"], "render --threads: expected a value"),
(&["ask", "hello", "--threads", "--yes"], "ask --threads: expected a value, found the option --yes"),
(&["ask", "hello", "--image"], "ask --image: expected a value"),
(&["mcp", "--attach", "5000", "--threads"], "mcp --threads: expected a value"),
];
for (args, want) in cases {
let out = cli(&dir, args);
let err = said(&out);
assert_eq!(out.status.code(), Some(2), "{args:?}: {err}");
assert!(err.contains(want), "{args:?}: {err}");
}
}

#[test]
fn a_dimension_that_is_not_a_positive_number_is_refused() {
let dir = TempDir::new("dimensions");
for flag in ["--width", "--height", "--dpi"] {
for bad in ["abc", "NaN", "inf", "1e400", "0", "-5"] {
let out = cli(&dir, &["render", "in.geojson", "out.png", flag, bad]);
let err = said(&out);
assert_eq!(out.status.code(), Some(2), "{flag} {bad}: {err}");
assert!(err.contains(&format!("render {flag} {bad}: expected a positive number")), "{flag} {bad}: {err}");
}
}
assert!(!dir.0.join("out.png").exists());
}

#[test]
fn well_formed_flags_render_and_say_nothing() {
let dir = TempDir::new("render-clean");
std::fs::write(
dir.0.join("pt.geojson"),
r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#,
)
.unwrap();
let out = cli(&dir, &["render", "pt.geojson", "out.png", "--worldview", "default", "--width", "64", "--height", "64", "--dpi", "96"]);
let err = said(&out);
assert!(out.status.success(), "{err}");
assert!(dir.0.join("out.png").exists());
assert!(!err.contains("expected a value") && !err.contains("positive number") && !err.contains("a side takes"), "{err}");
}

#[test]
fn a_side_past_its_limit_is_said() {
let dir = TempDir::new("side-limit");
std::fs::write(
dir.0.join("pt.geojson"),
r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#,
)
.unwrap();
// 100000 pixels wide is limited to 8000, and the program says so; 8 is raised to 16.
let out =
cli(&dir, &["render", "pt.geojson", "out.png", "--worldview", "default", "--width", "100000", "--height", "8", "--dpi", "48"]);
let err = said(&out);
assert!(out.status.success(), "{err}");
assert!(err.contains("rustgis-cli: --width 100000: using 8000 points, the most a side takes (16 to 8000)"), "{err}");
assert!(err.contains("rustgis-cli: --height 8: using 16 points, the least a side takes (16 to 8000)"), "{err}");
}
1 change: 1 addition & 0 deletions apps/rustgis-cli/tests/integration/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Consolidated integration tests (one binary per crate to cut link time in CI).

mod flag_values;
mod memory_override;
mod reproducible_exports;
mod saved_secrets;
Expand Down
6 changes: 6 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ tools and their parameters. See [Installation](installation.md) for the CLI pack

`render <data|project> <out.png>` opens a data file or saved project and exports its map.
It defaults to 1600 × 900 pixels at 96 DPI; `--width`, `--height` and `--dpi` change those.
A `--width` or `--height` outside 16 to 8000 points (pixels at 96 DPI; a higher `--dpi` draws more pixels) is moved to the nearest limit, and it says so.
A data file is zoomed to its full extent; a project keeps its saved view.
`--tiles` accepts an XYZ template, vector tiles or a MapLibre-style address.

Expand All @@ -43,6 +44,11 @@ cores), as [`gp.threads`](user-guide/analysis.md#analysis-workflows) sets it. Wi
open app's own setting holds, so `--threads` is refused there. Without it, a run takes
the computer's cores, up to 16.

An option that takes a value (`--save`, `--data`, `--cmd`, `--width` and the rest) and gets none, or
gets another option in its place, is refused with status 2 before anything runs, and so is a
`--width`, `--height` or `--dpi` of `render` that isn't a number above 0. A value that starts with
`--` is read as an option: put `./` in front of a file with such a name.

## Chaining commands

`run` starts with an empty project. `--sample` loads the World Atlas sample, `--project <path>`
Expand Down
Loading