mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
refactor(cli): reject repeated flags, use clap's --version (#7071)
The behaviour changes decided in step 0 of the issue: - A repeated single-value flag is a usage error (exit 2) instead of the last one winning: args_override_self is gone, and with it the argument scan that found repeats for mcp and serve (#8035). --cmd and --params stay repeatable. - A value starting with '-' was already written --out=-image.png or ./-image.png since the clap port (a flag can't be a value since #8035); this pins it, and that `--filter -1` still works and `--quality -1` is still refused by its range. - The bare `version` subcommand is gone; clap's version flag prints the same `photocraft-cli <long version>` line for --version and now -V too. `help <subcommand>` stays. clap's version wants a &'static str, so build_info gains long_version_static, long_version worked out once in a OnceLock, next to long_version. The desktop app will need the same in step 5. flag_value_forms_and_repeats and top_level_help_version_and_no_arguments now pin the new behaviour; a_value_starting_with_a_dash_is_written_with_equals is new. Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4 files changed
+58
-31
No files matched your search
@@ -1,8 +1,9 @@
|
||||
//! The command line, as clap types. Values stay strings: the handlers check them, with their own
|
||||
//! messages (#7071). A flag a subcommand doesn't take is a usage error, so a typo such as
|
||||
//! `--fromat` can't be silently ignored (#423). A value flag never takes the next flag as its
|
||||
//! value: a value starting with `-` is written `--out=-image.png` (or `./-image.png`); negative
|
||||
//! numbers are kept where they mean something.
|
||||
//! `--fromat` can't be silently ignored (#423), and so is a repeated one: `--quality 80 --quality
|
||||
//! 60` is more likely a mistake than a choice. A value starting with `-` is written
|
||||
//! `--out=-image.png` (or `./-image.png`), so a value flag never takes the next flag as its value;
|
||||
//! negative numbers are kept where they mean something.
|
||||
|
||||
use clap::builder::NonEmptyStringValueParser;
|
||||
use clap::error::ErrorKind;
|
||||
@@ -10,7 +11,7 @@ use clap::{ArgAction, ArgMatches, Args, CommandFactory, FromArgMatches, Parser,
|
||||
|
||||
/// photocraft-cli: headless PhotoCraft
|
||||
#[derive(Parser)]
|
||||
#[command(name = "photocraft-cli", arg_required_else_help = true, args_override_self = true)]
|
||||
#[command(name = "photocraft-cli", version = photocraft_engine::build_info::long_version_static(), arg_required_else_help = true)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
@@ -248,24 +249,18 @@ pub(crate) fn parse(args: &[String]) -> Result<Cli, clap::Error> {
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
match (&mut cli.command, matches.subcommand()) {
|
||||
(Command::Run(r), Some((_, m))) => r.steps = steps(m),
|
||||
(Command::Mcp(_), Some((name, m))) => check_server(cmd.find_subcommand_mut(name), &given, m, "bridge")?,
|
||||
(Command::Serve(_), Some((name, m))) => check_server(cmd.find_subcommand_mut(name), &given, m, "port")?,
|
||||
(Command::Mcp(_), Some((name, m))) => check_server(cmd.find_subcommand_mut(name), m, "bridge")?,
|
||||
(Command::Serve(_), Some((name, m))) => check_server(cmd.find_subcommand_mut(name), m, "port")?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// Refuse `mcp` and `serve` launch options that would otherwise be silently ignored (#8035): a
|
||||
/// repeated one (the last wins everywhere else), a token without the bridge or port that reads it,
|
||||
/// and bridge roots, which belong to the desktop process: accepting them here promises authority
|
||||
/// the bridge cannot set.
|
||||
fn check_server(sub: Option<&mut clap::Command>, given: &[&str], m: &ArgMatches, transport: &str) -> Result<(), clap::Error> {
|
||||
/// token without the bridge or port that reads it, and bridge roots, which belong to the desktop
|
||||
/// process: accepting them here promises authority the bridge cannot set.
|
||||
fn check_server(sub: Option<&mut clap::Command>, m: &ArgMatches, transport: &str) -> Result<(), clap::Error> {
|
||||
let Some(sub) = sub else { return Ok(()) };
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let flags = given.iter().skip(1).take_while(|a| **a != "--").filter(|a| a.starts_with("--"));
|
||||
if let Some(flag) = flags.map(|a| a.split_once('=').map_or(*a, |(k, _)| k)).find(|k| !seen.insert(*k)) {
|
||||
return Err(sub.error(ErrorKind::ArgumentConflict, format!("the argument '{flag}' cannot be used multiple times")));
|
||||
}
|
||||
for (id, flag) in [("control_token", "--control-token"), ("control_token_file", "--control-token-file")] {
|
||||
if m.contains_id(id) && !m.contains_id(transport) {
|
||||
return Err(sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires --{transport}")));
|
||||
|
||||
@@ -40,12 +40,8 @@ pub fn run_os(args: &[std::ffi::OsString], out: &mut dyn Write, err: &mut dyn Wr
|
||||
|
||||
/// Run the CLI. Returns the process exit code (0 ok, 1 failure, 2 usage).
|
||||
pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
|
||||
if matches!(args.first().map(String::as_str), Some("--version" | "version")) {
|
||||
let _ = writeln!(out, "photocraft-cli {}", photocraft_engine::build_info::long_version());
|
||||
return 0;
|
||||
}
|
||||
// Help (`help`, `-h`, `<subcommand> --help`) comes back as an error too, for `out`, exit 0: the
|
||||
// subcommand never runs.
|
||||
// Help and `--version` (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too,
|
||||
// for `out`, exit 0: the subcommand never runs.
|
||||
let cli = match parse(args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
|
||||
@@ -1025,7 +1025,8 @@ fn invoke(args: &[&str]) -> Invoke {
|
||||
|
||||
const SUBCOMMANDS: [&str; 8] = ["convert", "info", "run", "batch", "droplet", "commands", "mcp", "serve"];
|
||||
|
||||
/// Pins top-level dispatch: help goes to stdout (exit 0), no arguments is a usage error on stderr.
|
||||
/// Pins top-level dispatch: help and the version go to stdout (exit 0), no arguments is a usage
|
||||
/// error on stderr. There is no `version` subcommand.
|
||||
#[test]
|
||||
fn top_level_help_version_and_no_arguments() {
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&[]);
|
||||
@@ -1034,11 +1035,14 @@ fn top_level_help_version_and_no_arguments() {
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&[help]);
|
||||
assert_eq!((code, out.is_empty(), err.is_empty()), (0, false, true), "{help}");
|
||||
}
|
||||
for version in ["--version", "version"] {
|
||||
for version in ["--version", "-V"] {
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&[version]);
|
||||
assert_eq!((code, err.as_str()), (0, ""), "{version}");
|
||||
assert!(out.starts_with("photocraft-cli "), "{version}: {out}");
|
||||
assert!(out.starts_with("photocraft-cli ") && out.ends_with('\n') && out.lines().count() == 1, "{version}: {out}");
|
||||
}
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["version"]);
|
||||
assert_eq!((code, out.is_empty()), (2, true));
|
||||
assert!(err.contains("version"), "{err}");
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["frobnicate"]);
|
||||
assert_eq!((code, out.is_empty()), (2, true));
|
||||
assert!(err.contains("frobnicate"), "{err}");
|
||||
@@ -1071,7 +1075,8 @@ fn every_subcommand_rejects_an_unknown_flag() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `--flag=value`, a bare flag given a value, a value flag without one, and repeated flags.
|
||||
/// `--flag=value`, a bare flag given a value, a value flag without one, repeated flags, and values
|
||||
/// that start with `-`.
|
||||
#[test]
|
||||
fn flag_value_forms_and_repeats() {
|
||||
let ids = |out: &str| out.lines().filter_map(|l| l.split_whitespace().next()).map(str::to_owned).collect::<Vec<_>>();
|
||||
@@ -1080,13 +1085,25 @@ fn flag_value_forms_and_repeats() {
|
||||
let spaced = invoke(&["commands", "--filter", "file.new"]).stdout;
|
||||
assert_eq!(eq, spaced);
|
||||
assert!(ids(&eq).contains(&"file.new".to_string()), "{eq}");
|
||||
// The last of a repeated value flag wins, whichever order they come in.
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["commands", "--filter", "zzz-no-match", "--filter", "file.new"]);
|
||||
// A repeated flag is a usage error naming it, more likely a mistake than a choice.
|
||||
for repeat in [&["commands", "--filter", "zzz-no-match", "--filter", "file.new"][..], &["commands", "--json", "--json"][..]] {
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(repeat);
|
||||
assert_eq!((code, out.is_empty()), (2, true), "{repeat:?}");
|
||||
assert!(err.contains(repeat[1]) && err.contains("cannot be used multiple times"), "{repeat:?}: {err}");
|
||||
}
|
||||
let Invoke { code, stderr: err, .. } = invoke(&["convert", "a.png", "b.jpg", "--quality", "80", "--quality", "60"]);
|
||||
assert_eq!(code, 2);
|
||||
assert!(err.contains("--quality"), "{err}");
|
||||
// A value starting with `-` needs `=`; without it the token is a flag, never the value. A
|
||||
// negative number is still a value.
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["commands", "--filter=-zzz-no-match"]);
|
||||
assert_eq!((code, out.as_str()), (0, ""), "{err}");
|
||||
for value in ["-zzz-no-match", "--json"] {
|
||||
let Invoke { code, stdout: out, .. } = invoke(&["commands", "--filter", value]);
|
||||
assert_eq!((code, out.is_empty()), (2, true), "--filter {value}");
|
||||
}
|
||||
let Invoke { code, stderr: err, .. } = invoke(&["commands", "--filter", "-1"]);
|
||||
assert_eq!(code, 0, "{err}");
|
||||
assert_eq!(out, eq);
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["commands", "--filter", "file.new", "--filter", "zzz-no-match"]);
|
||||
assert_eq!(code, 0, "{err}");
|
||||
assert!(out.is_empty(), "{out}");
|
||||
// A bare flag takes no value; a value flag needs one.
|
||||
let Invoke { code, stdout: out, stderr: err } = invoke(&["commands", "--json=1"]);
|
||||
assert_eq!((code, out.is_empty()), (2, true));
|
||||
@@ -1147,3 +1164,15 @@ fn convert_opens_a_raw_at_the_raw_defaults_resolution() {
|
||||
assert_eq!(doc.resolution_dpi, 300.0);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
/// `--out=-image.png` writes `-image.png`; `--out -image.png` is a usage error and writes nothing.
|
||||
#[test]
|
||||
fn a_value_starting_with_a_dash_is_written_with_equals() {
|
||||
let d = tmp("dash-value");
|
||||
let o = bin().current_dir(&d).args(["run", "--new", r#"{"width":4,"height":4}"#, "--out", "-image.png"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
|
||||
ok(bin().current_dir(&d).args(["run", "--new", r#"{"width":4,"height":4}"#, "--out=-image.png"]));
|
||||
assert!(d.join("-image.png").is_file());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
@@ -33,6 +33,12 @@ pub fn long_version() -> String {
|
||||
format_long(VERSION, short_sha(), build_date())
|
||||
}
|
||||
|
||||
/// [`long_version`] worked out once, for a `&'static str` such as clap's `version`.
|
||||
pub fn long_version_static() -> &'static str {
|
||||
static LONG: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
LONG.get_or_init(long_version)
|
||||
}
|
||||
|
||||
fn format_long(version: &str, sha: Option<&str>, date: Option<&str>) -> String {
|
||||
match (sha, date) {
|
||||
(Some(s), Some(d)) => format!("{version} ({s}, {d})"),
|
||||
@@ -58,6 +64,7 @@ mod tests {
|
||||
fn version_is_the_workspace_version() {
|
||||
assert!(!VERSION.is_empty());
|
||||
assert!(long_version().starts_with(VERSION));
|
||||
assert_eq!(long_version_static(), long_version());
|
||||
if let Some(s) = short_sha() {
|
||||
assert!(s.len() <= 9);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user