[save] Atomic save: temp + flush + rename, .bak first, kill tests
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
//! Safe saving for Pictor: a file on disk is either the old version or the new one, never half of each.
|
||||
//!
|
||||
//! - [`save_new`] writes a new file and refuses to replace an existing one (the default: `<name>-edited.pdf`).
|
||||
//! - [`save_overwrite`] replaces a file, first keeping the current version as `<file>.bak`.
|
||||
//!
|
||||
//! Both write to a temporary file in the target's folder, flush it to disk, and then rename it into place, so a
|
||||
//! crash, a kill or a full disk at any moment leaves the original as it was. The `.bak` is written the same way, so
|
||||
//! it is always either the previous backup or a full copy of the original.
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SaveError {
|
||||
#[error("A file named {0} already exists.")]
|
||||
Exists(String),
|
||||
#[error("Pictor could not save {path}: {source}")]
|
||||
Io { path: String, source: io::Error },
|
||||
}
|
||||
|
||||
fn io_err(path: &Path) -> impl FnOnce(io::Error) -> SaveError + '_ {
|
||||
move |source| SaveError::Io { path: path.display().to_string(), source }
|
||||
}
|
||||
|
||||
/// The default name for an edited copy: `report.pdf` → `report-edited.pdf`, then `report-edited-2.pdf`, …
|
||||
/// (the first one that does not exist yet).
|
||||
pub fn edited_path(original: &Path) -> PathBuf {
|
||||
let dir = original.parent().unwrap_or(Path::new("."));
|
||||
let stem = original.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let ext = original.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||
let mut n = 1u32;
|
||||
loop {
|
||||
let name = if n == 1 { format!("{stem}-edited{ext}") } else { format!("{stem}-edited-{n}{ext}") };
|
||||
let candidate = dir.join(name);
|
||||
if !candidate.exists() {
|
||||
return candidate;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The backup path of `target`: `doc.pdf` → `doc.pdf.bak`.
|
||||
pub fn bak_path(target: &Path) -> PathBuf {
|
||||
let mut name = target.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(".bak");
|
||||
target.with_file_name(name)
|
||||
}
|
||||
|
||||
fn temp_in(dir: &Path) -> Result<tempfile::NamedTempFile, SaveError> {
|
||||
tempfile::Builder::new().prefix(".pictor-").suffix(".tmp").tempfile_in(dir).map_err(io_err(dir))
|
||||
}
|
||||
|
||||
fn parent(target: &Path) -> &Path {
|
||||
match target.parent() {
|
||||
Some(p) if !p.as_os_str().is_empty() => p,
|
||||
_ => Path::new("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a new file at `target`; fails with [`SaveError::Exists`] if something is already there.
|
||||
pub fn save_new(target: &Path, bytes: &[u8]) -> Result<(), SaveError> {
|
||||
let mut tmp = temp_in(parent(target))?;
|
||||
tmp.write_all(bytes).map_err(io_err(target))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(target))?;
|
||||
tmp.persist_noclobber(target).map_err(|e| {
|
||||
if e.error.kind() == io::ErrorKind::AlreadyExists || target.exists() {
|
||||
SaveError::Exists(target.file_name().unwrap_or_default().to_string_lossy().into_owned())
|
||||
} else {
|
||||
SaveError::Io { path: target.display().to_string(), source: e.error }
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces `target` with `bytes`, keeping the current version as `<target>.bak` first. Returns the `.bak` path
|
||||
/// (which does not exist if `target` did not exist).
|
||||
pub fn save_overwrite(target: &Path, bytes: &[u8]) -> Result<PathBuf, SaveError> {
|
||||
save_overwrite_hooked(target, |f| f.write_all(bytes), || {})
|
||||
}
|
||||
|
||||
/// [`save_overwrite`] with the content written by `write` and a hook called just before the `.bak` is renamed into
|
||||
/// place. Only the save-safety tests use the hooks (they stop the process inside a save and kill it).
|
||||
#[doc(hidden)]
|
||||
pub fn save_overwrite_hooked(
|
||||
target: &Path,
|
||||
write: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
before_bak_rename: impl FnOnce(),
|
||||
) -> Result<PathBuf, SaveError> {
|
||||
let dir = parent(target);
|
||||
let bak = bak_path(target);
|
||||
// 1. The backup: a full copy written beside the target, flushed, then renamed over any older .bak.
|
||||
if target.exists() {
|
||||
let mut tmp = temp_in(dir)?;
|
||||
let mut src = File::open(target).map_err(io_err(target))?;
|
||||
io::copy(&mut src, tmp.as_file_mut()).map_err(io_err(&bak))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(&bak))?;
|
||||
before_bak_rename();
|
||||
tmp.persist(&bak).map_err(|e| SaveError::Io { path: bak.display().to_string(), source: e.error })?;
|
||||
}
|
||||
// 2. The new content, flushed, then renamed over the target in one step.
|
||||
let mut tmp = temp_in(dir)?;
|
||||
write(tmp.as_file_mut()).map_err(io_err(target))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(target))?;
|
||||
tmp.persist(target).map_err(|e| SaveError::Io { path: target.display().to_string(), source: e.error })?;
|
||||
Ok(bak)
|
||||
}
|
||||
Reference in New Issue
Block a user