Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge PR #2544: A save keeps the permissions of the file it replaces

aionggfcab31b76472
diff --cc crates/platform/src/staging.rs
index 1319e468e,5120deae4..aab309299
--- a/crates/platform/src/staging.rs
+++ b/crates/platform/src/staging.rs
@@@ -85,15 -115,14 +115,20 @@@ pub fn write_atomically_with
sync_all: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
use std::io::Write as _;
+ // A read-only file is not replaced. Windows refuses the rename anyway, but on Unix a rename
+ // ignores the target's permissions: the file would be overwritten without a word, and come
+ // out writable (#2658).
+ if std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().readonly()) {
+ return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the file is read-only; save a copy with Save As"));
+ }
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("save");
- let (tmp, file) = create_staging(dir, name, form, suffixes)?;
+ // A file that is replaced keeps its permissions (#1790). Unix modes only: Windows is as before.
+ #[cfg(unix)]
+ let keep = std::fs::metadata(path).ok().map(|m| m.permissions());
+ #[cfg(not(unix))]
+ let keep = None;
+ let (tmp, file) = create_staging_as(dir, name, form, suffixes, keep.as_ref())?;
let result = (|| {
// Closed at the end of the block, before the rename (required on Windows).
{