diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 88344574ab..821c9ae7af 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -22,7 +22,7 @@ use serde_json::Value; /// photocraft-cli: headless PhotoCraft #[derive(Parser)] -#[command(name = "photocraft-cli", version = photocraft_engine::build_info::long_version_static(), arg_required_else_help = true)] +#[command(name = "photocraft-cli", version = photocraft_engine::build_info::long_version_static(), propagate_version = true, arg_required_else_help = true)] pub(crate) struct Cli { #[command(subcommand)] pub(crate) command: Command, @@ -250,13 +250,13 @@ pub(crate) struct BatchArgs { pub(crate) struct DropletArgs { /// The droplet to run #[arg(value_name = "FILE.pcdroplet")] - pub(crate) file: String, + pub(crate) file: PathBuf, /// Images and folders to run it on #[arg(value_name = "FILE-OR-DIR", required = true)] - pub(crate) inputs: Vec, + pub(crate) inputs: Vec, /// The folder to write the results to #[arg(long, value_name = "DIR")] - pub(crate) out: Option, + pub(crate) out: Option, } /// List the engine command registry diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index 975e12b70c..3c568f4ad2 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -198,10 +198,15 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> } pub(crate) fn droplet(a: &DropletArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result { - let (file, inputs) = (&a.file, &a.inputs); - let mut p = json!({"droplet": file, "input": inputs}); + // The engine command takes its paths as JSON text, so a path that isn't valid UTF-8 stops here + // with the same exit 1 as `info`'s, not at parsing. + fn text<'a>(path: &'a Path, what: &'static str) -> Result<&'a str> { + path.to_str().ok_or_else(|| CliError::PathNotUtf8 { what, path: path.to_path_buf() }) + } + let inputs = a.inputs.iter().map(|i| text(i, "droplet input")).collect::>>()?; + let mut p = json!({"droplet": text(&a.file, "droplet file")?, "input": inputs}); if let Some(o) = &a.out { - p["output"] = json!(o); + p["output"] = json!(text(o, "--out")?); } let mut s = photocraft_engine::Session::new(); let r = s.execute("file.automate.runDroplet", p)?; diff --git a/apps/photocraft-cli/src/error.rs b/apps/photocraft-cli/src/error.rs index 6b2e0636c6..f44fc22416 100644 --- a/apps/photocraft-cli/src/error.rs +++ b/apps/photocraft-cli/src/error.rs @@ -36,6 +36,9 @@ pub(crate) enum CliError { Naming(String), #[error("{0}")] BatchOption(String), + /// A path the engine command takes as JSON text: the command line took it as a native path. + #[error("{what} must be valid UTF-8: {path:?}")] + PathNotUtf8 { what: &'static str, path: PathBuf }, #[error("{0} file(s) failed")] FilesFailed(usize), #[error("invalid value '{0}' for 'PHOTOCRAFT_GPU': expected '1' or '0'")] diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 894b4d7a34..74dc09e184 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -1422,6 +1422,31 @@ fn a_non_unicode_path_is_taken_and_non_unicode_text_is_a_usage_error() { std::fs::remove_dir_all(d).unwrap(); } +/// RFC-0018 rule 1.5: `droplet` takes its file, inputs and `--out` as native paths, so a name that +/// isn't valid Unicode is parsed rather than refused as a usage error (exit 2). The engine command +/// that runs the droplet takes JSON text, so the run stops there, exit 1 and naming the path, like +/// `info`'s. +#[cfg(unix)] +#[test] +fn droplet_takes_a_non_unicode_path_and_stops_at_the_engine_boundary() { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + let d = tmp("droplet-non-unicode"); + let name = OsStr::from_bytes(b"caf\xe9"); + let utf8 = d.join("rot.pcdroplet"); + for args in [ + vec![OsStr::new("droplet").to_owned(), name.to_owned(), OsStr::new("in.png").to_owned()], + vec![OsStr::new("droplet").to_owned(), utf8.clone().into_os_string(), name.to_owned()], + vec![OsStr::new("droplet").to_owned(), utf8.clone().into_os_string(), OsStr::new("in.png").to_owned(), OsStr::new("--out").to_owned(), name.to_owned()], + ] { + let o = bin().current_dir(&d).args(&args).output().unwrap(); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!((o.status.code(), o.stdout.is_empty()), (Some(1), true), "{args:?}: {err}"); + assert!(err.contains("must be valid UTF-8") && !err.contains("panicked"), "{err}"); + } + std::fs::remove_dir_all(d).unwrap(); +} + /// `batch --actions set.atn`: a Photoshop Actions file plays like an Actions set, and its steps /// PhotoCraft can't play are warned about up front. #[test] @@ -1520,6 +1545,23 @@ fn every_subcommand_help_returns_on_stdout() { } } +/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and +/// return without running it (`mcp` and `serve` would otherwise block on stdin). +#[test] +fn every_subcommand_prints_the_version() { + for sub in SUBCOMMANDS { + for version in ["--version", "-V"] { + let Invoke { code, stdout: out, stderr: err } = invoke(&[sub, version]); + assert_eq!((code, err.as_str()), (0, ""), "{sub} {version}"); + assert!(out.starts_with("photocraft-cli") && out.ends_with('\n') && out.lines().count() == 1, "{sub} {version}: {out}"); + // The same release as the top level's, so a script can read it from any command. + let top = invoke(&[version]).stdout; + let release = top.trim_end().strip_prefix("photocraft-cli ").unwrap(); + assert!(out.contains(release), "{sub} {version}: {out} lacks {release}"); + } + } +} + /// Every subcommand refuses an unknown flag (bare or `=value`) with exit 2, naming it on stderr. #[test] fn every_subcommand_rejects_an_unknown_flag() { diff --git a/book/src/automation/cli.md b/book/src/automation/cli.md index 97540c0ecd..328ca5440e 100644 --- a/book/src/automation/cli.md +++ b/book/src/automation/cli.md @@ -84,7 +84,9 @@ layers because that would lose their group's blending semantics. Paths supplied to the current CLI are ordinary operating-system paths. The CLI does not restrict them to a workspace root. Batch output creates the requested output directory, and save operations may create parent directories. `batch` refuses an output directory that is its input directory (the results would replace the originals) unless `--in-place` is given. Run untrusted action files only in an appropriately isolated account or environment. -CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (`--cmd`, `--params` and `--automation-read-root` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand. +CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (`--cmd`, `--params` and `--automation-read-root` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run`, `batch` and `droplet` hand their paths to engine commands that take JSON text, which still needs UTF-8 paths, so they fail with exit status 1 (`droplet` too: it used to refuse such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version, and so does every subcommand (`photocraft-cli convert --version`); there is no `version` subcommand. + +Follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md), except that `info`, `run`, `batch` and `droplet` need UTF-8 paths (rule 1.5: they take native paths on the command line, but the engine commands they call take JSON text), and the macOS zip has no completions or man pages (rule 1.9, craft-launcher#1422). `mcp` and `serve` reject positional arguments, empty values and options for the wrong mode before starting a server. Explicit control-token flags require `mcp --bridge` or `serve --port` (or