Skip to main content

utf8_forge/
writer.rs

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