Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

CLI convert: refuse to write over the input file unless --in-place (#7437)

Khawar Zamman Wani4f0876958db1
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 03001ab02..69bc1a963 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -15,8 +15,10 @@ pub const USAGE: &str = "\
photocraft-cli: headless PhotoCraft
USAGE:
- photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
+ photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).
+ An <out> that is the <in> file is refused, as the result would replace the original;
+ --in-place allows it.
TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).
--quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless.
--tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as
@@ -69,7 +71,7 @@ struct Subcommand {
}
const SUBCOMMANDS: &[Subcommand] = &[
- Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--tiff-layers"], run: convert },
+ Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--in-place", "--tiff-layers"], run: convert },
Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },
Subcommand {
name: "run",
@@ -239,11 +241,23 @@ fn automation_workspace(args: &Args) -> Result<AuthorizedWorkspace, String> {
.map_err(|error| error.to_string())
}
+/// An output that is the input file itself, however it is spelt (relative, with `./`, through a
+/// hard or symbolic link), would replace the original, and a lossy re-encode can't be undone: it
+/// is refused unless `--in-place` asks for it, as `batch` refuses an `--out` that is its `--in`
+/// folder (#7437).
+fn refuse_overwriting_input(a: &Args, input: &str, output: &str) -> R {
+ if !a.has("--in-place") && photocraft_engine::file_cmds::same_file(input, output) {
+ return Err(format!("{output} is the input file, so the result would replace the original: choose another output, or pass --in-place to overwrite it"));
+ }
+ Ok(())
+}
+
fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R {
let [input, output] = a.positional.as_slice() else {
return Err("convert needs <in> <out>".into());
};
let opts = export_opts(a)?;
+ refuse_overwriting_input(a, input, output)?;
let o = files::open(Path::new(input)).map_err(|e| e.to_string())?;
warn_all(err, &o.warnings);
warn_all(err, &photocraft_engine::type_extra_cmds::missing_font_warnings(&o.document));
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs
index 3c28a8196..b8aa434b3 100644
--- a/apps/photocraft-cli/tests/cli.rs
+++ b/apps/photocraft-cli/tests/cli.rs
@@ -566,6 +566,42 @@ fn batch_refuses_to_write_over_its_inputs() {
assert!(after.iter().zip(&before).all(|(a, b)| a.0 == b.0 && a.1 != b.1), "both inputs replaced");
}
+/// #7437: `convert` to its own input file, however the output is spelt, is refused before
+/// anything is read or written, unless `--in-place` asks for it (as `batch` does, #492).
+#[test]
+fn convert_refuses_to_write_over_its_input() {
+ let d = tmp("convert-in-place");
+ write_png(&d.join("in.png"), 8, 4, 5);
+ let before = std::fs::read(d.join("in.png")).unwrap();
+ let convert = |out: &Path, extra: &[&str]| bin().current_dir(&d).args(["convert", "in.png"]).arg(out).args(extra).output().unwrap();
+ let mut outs = vec![PathBuf::from("in.png"), PathBuf::from("./in.png"), d.join("in.png"), d.join(".").join("in.png")];
+ std::fs::hard_link(d.join("in.png"), d.join("hard.png")).unwrap();
+ outs.push(PathBuf::from("hard.png"));
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(d.join("in.png"), d.join("soft.png")).unwrap();
+ outs.push(PathBuf::from("soft.png"));
+ }
+ for out in &outs {
+ for extra in [&[][..], &["--format", "png"][..], &["--quality", "80"][..]] {
+ let o = convert(out, extra);
+ let err = String::from_utf8_lossy(&o.stderr);
+ assert_eq!(o.status.code(), Some(1), "{} {extra:?}: {err}", out.display());
+ assert!(err.contains("is the input file") && err.contains("--in-place"), "{err}");
+ assert_eq!(std::fs::read(d.join("in.png")).unwrap(), before, "{} {extra:?} changed the original", out.display());
+ }
+ }
+ // Another file converts as before, leaving the original alone.
+ ok(bin().current_dir(&d).args(["convert", "in.png", "out.jpg"]));
+ assert!(d.join("out.jpg").is_file());
+ assert_eq!(std::fs::read(d.join("in.png")).unwrap(), before);
+ // `--in-place` opts in: the result replaces the original, which still opens.
+ ok(bin().current_dir(&d).args(["convert", "in.png", "in.png", "--in-place"]));
+ let (out, _) = ok(bin().current_dir(&d).args(["info", "in.png", "--compact"]));
+ let info: Value = serde_json::from_str(&out).unwrap();
+ assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(8), Some(4)), "{info}");
+}
+
#[test]
fn commands_listing() {
let (out, _) = ok(bin().arg("commands"));