Repository navigation
fix(cli): an option with no value, and a render size that isn't a number, are refused with status 2 (#2917) #3087
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
2803cba
2f00788
4e27098
f62bbc5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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()) | ||||||||||
| } | ||||||||||
|
|
@@ -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); | ||||||||||
| 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()) | ||||||||||
| } | ||||||||||
|
|
@@ -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)?; | ||||||||||
| } | ||||||||||
| } | ||||||||||
|
|
@@ -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 { | ||||||||||
|
|
@@ -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)?; | ||||||||||
|
|
@@ -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), | ||||||||||
|
|
@@ -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, \""] { | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This completeness check only scans
Suggested change
Category: quality
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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:
Suggested change
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 { | ||||||||||
|
|
||||||||||
| 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}"); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sideemits one notice per side that is moved, so--width 100000 --height 8prints 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