1use 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
30pub(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
40pub 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 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 let _ = fs::remove_file(&tmp);
71 Err(ForgeError::Io(e))
72 }
73 }
74}
75
76pub 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 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}