Skip to main content

utf8_forge/
writer.rs

1//! Crash-safe persistence (`DESIGN.md §7`).
2//!
3//! Never truncate-then-write: every overwrite goes through a temp file in the
4//! same directory + `fs::rename`, so a crash mid-write leaves either the old
5//! or the new content, never neither (invariant #6). Backups copy the
6//! original bytes *before* the rename, mirroring the tree structure under
7//! `--backup-dir`.
8
9use std::fs;
10use std::io::Write;
11use std::path::{Path, PathBuf};
12use std::process;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use crate::error::ForgeError;
16
17/// Monotonic-enough uniqueness source for temp names (pid + wall nanos).
18fn unique_suffix() -> String {
19    let nanos = SystemTime::now()
20        .duration_since(UNIX_EPOCH)
21        .map(|d| d.as_nanos())
22        .unwrap_or(0);
23    format!("{}-{}", process::id(), nanos)
24}
25
26/// Atomically replace `path` with `bytes`.
27///
28/// The temp file is created in the destination's parent directory (same
29/// volume, so rename is atomic), fsynced, given the original's permissions,
30/// then renamed over the destination. Temp leftovers are cleaned up on error.
31pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ForgeError> {
32    let parent = path.parent().unwrap_or(Path::new("."));
33    let file_name = path
34        .file_name()
35        .map(|n| n.to_string_lossy().into_owned())
36        .unwrap_or_else(|| "output".to_string());
37    let tmp = parent.join(format!(".utf8-forge-tmp-{}-{}", unique_suffix(), file_name));
38
39    let write_result = (|| -> std::io::Result<()> {
40        let mut f = fs::File::create(&tmp)?;
41        f.write_all(bytes)?;
42        f.sync_all()?;
43        drop(f);
44        // Preserve the original file's permissions when replacing it.
45        if let Ok(meta) = fs::metadata(path) {
46            let _ = fs::set_permissions(&tmp, meta.permissions());
47        }
48        fs::rename(&tmp, path)?;
49        Ok(())
50    })();
51
52    match write_result {
53        Ok(()) => Ok(()),
54        Err(e) => {
55            // Best-effort cleanup of the temp file; the original is intact.
56            let _ = fs::remove_file(&tmp);
57            Err(ForgeError::Io(e))
58        }
59    }
60}
61
62/// Copy the original bytes of `path` into `backup_dir`, mirroring the
63/// tree structure relative to `root`.
64///
65/// Called *before* the converted bytes are renamed into place, so the backup
66/// always holds the pre-conversion content and stays replayable.
67pub fn backup_original(
68    root: &Path,
69    path: &Path,
70    backup_dir: &Path,
71    original: &[u8],
72) -> Result<(), ForgeError> {
73    let rel = path.strip_prefix(root).map_err(|_| {
74        ForgeError::Io(std::io::Error::new(
75            std::io::ErrorKind::InvalidInput,
76            format!(
77                "file {} is not under root {}",
78                path.display(),
79                root.display()
80            ),
81        ))
82    })?;
83    let target: PathBuf = backup_dir.join(rel);
84    if let Some(parent) = target.parent() {
85        fs::create_dir_all(parent)?;
86    }
87    atomic_write(&target, original)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use std::fs;
94
95    #[test]
96    fn atomic_write_replaces_content_and_cleans_up_temps() {
97        let dir = tempfile::tempdir().unwrap();
98        let p = dir.path().join("a.txt");
99        fs::write(&p, b"old").unwrap();
100
101        atomic_write(&p, b"new-bytes").unwrap();
102        assert_eq!(fs::read(&p).unwrap(), b"new-bytes");
103
104        let leftovers: Vec<_> = fs::read_dir(dir.path())
105            .unwrap()
106            .filter_map(|e| e.ok())
107            .filter(|e| e.file_name().to_string_lossy().starts_with(".utf8-forge-tmp"))
108            .collect();
109        assert!(leftovers.is_empty(), "temp files must be renamed away");
110    }
111
112    #[test]
113    fn atomic_write_creates_file_when_missing() {
114        let dir = tempfile::tempdir().unwrap();
115        let p = dir.path().join("sub").join("b.txt");
116        // Parent does not exist → io error, original "missing" state preserved.
117        assert!(atomic_write(&p, b"x").is_err());
118        let p2 = dir.path().join("c.txt");
119        atomic_write(&p2, b"x").unwrap();
120        assert_eq!(fs::read(&p2).unwrap(), b"x");
121    }
122
123    #[test]
124    fn backup_mirrors_relative_structure() {
125        let root = tempfile::tempdir().unwrap();
126        let backup = tempfile::tempdir().unwrap();
127        let src = root.path().join("GameServer").join("Channel.cpp");
128        fs::create_dir_all(src.parent().unwrap()).unwrap();
129        fs::write(&src, b"original").unwrap();
130
131        backup_original(root.path(), &src, backup.path(), b"original").unwrap();
132        let backed = backup.path().join("GameServer").join("Channel.cpp");
133        assert_eq!(fs::read(&backed).unwrap(), b"original");
134    }
135
136    #[test]
137    fn backup_rejects_path_outside_root() {
138        let root = tempfile::tempdir().unwrap();
139        let backup = tempfile::tempdir().unwrap();
140        let outside = tempfile::tempdir().unwrap();
141        let src = outside.path().join("x.cpp");
142        fs::write(&src, b"x").unwrap();
143        let res = backup_original(root.path(), &src, backup.path(), b"x");
144        assert!(res.is_err());
145    }
146}