mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-20 17:06:42 +00:00
fix(cli): retain typed errors through launch option validation
This commit is contained in:
1 parent
35cfb1c6d8
commit
6bbe4cc1df
7 files changed
+53
-22
No files matched your search
@@ -35,7 +35,7 @@ pub(crate) fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result {
|
||||
pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let mut h = Headless::with_workspace(a.automation.workspace()?);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
for d in h.drain_diagnostics() {
|
||||
let _ = writeln!(err, "warning: {d}");
|
||||
@@ -87,7 +87,7 @@ pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
|
||||
}
|
||||
None => {
|
||||
let mut h = Headless::with_workspace(a.automation.workspace()?);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
for d in h.drain_diagnostics() {
|
||||
let _ = writeln!(err, "warning: {d}");
|
||||
@@ -114,7 +114,7 @@ fn live_config(a: &McpArgs) -> Result<photocraft_automation::live::LiveConfig> {
|
||||
config.read_roots.clone_from(&a.automation.automation_read_root);
|
||||
config.write_root = a.automation.automation_write_root.clone();
|
||||
config.launch = std::env::current_exe().ok().and_then(|exe| photocraft_automation::live::launcher(&exe));
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
config.prepare_headless = Some(Box::new(move |h| {
|
||||
policy.apply_to_headless(h);
|
||||
// stdout carries the protocol; the warnings a headless start has go to stderr.
|
||||
|
||||
@@ -110,7 +110,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
}
|
||||
std::fs::create_dir_all(out_dir)?;
|
||||
let mut failures = Vec::new();
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
let mut renderer = policy.create_renderer();
|
||||
for (input, target) in inputs.iter().zip(targets) {
|
||||
let input = Path::new(&input.path);
|
||||
|
||||
@@ -55,7 +55,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
|
||||
let mut seen_warnings = std::collections::HashSet::<String>::new();
|
||||
warn_dedup(err, &o.warnings, &mut seen_warnings);
|
||||
warn_dedup(err, &missing_font_warnings(&o.document), &mut seen_warnings);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
let mut renderer = policy.create_renderer();
|
||||
let ws = match renderer.as_mut() {
|
||||
Some(renderer) => files::save_with_renderer(&o.document, output, a.export.format.as_deref(), &opts, None, Some(&mut **renderer)),
|
||||
@@ -112,7 +112,7 @@ const QUICK_EXPORT_CPU_NOTE: &str = "file.export.quickExport runs on the CPU com
|
||||
pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
let mut h = Headless::trusted_local();
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
// Opening, running commands and exporting can all notice the same missing font:
|
||||
// one `run` invocation reports each warning line at most once.
|
||||
|
||||
@@ -38,6 +38,8 @@ pub(crate) enum CliError {
|
||||
BatchOption(String),
|
||||
#[error("{0} file(s) failed")]
|
||||
FilesFailed(usize),
|
||||
#[error("invalid value '{0}' for 'PHOTOCRAFT_GPU': expected '1' or '0'")]
|
||||
GpuEnvironment(String),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ impl GpuPolicy {
|
||||
/// - Explicit `--no-gpu` disables GPU.
|
||||
/// - Neither flag: `PHOTOCRAFT_GPU` env var (1 = enabled, 0 or empty/unset = disabled).
|
||||
/// Any other nonempty value is rejected.
|
||||
pub(crate) fn from_args(args: &GpuArgs) -> Result<Self, String> {
|
||||
pub(crate) fn from_args(args: &GpuArgs) -> crate::Result<Self> {
|
||||
if args.gpu {
|
||||
return Ok(Self { enabled: true });
|
||||
}
|
||||
@@ -36,21 +36,19 @@ impl GpuPolicy {
|
||||
return Ok(Self { enabled: false });
|
||||
}
|
||||
match std::env::var_os("PHOTOCRAFT_GPU") {
|
||||
Some(val) => {
|
||||
let val = val.to_string_lossy();
|
||||
let trimmed = val.trim();
|
||||
if trimmed.is_empty() || trimmed == "0" {
|
||||
Ok(Self { enabled: false })
|
||||
} else if trimmed == "1" {
|
||||
Ok(Self { enabled: true })
|
||||
} else {
|
||||
Err(format!("invalid value '{trimmed}' for 'PHOTOCRAFT_GPU': expected '1' or '0'"))
|
||||
}
|
||||
}
|
||||
Some(val) => Self::from_environment(&val.to_string_lossy()),
|
||||
None => Ok(Self { enabled: false }),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_environment(value: &str) -> crate::Result<Self> {
|
||||
match value.trim() {
|
||||
"" | "0" => Ok(Self { enabled: false }),
|
||||
"1" => Ok(Self { enabled: true }),
|
||||
other => Err(crate::CliError::GpuEnvironment(other.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply policy to a headless automation session.
|
||||
pub(crate) fn apply_to_headless(&self, h: &mut Headless) {
|
||||
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
|
||||
@@ -110,3 +108,21 @@ impl BandRenderer for DisabledGpuRenderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn environment_policy_keeps_whitespace_and_boolean_semantics() {
|
||||
for value in ["", " ", "0", " 0 "] {
|
||||
assert_eq!(GpuPolicy::from_environment(value).unwrap(), GpuPolicy { enabled: false });
|
||||
}
|
||||
for value in ["1", " 1 "] {
|
||||
assert_eq!(GpuPolicy::from_environment(value).unwrap(), GpuPolicy { enabled: true });
|
||||
}
|
||||
let error = GpuPolicy::from_environment(" invalid ").unwrap_err();
|
||||
assert!(matches!(error, crate::CliError::GpuEnvironment(ref value) if value == "invalid"));
|
||||
assert_eq!(error.to_string(), "invalid value 'invalid' for 'PHOTOCRAFT_GPU': expected '1' or '0'");
|
||||
}
|
||||
}
|
||||
@@ -99,11 +99,11 @@ fn automation_workspace(
|
||||
continue;
|
||||
};
|
||||
let opened = if !root.is_absolute() {
|
||||
Err(format!("`{}` is not an absolute path", root.display()))
|
||||
Err(photocraft_automation::AutomationError::BadRequest(format!("`{}` is not an absolute path", root.display())))
|
||||
} else if read {
|
||||
workspace.with_read_root(&root).map_err(|e| e.to_string())
|
||||
workspace.with_read_root(&root)
|
||||
} else {
|
||||
workspace.with_write_root(&root).map_err(|e| e.to_string())
|
||||
workspace.with_write_root(&root)
|
||||
};
|
||||
match opened {
|
||||
Ok(w) => workspace = w,
|
||||
|
||||
@@ -43,9 +43,14 @@ pub struct AutomationArgs {
|
||||
}
|
||||
|
||||
fn root_path() -> impl TypedValueParser<Value = PathBuf> {
|
||||
OsStringValueParser::new().try_map(|value: OsString| if value.is_empty() { Err("root needs a non-empty directory") } else { Ok(PathBuf::from(value)) })
|
||||
OsStringValueParser::new().try_map(|value: OsString| if value.is_empty() { Err(EmptyRoot) } else { Ok(PathBuf::from(value)) })
|
||||
}
|
||||
|
||||
/// An empty automation root cannot grant a directory capability.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("root needs a non-empty directory")]
|
||||
struct EmptyRoot;
|
||||
|
||||
impl AutomationArgs {
|
||||
/// The roots, opened as capabilities.
|
||||
pub fn workspace(&self) -> Result<AuthorizedWorkspace, AutomationError> {
|
||||
@@ -155,6 +160,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_root_retains_its_usage_error_message() {
|
||||
use clap::Parser;
|
||||
let error = RootCli::try_parse_from(["test", "--automation-read-root="]).err().unwrap();
|
||||
assert_eq!(error.kind(), ErrorKind::ValueValidation);
|
||||
assert!(error.to_string().contains("root needs a non-empty directory"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_unicode_root_paths_are_preserved_without_lossy_conversion() {
|
||||
|
||||
Reference in new issue
Block a user