1use std::fs;
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use std::process;
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::time::{SystemTime, UNIX_EPOCH};
28
29use crate::error::ForgeError;
30
31pub(crate) fn unique_suffix() -> String {
34 static SEQUENCE: AtomicU64 = AtomicU64::new(0);
35 let nanos = SystemTime::now()
36 .duration_since(UNIX_EPOCH)
37 .map(|d| d.as_nanos())
38 .unwrap_or(0);
39 let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
40 format!("{}-{nanos}-{sequence}", process::id())
41}
42
43pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ForgeError> {
49 let parent = path
50 .parent()
51 .filter(|p| !p.as_os_str().is_empty())
52 .unwrap_or(Path::new("."));
53 let tmp = parent.join(format!(".utf8-forge-tmp-{}", unique_suffix()));
57 let mut f = fs::File::create_new(&tmp)?;
58
59 let write_result = (|| -> std::io::Result<()> {
60 f.write_all(bytes)?;
61 match fs::metadata(path) {
64 Ok(meta) => f.set_permissions(meta.permissions())?,
65 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
66 Err(e) => return Err(e),
67 }
68 f.sync_all()?;
69 drop(f);
70 fs::rename(&tmp, path)?;
71 if let Ok(dir) = fs::File::open(parent) {
75 let _ = dir.sync_all();
76 }
77 Ok(())
78 })();
79
80 match write_result {
81 Ok(()) => Ok(()),
82 Err(e) => {
83 let _ = fs::remove_file(&tmp);
85 Err(ForgeError::Io(e))
86 }
87 }
88}
89
90pub fn backup_original(
96 root: &Path,
97 path: &Path,
98 backup_dir: &Path,
99 original: &[u8],
100) -> Result<(), ForgeError> {
101 let rel = path.strip_prefix(root).map_err(|_| {
102 ForgeError::Io(std::io::Error::new(
103 std::io::ErrorKind::InvalidInput,
104 format!(
105 "file {} is not under root {}",
106 path.display(),
107 root.display()
108 ),
109 ))
110 })?;
111 let target: PathBuf = backup_dir.join(rel);
112 if let Some(parent) = target.parent() {
113 fs::create_dir_all(parent)?;
114 }
115 atomic_write(&target, original)
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use std::fs;
122
123 #[test]
124 fn atomic_write_replaces_content_and_cleans_up_temps() {
125 let dir = tempfile::tempdir().unwrap();
126 let p = dir.path().join("a.txt");
127 fs::write(&p, b"old").unwrap();
128
129 atomic_write(&p, b"new-bytes").unwrap();
130 assert_eq!(fs::read(&p).unwrap(), b"new-bytes");
131
132 let leftovers: Vec<_> = fs::read_dir(dir.path())
133 .unwrap()
134 .filter_map(|e| e.ok())
135 .filter(|e| {
136 e.file_name()
137 .to_string_lossy()
138 .starts_with(".utf8-forge-tmp")
139 })
140 .collect();
141 assert!(leftovers.is_empty(), "temp files must be renamed away");
142 }
143
144 #[test]
145 fn atomic_write_creates_file_when_missing() {
146 let dir = tempfile::tempdir().unwrap();
147 let p = dir.path().join("sub").join("b.txt");
148 assert!(atomic_write(&p, b"x").is_err());
150 let p2 = dir.path().join("c.txt");
151 atomic_write(&p2, b"x").unwrap();
152 assert_eq!(fs::read(&p2).unwrap(), b"x");
153 }
154
155 #[test]
156 fn failed_rename_cleans_up_temp_and_keeps_destination() {
157 let dir = tempfile::tempdir().unwrap();
158 let destination = dir.path().join("occupied");
159 fs::create_dir(&destination).unwrap();
160 fs::write(destination.join("original"), b"old").unwrap();
161
162 assert!(atomic_write(&destination, b"replacement").is_err());
163 assert_eq!(fs::read(destination.join("original")).unwrap(), b"old");
164 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
165 }
166
167 #[test]
168 fn concurrent_writes_produce_complete_content_without_temp_leftovers() {
169 let dir = tempfile::tempdir().unwrap();
170 let path = dir.path().join("shared.cpp");
171 std::thread::scope(|scope| {
172 let handles: Vec<_> = (0..16u8)
173 .map(|value| {
174 let path = &path;
175 scope.spawn(move || atomic_write(path, &vec![value; 4096]))
176 })
177 .collect();
178 for handle in handles {
179 handle.join().unwrap().unwrap();
180 }
181 });
182 let bytes = fs::read(&path).unwrap();
183 assert_eq!(bytes.len(), 4096);
184 assert!(bytes[0] < 16);
185 assert!(bytes.iter().all(|byte| *byte == bytes[0]));
186 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
187 }
188
189 #[test]
190 fn backup_mirrors_relative_structure() {
191 let root = tempfile::tempdir().unwrap();
192 let backup = tempfile::tempdir().unwrap();
193 let src = root.path().join("GameServer").join("Channel.cpp");
194 fs::create_dir_all(src.parent().unwrap()).unwrap();
195 fs::write(&src, b"original").unwrap();
196
197 backup_original(root.path(), &src, backup.path(), b"original").unwrap();
198 let backed = backup.path().join("GameServer").join("Channel.cpp");
199 assert_eq!(fs::read(&backed).unwrap(), b"original");
200 }
201
202 #[test]
203 fn backup_rejects_path_outside_root() {
204 let root = tempfile::tempdir().unwrap();
205 let backup = tempfile::tempdir().unwrap();
206 let outside = tempfile::tempdir().unwrap();
207 let src = outside.path().join("x.cpp");
208 fs::write(&src, b"x").unwrap();
209 let res = backup_original(root.path(), &src, backup.path(), b"x");
210 assert!(res.is_err());
211 }
212}