Skip to main content

atomic_replace/
lib.rs

1//! Replace a file atomically.
2//!
3//! The new bytes go to a sibling temp file that is renamed over the target, so
4//! a reader, a crash or a full disk never sees a half-written file: the target
5//! holds either the old bytes or the new ones.
6//!
7//! ```no_run
8//! # fn main() -> std::io::Result<()> {
9//! use std::io::Write;
10//!
11//! atomic_replace::write("state.json", b"{}\n")?;
12//!
13//! atomic_replace::Options::new()
14//!     .create_parent(true)
15//!     .durable(false)
16//!     .write_with("cache/index.bin", |file| file.write_all(b"index"))?;
17//! # Ok(())
18//! # }
19//! ```
20
21use std::fs::{self, File, OpenOptions};
22use std::io::{self, Write};
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicU64, Ordering};
25use std::time::{SystemTime, UNIX_EPOCH};
26
27/// Replace `path` with `bytes` using the default [`Options`].
28pub fn write(path: impl AsRef<Path>, bytes: impl AsRef<[u8]>) -> io::Result<()> {
29    Options::new().write(path, bytes)
30}
31
32/// How [`Options::write`] and [`Options::write_with`] replace a file.
33///
34/// The defaults are the safe ones: fsync, keep permissions, keep symlinks,
35/// and do not create missing directories.
36#[derive(Clone, Debug)]
37pub struct Options {
38    durable: bool,
39    preserve_permissions: bool,
40    follow_symlinks: bool,
41    create_parent: bool,
42    #[cfg(unix)]
43    mode: Option<u32>,
44}
45
46impl Default for Options {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl Options {
53    pub fn new() -> Self {
54        Self {
55            durable: true,
56            preserve_permissions: true,
57            follow_symlinks: true,
58            create_parent: false,
59            #[cfg(unix)]
60            mode: None,
61        }
62    }
63
64    /// Fsync the file before the rename and its directory after it (default
65    /// on). Without the file fsync the kernel may record the rename and lose
66    /// the bytes, leaving an empty file after a crash.
67    pub fn durable(mut self, on: bool) -> Self {
68        self.durable = on;
69        self
70    }
71
72    /// Copy an existing target's permissions onto the new file (default on),
73    /// so a 0600 file stays 0600. On Windows this clears the target's
74    /// read-only bit instead, because the rename cannot replace a read-only
75    /// file.
76    pub fn preserve_permissions(mut self, on: bool) -> Self {
77        self.preserve_permissions = on;
78        self
79    }
80
81    /// When the target is a symlink, write the file it points to and keep the
82    /// link (default on). Off replaces the link itself with a plain file.
83    pub fn follow_symlinks(mut self, on: bool) -> Self {
84        self.follow_symlinks = on;
85        self
86    }
87
88    /// Create the target's missing parent directories (default off).
89    pub fn create_parent(mut self, on: bool) -> Self {
90        self.create_parent = on;
91        self
92    }
93
94    /// Unix mode of the new file. An existing target's permissions still win
95    /// while [`preserve_permissions`](Self::preserve_permissions) is on.
96    #[cfg(unix)]
97    pub fn mode(mut self, mode: u32) -> Self {
98        self.mode = Some(mode);
99        self
100    }
101
102    /// Replace `path` with `bytes`.
103    pub fn write(&self, path: impl AsRef<Path>, bytes: impl AsRef<[u8]>) -> io::Result<()> {
104        self.write_with(path, |file| file.write_all(bytes.as_ref()))
105    }
106
107    /// Replace `path` with whatever `fill` writes into the temp file.
108    pub fn write_with<F>(&self, path: impl AsRef<Path>, fill: F) -> io::Result<()>
109    where
110        F: FnOnce(&mut File) -> io::Result<()>,
111    {
112        let path = path.as_ref();
113        if path.file_name().is_none() {
114            return Err(io::Error::new(
115                io::ErrorKind::InvalidInput,
116                format!("{} names no file", path.display()),
117            ));
118        }
119        if self.create_parent {
120            if let Some(dir) = parent(path) {
121                fs::create_dir_all(dir)?;
122            }
123        }
124        let target = if self.follow_symlinks {
125            link_target(path)?
126        } else {
127            path.to_path_buf()
128        };
129        let (tmp, mut file) = self.create_temp(&target)?;
130        let result = self.fill_and_swap(&target, &tmp, &mut file, fill);
131        if result.is_err() {
132            let _ = fs::remove_file(&tmp);
133        }
134        result
135    }
136
137    fn fill_and_swap<F>(
138        &self,
139        target: &Path,
140        tmp: &Path,
141        file: &mut File,
142        fill: F,
143    ) -> io::Result<()>
144    where
145        F: FnOnce(&mut File) -> io::Result<()>,
146    {
147        fill(file)?;
148        file.flush()?;
149        if self.preserve_permissions {
150            keep_permissions(target, tmp)?;
151        }
152        if self.durable {
153            file.sync_all()?;
154        }
155        fs::rename(tmp, target)?;
156        if self.durable {
157            if let Some(dir) = parent(target) {
158                // Best effort: some filesystems (and Windows) refuse to fsync
159                // a directory, and the bytes are already safe by then.
160                let _ = sync_dir(dir);
161            }
162        }
163        Ok(())
164    }
165
166    /// A fresh temp file beside `target`. `create_new` with pid, time and a
167    /// process-wide counter in the name, so two writers never share a file
168    /// and a leftover from a crashed run is never reused.
169    fn create_temp(&self, target: &Path) -> io::Result<(PathBuf, File)> {
170        static COUNTER: AtomicU64 = AtomicU64::new(0);
171        let dir = parent(target).unwrap_or(Path::new("."));
172        let name = target.file_name().unwrap_or_default().to_string_lossy();
173        let mut last = None;
174        for _ in 0..8 {
175            let nanos = SystemTime::now()
176                .duration_since(UNIX_EPOCH)
177                .map(|d| d.as_nanos())
178                .unwrap_or(0);
179            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
180            let tmp = dir.join(format!(".{name}.tmp-{}-{nanos}-{n}", std::process::id()));
181            let mut open = OpenOptions::new();
182            open.write(true).create_new(true);
183            #[cfg(unix)]
184            if let Some(mode) = self.mode {
185                use std::os::unix::fs::OpenOptionsExt;
186                open.mode(mode);
187            }
188            match open.open(&tmp) {
189                Ok(file) => return Ok((tmp, file)),
190                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => last = Some(e),
191                Err(e) => return Err(e),
192            }
193        }
194        Err(last.unwrap_or_else(|| io::Error::other("no free temp file name")))
195    }
196}
197
198/// Fsync a directory so a rename or create inside it survives a crash.
199pub fn sync_dir(dir: impl AsRef<Path>) -> io::Result<()> {
200    File::open(dir)?.sync_all()
201}
202
203/// `Path::parent` returns `Some("")` for a bare file name; that means the
204/// current directory.
205fn parent(path: &Path) -> Option<&Path> {
206    match path.parent() {
207        Some(p) if p.as_os_str().is_empty() => Some(Path::new(".")),
208        other => other,
209    }
210}
211
212/// The file `path` resolves to. `canonicalize` fails on a dangling link (a
213/// dotfile manager's link whose target is not there yet), and the rename then
214/// replaced the link with a plain file; following the links by hand writes the
215/// target and keeps the link. A cycle is an error: replacing one of its links
216/// with a file would silently break the others.
217fn link_target(path: &Path) -> io::Result<PathBuf> {
218    let mut p = path.to_path_buf();
219    // 40: the kernel's own ELOOP limit.
220    for _ in 0..40 {
221        if let Ok(real) = fs::canonicalize(&p) {
222            return Ok(real);
223        }
224        match fs::read_link(&p) {
225            Ok(next) => p = p.parent().unwrap_or(Path::new("")).join(next),
226            Err(_) => return Ok(p),
227        }
228    }
229    Err(io::Error::other(format!(
230        "{}: too many levels of symbolic links",
231        path.display()
232    )))
233}
234
235#[cfg(unix)]
236fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
237    match fs::metadata(target) {
238        Ok(meta) => fs::set_permissions(tmp, meta.permissions()),
239        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
240        Err(e) => Err(e),
241    }
242}
243
244/// `MOVEFILE_REPLACE_EXISTING` cannot replace a read-only file; drop that bit
245/// on the target rather than copying it onto the temp file.
246#[cfg(windows)]
247// Windows-only, so the world-writable risk the lint names for Unix cannot arise here.
248#[allow(clippy::permissions_set_readonly_false)]
249fn keep_permissions(target: &Path, _tmp: &Path) -> io::Result<()> {
250    let Ok(meta) = fs::metadata(target) else {
251        return Ok(());
252    };
253    let mut perms = meta.permissions();
254    if perms.readonly() {
255        perms.set_readonly(false);
256        fs::set_permissions(target, perms)?;
257    }
258    Ok(())
259}
260
261#[cfg(not(any(unix, windows)))]
262fn keep_permissions(_target: &Path, _tmp: &Path) -> io::Result<()> {
263    Ok(())
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn entries(dir: &Path) -> Vec<String> {
271        let mut names: Vec<String> = fs::read_dir(dir)
272            .unwrap()
273            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
274            .collect();
275        names.sort();
276        names
277    }
278
279    #[test]
280    fn creates_and_replaces_without_leftovers() {
281        let dir = tempfile::tempdir().unwrap();
282        let f = dir.path().join("state.json");
283        write(&f, "one").unwrap();
284        assert_eq!(fs::read_to_string(&f).unwrap(), "one");
285        write(&f, "two").unwrap();
286        assert_eq!(fs::read_to_string(&f).unwrap(), "two");
287        assert_eq!(entries(dir.path()), ["state.json"]);
288    }
289
290    #[test]
291    fn failed_fill_keeps_the_old_file_and_removes_the_temp() {
292        let dir = tempfile::tempdir().unwrap();
293        let f = dir.path().join("a");
294        write(&f, "old").unwrap();
295        let err = Options::new()
296            .write_with(&f, |file| {
297                file.write_all(b"half")?;
298                Err(io::Error::other("boom"))
299            })
300            .unwrap_err();
301        assert_eq!(err.to_string(), "boom");
302        assert_eq!(fs::read_to_string(&f).unwrap(), "old");
303        assert_eq!(entries(dir.path()), ["a"]);
304    }
305
306    #[test]
307    fn missing_parent_fails_unless_asked_to_create_it() {
308        let dir = tempfile::tempdir().unwrap();
309        let f = dir.path().join("x/y/z.toml");
310        let err = write(&f, "v").unwrap_err();
311        assert_eq!(err.kind(), io::ErrorKind::NotFound);
312        Options::new().create_parent(true).write(&f, "v").unwrap();
313        assert_eq!(fs::read_to_string(&f).unwrap(), "v");
314    }
315
316    #[test]
317    fn path_without_a_file_name_is_refused() {
318        let err = write("..", "v").unwrap_err();
319        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
320    }
321
322    #[test]
323    fn not_durable_still_replaces() {
324        let dir = tempfile::tempdir().unwrap();
325        let f = dir.path().join("c");
326        Options::new().durable(false).write(&f, "fast").unwrap();
327        assert_eq!(fs::read_to_string(&f).unwrap(), "fast");
328    }
329
330    #[cfg(unix)]
331    mod unix {
332        use super::*;
333        use std::os::unix::fs::{symlink, PermissionsExt};
334
335        fn mode(p: &Path) -> u32 {
336            fs::metadata(p).unwrap().permissions().mode() & 0o777
337        }
338
339        #[test]
340        fn keeps_the_old_mode() {
341            let dir = tempfile::tempdir().unwrap();
342            let f = dir.path().join("secret");
343            fs::write(&f, "old").unwrap();
344            fs::set_permissions(&f, fs::Permissions::from_mode(0o600)).unwrap();
345            write(&f, "new").unwrap();
346            assert_eq!(mode(&f), 0o600);
347        }
348
349        #[test]
350        fn mode_applies_to_a_new_file_and_yields_to_an_existing_one() {
351            let dir = tempfile::tempdir().unwrap();
352            let f = dir.path().join("key");
353            Options::new().mode(0o600).write(&f, "k").unwrap();
354            assert_eq!(mode(&f), 0o600);
355            fs::set_permissions(&f, fs::Permissions::from_mode(0o640)).unwrap();
356            Options::new().mode(0o600).write(&f, "k2").unwrap();
357            assert_eq!(mode(&f), 0o640);
358            Options::new()
359                .mode(0o600)
360                .preserve_permissions(false)
361                .write(&f, "k3")
362                .unwrap();
363            assert_eq!(mode(&f), 0o600);
364        }
365
366        #[test]
367        fn writes_through_a_symlink_and_keeps_it() {
368            let dir = tempfile::tempdir().unwrap();
369            let real = dir.path().join("real.json");
370            let link = dir.path().join("link.json");
371            fs::write(&real, "old").unwrap();
372            symlink("real.json", &link).unwrap();
373            write(&link, "new").unwrap();
374            assert!(fs::symlink_metadata(&link)
375                .unwrap()
376                .file_type()
377                .is_symlink());
378            assert_eq!(fs::read_to_string(&real).unwrap(), "new");
379        }
380
381        #[test]
382        fn creates_the_target_of_a_dangling_symlink() {
383            let dir = tempfile::tempdir().unwrap();
384            let link = dir.path().join("link");
385            symlink("missing", &link).unwrap();
386            write(&link, "made").unwrap();
387            assert!(fs::symlink_metadata(&link)
388                .unwrap()
389                .file_type()
390                .is_symlink());
391            assert_eq!(
392                fs::read_to_string(dir.path().join("missing")).unwrap(),
393                "made"
394            );
395        }
396
397        #[test]
398        fn not_following_replaces_the_link_itself() {
399            let dir = tempfile::tempdir().unwrap();
400            let real = dir.path().join("real");
401            let link = dir.path().join("link");
402            fs::write(&real, "old").unwrap();
403            symlink(&real, &link).unwrap();
404            Options::new()
405                .follow_symlinks(false)
406                .write(&link, "new")
407                .unwrap();
408            assert!(fs::symlink_metadata(&link).unwrap().is_file());
409            assert_eq!(fs::read_to_string(&real).unwrap(), "old");
410        }
411
412        #[test]
413        fn symlink_cycle_ends() {
414            let dir = tempfile::tempdir().unwrap();
415            let a = dir.path().join("a");
416            let b = dir.path().join("b");
417            symlink(&b, &a).unwrap();
418            symlink(&a, &b).unwrap();
419            assert!(write(&a, "v").is_err());
420            assert_eq!(entries(dir.path()), ["a", "b"]);
421        }
422    }
423
424    #[cfg(windows)]
425    #[test]
426    fn replaces_a_read_only_file() {
427        let dir = tempfile::tempdir().unwrap();
428        let f = dir.path().join("ro.json");
429        fs::write(&f, "old").unwrap();
430        let mut perms = fs::metadata(&f).unwrap().permissions();
431        perms.set_readonly(true);
432        fs::set_permissions(&f, perms).unwrap();
433        write(&f, "new").unwrap();
434        assert_eq!(fs::read_to_string(&f).unwrap(), "new");
435    }
436}