1use std::io::Write as _;
10use std::path::{Path, PathBuf};
11
12pub fn write_atomically(path: &Path, contents: &[u8]) -> std::io::Result<()> {
19 let target = resolve(path);
20 let temp = temp_path(&target)?;
21 write_and_replace(&temp, &target, contents).inspect_err(|_| {
22 let _ = std::fs::remove_file(&temp);
25 })
26}
27
28fn resolve(path: &Path) -> PathBuf {
32 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
33}
34
35fn temp_path(target: &Path) -> std::io::Result<PathBuf> {
38 let name = target.file_name().ok_or_else(|| {
39 std::io::Error::new(
40 std::io::ErrorKind::InvalidInput,
41 format!("{} names no file to write", target.display()),
42 )
43 })?;
44 let mut temp = std::ffi::OsString::from(".");
45 temp.push(name);
46 temp.push(".tmp");
47 Ok(target.with_file_name(temp))
48}
49
50fn write_and_replace(temp: &Path, target: &Path, contents: &[u8]) -> std::io::Result<()> {
51 let mut file = std::fs::File::create(temp)?;
52 file.write_all(contents)?;
53 file.sync_all()?;
56 drop(file);
57 std::fs::rename(temp, target)?;
58 sync_dir(parent_dir(target))?;
59 Ok(())
60}
61
62fn parent_dir(target: &Path) -> &Path {
65 match target.parent() {
66 Some(dir) if !dir.as_os_str().is_empty() => dir,
67 _ => Path::new("."),
68 }
69}
70
71#[cfg(unix)]
74fn sync_dir(dir: &Path) -> std::io::Result<()> {
75 std::fs::File::open(dir)?.sync_all()
76}
77
78#[cfg(not(unix))]
81fn sync_dir(_dir: &Path) -> std::io::Result<()> {
82 Ok(())
83}
84
85#[cfg(test)]
86pub mod tests {
87 use super::*;
88
89 pub struct TempDir(PathBuf);
93
94 impl TempDir {
95 pub fn new(name: &str) -> Self {
100 let dir = std::env::temp_dir().join(format!("blockworx-{}-{name}", std::process::id()));
101 let _ = std::fs::remove_dir_all(&dir);
102 std::fs::create_dir_all(&dir).unwrap();
103 Self(dir)
104 }
105
106 pub fn join(&self, name: &str) -> PathBuf {
107 self.0.join(name)
108 }
109
110 pub fn path(&self) -> &Path {
111 &self.0
112 }
113 }
114
115 impl Drop for TempDir {
116 fn drop(&mut self) {
117 let _ = std::fs::remove_dir_all(&self.0);
118 }
119 }
120
121 fn read(path: &Path) -> String {
122 std::fs::read_to_string(path).unwrap()
123 }
124
125 #[test]
126 fn it_creates_and_then_overwrites() {
127 let dir = TempDir::new("create-overwrite");
128 let doc = dir.join("doc.json");
129
130 write_atomically(&doc, b"first").unwrap();
131 assert_eq!(read(&doc), "first");
132
133 write_atomically(&doc, b"second").unwrap();
134 assert_eq!(read(&doc), "second");
135 }
136
137 #[test]
138 fn a_successful_write_leaves_no_temp_behind() {
139 let dir = TempDir::new("no-temp");
140 let doc = dir.join("doc.json");
141 write_atomically(&doc, b"content").unwrap();
142
143 let leftovers: Vec<_> = std::fs::read_dir(&dir.0)
144 .unwrap()
145 .map(|e| e.unwrap().file_name())
146 .filter(|name| name != "doc.json")
147 .collect();
148 assert!(leftovers.is_empty(), "left {leftovers:?} behind");
149 }
150
151 #[test]
156 fn a_failed_write_leaves_the_previous_contents_intact() {
157 let dir = TempDir::new("failed-write");
158 let doc = dir.join("doc.json");
159 write_atomically(&doc, b"the good version").unwrap();
160
161 let blocker = dir.join(".doc.json.tmp");
162 std::fs::create_dir(&blocker).unwrap();
163 assert_eq!(
167 temp_path(&resolve(&doc)).unwrap(),
168 std::fs::canonicalize(&blocker).unwrap(),
169 );
170
171 assert!(write_atomically(&doc, b"a doomed longer version").is_err());
172 assert_eq!(read(&doc), "the good version");
173 }
174
175 #[test]
176 fn a_path_naming_no_file_is_an_error() {
177 assert!(write_atomically(Path::new(".."), b"x").is_err());
178 }
179
180 #[cfg(unix)]
183 #[test]
184 fn writing_a_symlink_updates_its_target() {
185 let dir = TempDir::new("symlink");
186 let target = dir.join("real.json");
187 let link = dir.join("link.json");
188 write_atomically(&target, b"before").unwrap();
189 std::os::unix::fs::symlink(&target, &link).unwrap();
190
191 write_atomically(&link, b"after").unwrap();
192
193 assert!(
194 std::fs::symlink_metadata(&link).unwrap().is_symlink(),
195 "the link itself was replaced"
196 );
197 assert_eq!(read(&target), "after");
198 }
199}