Skip to main content

agentmux_remote/
rename.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A rename that never replaces what is already at the new name.
5//!
6//! `std::fs::rename` replaces an existing destination on every platform, so "check that the name is free, then
7//! rename" lets something created in between be replaced, and its content is gone. [`rename_no_replace`] makes
8//! the check and the rename one step:
9//!
10//! - Linux: `renameat2` with `RENAME_NOREPLACE`.
11//! - macOS: `renamex_np` with `RENAME_EXCL`.
12//! - Windows: `MoveFileExW` without `MOVEFILE_REPLACE_EXISTING`.
13//!
14//! An old kernel, or a filesystem that has no such rename (NFS, some FUSE mounts, FAT and exFAT volumes on
15//! macOS), is renamed in steps whose first one takes the new name and fails if it is taken:
16//!
17//! - A folder: an empty folder is made at the new name, and the folder is renamed over it. A rename over a
18//!   folder that got something in it meanwhile fails, so nothing put there is lost.
19//! - Anything else: a hard link is made at the new name, then the old name is removed.
20//! - Where hard links can't be made either: an empty file is made at the new name, exclusively, and the file
21//!   is renamed over it. Whatever was there already, and whatever anything that does not overwrite files
22//!   creates there meanwhile, is kept. Only a program that overwrites that empty file in the instant before
23//!   the rename loses what it wrote: such a filesystem has nothing that closes that last gap.
24//!
25//! Either way the caller gets `AlreadyExists` for a name that is taken, and the person is told the name
26//! already exists.
27//!
28//! srv renames local files through this too, so a host and this computer follow one rule.
29
30use std::io;
31use std::path::Path;
32
33/// Rename `from` to `to`, failing with `AlreadyExists` instead of replacing an existing `to` (a file, a
34/// folder, even an empty one, or a link, even a dangling one).
35pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
36    #[cfg(windows)]
37    {
38        move_no_replace(from, to)
39    }
40    #[cfg(unix)]
41    {
42        match one_step(from, to) {
43            Some(result) => result,
44            None => in_steps(from, to),
45        }
46    }
47}
48
49#[cfg(windows)]
50fn move_no_replace(from: &Path, to: &Path) -> io::Result<()> {
51    use std::os::windows::ffi::OsStrExt;
52    // Declared here rather than taken from a crate: the helper stays std and libc only.
53    #[link(name = "kernel32")]
54    extern "system" {
55        fn MoveFileExW(existing: *const u16, new: *const u16, flags: u32) -> i32;
56    }
57    let wide = |p: &Path| -> Vec<u16> { p.as_os_str().encode_wide().chain(std::iter::once(0)).collect() };
58    let (f, t) = (wide(from), wide(to));
59    // Flags 0: without MOVEFILE_REPLACE_EXISTING an existing destination fails with ERROR_ALREADY_EXISTS,
60    // which std maps to AlreadyExists.
61    // SAFETY: both buffers are NUL-terminated UTF-16 that outlive the call.
62    if unsafe { MoveFileExW(f.as_ptr(), t.as_ptr(), 0) } == 0 {
63        return Err(io::Error::last_os_error());
64    }
65    Ok(())
66}
67
68#[cfg(any(target_os = "linux", target_os = "macos"))]
69fn c_path(p: &Path) -> io::Result<std::ffi::CString> {
70    use std::os::unix::ffi::OsStrExt;
71    Ok(std::ffi::CString::new(p.as_os_str().as_bytes())?)
72}
73
74/// The system's own no-replace rename. `None` where this kernel or this filesystem has none.
75#[cfg(target_os = "linux")]
76fn one_step(from: &Path, to: &Path) -> Option<io::Result<()>> {
77    // The kernel's value, written out: libc does not name it for every C library.
78    const RENAME_NOREPLACE: libc::c_uint = 1;
79    let (f, t) = match (c_path(from), c_path(to)) {
80        (Ok(f), Ok(t)) => (f, t),
81        (Err(e), _) | (_, Err(e)) => return Some(Err(e)),
82    };
83    // The system call itself rather than the C library's wrapper, which glibc has only from 2.28 on.
84    // SAFETY: both pointers are NUL-terminated strings that outlive the call.
85    let r = unsafe {
86        libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, f.as_ptr(), libc::AT_FDCWD, t.as_ptr(), RENAME_NOREPLACE)
87    };
88    if r == 0 {
89        return Some(Ok(()));
90    }
91    let err = io::Error::last_os_error();
92    match err.raw_os_error() {
93        // A kernel before 3.15, or a filesystem without RENAME_NOREPLACE.
94        Some(libc::ENOSYS) | Some(libc::EINVAL) => None,
95        _ => Some(Err(err)),
96    }
97}
98
99#[cfg(target_os = "macos")]
100fn one_step(from: &Path, to: &Path) -> Option<io::Result<()>> {
101    let (f, t) = match (c_path(from), c_path(to)) {
102        (Ok(f), Ok(t)) => (f, t),
103        (Err(e), _) | (_, Err(e)) => return Some(Err(e)),
104    };
105    // SAFETY: both pointers are NUL-terminated strings that outlive the call.
106    if unsafe { libc::renamex_np(f.as_ptr(), t.as_ptr(), libc::RENAME_EXCL) } == 0 {
107        return Some(Ok(()));
108    }
109    let err = io::Error::last_os_error();
110    match err.raw_os_error() {
111        // A filesystem without RENAME_EXCL (FAT and exFAT, some network volumes).
112        Some(libc::ENOTSUP) | Some(libc::EINVAL) => None,
113        _ => Some(Err(err)),
114    }
115}
116
117#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
118fn one_step(_from: &Path, _to: &Path) -> Option<io::Result<()>> {
119    None
120}
121
122/// The rename where the system has no one-step one: the new name is taken first, by a step that fails if it
123/// is taken already (the module's doc says which, and what each keeps).
124#[cfg(unix)]
125fn in_steps(from: &Path, to: &Path) -> io::Result<()> {
126    // Not followed: a link to a folder is a link, and is renamed as a file is.
127    if std::fs::symlink_metadata(from)?.is_dir() {
128        return dir_by_claim(from, to);
129    }
130    match by_link(from, to) {
131        // The name is taken, or there is nothing to rename: the answer, whatever the filesystem can do.
132        Err(e) if matches!(e.kind(), io::ErrorKind::AlreadyExists | io::ErrorKind::NotFound) => Err(e),
133        // No hard link could be made here (the filesystem has none, or this user may not link this file).
134        // Any other failure shows again below, as the claim's own or the rename's.
135        Err(_) => by_placeholder(from, to),
136        Ok(()) => Ok(()),
137    }
138}
139
140/// A file (or a link, or anything that is not a folder) by a hard link at the new name, which fails if the
141/// name is taken, then the old name's removal.
142#[cfg(unix)]
143fn by_link(from: &Path, to: &Path) -> io::Result<()> {
144    std::fs::hard_link(from, to)?;
145    if let Err(e) = std::fs::remove_file(from) {
146        // Both names now: take the new one away again rather than leave the file under two.
147        let _ = std::fs::remove_file(to);
148        return Err(e);
149    }
150    Ok(())
151}
152
153/// A folder by an empty folder made at the new name, which fails if the name is taken, and a rename over
154/// it. A rename over a folder that is no longer empty fails, so what was put in it meanwhile stays.
155#[cfg(unix)]
156fn dir_by_claim(from: &Path, to: &Path) -> io::Result<()> {
157    std::fs::create_dir(to)?;
158    std::fs::rename(from, to).map_err(|e| {
159        // Only an empty folder goes: one that was filled meanwhile is someone else's now.
160        let _ = std::fs::remove_dir(to);
161        match e.raw_os_error() {
162            Some(libc::ENOTEMPTY) | Some(libc::EEXIST) => io::Error::new(io::ErrorKind::AlreadyExists, e),
163            _ => e,
164        }
165    })
166}
167
168/// A file by an empty file made at the new name, exclusively, which fails if the name is taken, and a
169/// rename over it. For a filesystem with neither a no-replace rename nor hard links.
170#[cfg(unix)]
171fn by_placeholder(from: &Path, to: &Path) -> io::Result<()> {
172    use std::os::unix::fs::MetadataExt;
173    let claim = std::fs::OpenOptions::new().write(true).create_new(true).open(to)?;
174    // Still the empty file made here, and not something written or moved over it since.
175    let still_the_claim = || match (claim.metadata(), std::fs::symlink_metadata(to)) {
176        (Ok(made), Ok(there)) => made.len() == 0 && made.dev() == there.dev() && made.ino() == there.ino(),
177        _ => false,
178    };
179    if !still_the_claim() {
180        return Err(io::Error::new(io::ErrorKind::AlreadyExists, "the new name was taken meanwhile"));
181    }
182    std::fs::rename(from, to).inspect_err(|_| {
183        if still_the_claim() {
184            let _ = std::fs::remove_file(to);
185        }
186    })
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use std::fs;
193    use std::sync::{Arc, Barrier};
194
195    type Rename = fn(&Path, &Path) -> io::Result<()>;
196
197    /// Every way a file is renamed on this platform: the whole function, and on Unix each of the steps it
198    /// falls back to, which no filesystem a test runs on would reach.
199    fn file_ways() -> Vec<(&'static str, Rename)> {
200        let mut ways: Vec<(&'static str, Rename)> = vec![("rename_no_replace", rename_no_replace)];
201        #[cfg(unix)]
202        ways.extend([
203            ("in_steps", in_steps as Rename),
204            ("by_link", by_link as Rename),
205            ("by_placeholder", by_placeholder as Rename),
206        ]);
207        ways
208    }
209
210    fn dir_ways() -> Vec<(&'static str, Rename)> {
211        let mut ways: Vec<(&'static str, Rename)> = vec![("rename_no_replace", rename_no_replace)];
212        #[cfg(unix)]
213        ways.extend([("in_steps", in_steps as Rename), ("dir_by_claim", dir_by_claim as Rename)]);
214        ways
215    }
216
217    #[test]
218    fn a_file_moves_to_a_free_name_with_its_content() {
219        for (way, rename) in file_ways() {
220            let dir = tempfile::tempdir().unwrap();
221            let (a, b) = (dir.path().join("a"), dir.path().join("b"));
222            fs::write(&a, "one").unwrap();
223            rename(&a, &b).unwrap_or_else(|e| panic!("{way}: {e}"));
224            assert!(!a.exists(), "{way}");
225            assert_eq!(fs::read_to_string(&b).unwrap(), "one", "{way}");
226        }
227    }
228
229    #[test]
230    fn a_taken_name_is_refused_and_both_files_keep_their_content() {
231        for (way, rename) in file_ways() {
232            let dir = tempfile::tempdir().unwrap();
233            let (a, b) = (dir.path().join("a"), dir.path().join("b"));
234            fs::write(&a, "one").unwrap();
235            fs::write(&b, "two").unwrap();
236            let err = rename(&a, &b).unwrap_err();
237            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
238            assert_eq!(fs::read_to_string(&a).unwrap(), "one", "{way}");
239            assert_eq!(fs::read_to_string(&b).unwrap(), "two", "{way}");
240        }
241    }
242
243    #[test]
244    fn a_file_is_not_renamed_over_a_folder_even_an_empty_one() {
245        for (way, rename) in file_ways() {
246            let dir = tempfile::tempdir().unwrap();
247            let (a, b) = (dir.path().join("a"), dir.path().join("b"));
248            fs::write(&a, "one").unwrap();
249            fs::create_dir(&b).unwrap();
250            let err = rename(&a, &b).unwrap_err();
251            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
252            assert!(a.is_file() && b.is_dir(), "{way}");
253        }
254    }
255
256    #[test]
257    fn a_missing_file_is_not_found_and_leaves_nothing_at_the_new_name() {
258        for (way, rename) in file_ways() {
259            let dir = tempfile::tempdir().unwrap();
260            let (a, b) = (dir.path().join("a"), dir.path().join("b"));
261            let err = rename(&a, &b).unwrap_err();
262            assert_eq!(err.kind(), io::ErrorKind::NotFound, "{way}: {err}");
263            assert!(fs::symlink_metadata(&b).is_err(), "{way}: something was left at the new name");
264        }
265    }
266
267    #[test]
268    fn a_folder_moves_with_what_is_in_it_and_never_over_another_folder() {
269        for (way, rename) in dir_ways() {
270            let dir = tempfile::tempdir().unwrap();
271            let (a, b, c) = (dir.path().join("a"), dir.path().join("b"), dir.path().join("c"));
272            fs::create_dir(&a).unwrap();
273            fs::write(a.join("inside"), "one").unwrap();
274            // An empty folder is in the way as much as a full one: a plain rename would replace it.
275            fs::create_dir(&b).unwrap();
276            let err = rename(&a, &b).unwrap_err();
277            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
278            assert!(a.join("inside").is_file() && b.is_dir(), "{way}");
279
280            rename(&a, &c).unwrap_or_else(|e| panic!("{way}: {e}"));
281            assert!(!a.exists(), "{way}");
282            assert_eq!(fs::read_to_string(c.join("inside")).unwrap(), "one", "{way}");
283        }
284    }
285
286    #[cfg(unix)]
287    #[test]
288    fn a_link_stays_a_link_and_a_dangling_link_takes_its_name() {
289        use std::os::unix::fs::symlink;
290        // Not through the empty file: a link made that way is what the test's filesystem never needs.
291        for (way, rename) in [("rename_no_replace", rename_no_replace as Rename), ("by_link", by_link as Rename)] {
292            let dir = tempfile::tempdir().unwrap();
293            let (a, b, link, dangling) =
294                (dir.path().join("a"), dir.path().join("b"), dir.path().join("link"), dir.path().join("dangling"));
295            fs::write(&a, "one").unwrap();
296            symlink(&a, &link).unwrap();
297            symlink(dir.path().join("nowhere"), &dangling).unwrap();
298
299            let err = rename(&a, &dangling).unwrap_err();
300            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
301            assert!(fs::symlink_metadata(&dangling).unwrap().file_type().is_symlink(), "{way}");
302
303            rename(&link, &b).unwrap_or_else(|e| panic!("{way}: {e}"));
304            assert!(fs::symlink_metadata(&b).unwrap().file_type().is_symlink(), "{way}");
305            assert_eq!(fs::read_to_string(&a).unwrap(), "one", "{way}");
306        }
307    }
308
309    #[cfg(unix)]
310    #[test]
311    fn a_folder_filled_while_it_is_renamed_over_keeps_what_was_put_in_it() {
312        // The claim's own folder, filled before the rename: the state a rename in steps can meet.
313        let dir = tempfile::tempdir().unwrap();
314        let (a, b) = (dir.path().join("a"), dir.path().join("b"));
315        fs::create_dir(&a).unwrap();
316        fs::create_dir(&b).unwrap();
317        fs::write(b.join("theirs"), "two").unwrap();
318        let err = fs::rename(&a, &b).unwrap_err();
319        assert!(
320            matches!(err.raw_os_error(), Some(libc::ENOTEMPTY) | Some(libc::EEXIST)),
321            "a rename over a folder with something in it must fail: {err}"
322        );
323        assert_eq!(fs::read_to_string(b.join("theirs")).unwrap(), "two");
324    }
325
326    /// Two renames to one new name, started together, many times over: one wins, the other is told the name
327    /// is taken, and each file's content is where its rename's answer says it is.
328    #[test]
329    fn two_renames_to_one_name_started_together_have_one_winner_and_lose_nothing() {
330        for (way, rename) in file_ways() {
331            let dir = tempfile::tempdir().unwrap();
332            for round in 0..100 {
333                let (a, b, to) = (dir.path().join("a"), dir.path().join("b"), dir.path().join(format!("to{round}")));
334                fs::write(&a, "one").unwrap();
335                fs::write(&b, "two").unwrap();
336                let start = Arc::new(Barrier::new(2));
337                let run = |from: std::path::PathBuf| {
338                    let (start, to) = (start.clone(), to.clone());
339                    std::thread::spawn(move || {
340                        start.wait();
341                        rename(&from, &to)
342                    })
343                };
344                let (ra, rb) = (run(a.clone()), run(b.clone()));
345                let (ra, rb) = (ra.join().unwrap(), rb.join().unwrap());
346                let (won, lost, lost_at, lost_text, won_text) = match (&ra, &rb) {
347                    (Ok(()), Err(e)) => (&a, e, &b, "two", "one"),
348                    (Err(e), Ok(())) => (&b, e, &a, "one", "two"),
349                    other => panic!("{way} round {round}: exactly one must win: {other:?}"),
350                };
351                assert_eq!(lost.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {lost}");
352                assert!(!won.exists(), "{way} round {round}: the winner's old name is still there");
353                assert_eq!(fs::read_to_string(&to).unwrap(), won_text, "{way} round {round}");
354                assert_eq!(fs::read_to_string(lost_at).unwrap(), lost_text, "{way} round {round}");
355                fs::remove_file(lost_at).unwrap();
356            }
357        }
358    }
359
360    /// A file made at the new name while a rename to it is under way: whichever comes first, the other is
361    /// refused, and the file that was made is never replaced.
362    #[test]
363    fn a_file_made_at_the_new_name_while_a_rename_is_under_way_is_never_replaced() {
364        for (way, rename) in file_ways() {
365            let dir = tempfile::tempdir().unwrap();
366            for round in 0..100 {
367                let (a, to) = (dir.path().join("a"), dir.path().join(format!("to{round}")));
368                fs::write(&a, "renamed").unwrap();
369                let start = Arc::new(Barrier::new(2));
370                let renamer = {
371                    let (start, a, to) = (start.clone(), a.clone(), to.clone());
372                    std::thread::spawn(move || {
373                        start.wait();
374                        rename(&a, &to)
375                    })
376                };
377                let maker = {
378                    let (start, to) = (start.clone(), to.clone());
379                    std::thread::spawn(move || {
380                        use std::io::Write;
381                        start.wait();
382                        fs::OpenOptions::new().write(true).create_new(true).open(&to)?.write_all(b"made")
383                    })
384                };
385                let (renamed, made) = (renamer.join().unwrap(), maker.join().unwrap());
386                match (&renamed, &made) {
387                    (Ok(()), Err(e)) => {
388                        assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {e}");
389                        assert_eq!(fs::read_to_string(&to).unwrap(), "renamed", "{way} round {round}");
390                        assert!(!a.exists(), "{way} round {round}");
391                    }
392                    (Err(e), Ok(())) => {
393                        assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {e}");
394                        assert_eq!(fs::read_to_string(&to).unwrap(), "made", "{way} round {round}");
395                        assert_eq!(fs::read_to_string(&a).unwrap(), "renamed", "{way} round {round}");
396                    }
397                    other => panic!("{way} round {round}: exactly one must get the name: {other:?}"),
398                }
399            }
400        }
401    }
402
403    #[test]
404    fn two_folders_renamed_to_one_name_together_have_one_winner_and_keep_their_files() {
405        for (way, rename) in dir_ways() {
406            let dir = tempfile::tempdir().unwrap();
407            for round in 0..50 {
408                let (a, b, to) = (dir.path().join("a"), dir.path().join("b"), dir.path().join(format!("to{round}")));
409                for (d, text) in [(&a, "one"), (&b, "two")] {
410                    fs::create_dir(d).unwrap();
411                    fs::write(d.join("inside"), text).unwrap();
412                }
413                let start = Arc::new(Barrier::new(2));
414                let run = |from: std::path::PathBuf| {
415                    let (start, to) = (start.clone(), to.clone());
416                    std::thread::spawn(move || {
417                        start.wait();
418                        rename(&from, &to)
419                    })
420                };
421                let (ra, rb) = (run(a.clone()), run(b.clone()));
422                let (ra, rb) = (ra.join().unwrap(), rb.join().unwrap());
423                let (lost, lost_at, lost_text, won_text) = match (&ra, &rb) {
424                    (Ok(()), Err(e)) => (e, &b, "two", "one"),
425                    (Err(e), Ok(())) => (e, &a, "one", "two"),
426                    other => panic!("{way} round {round}: exactly one must win: {other:?}"),
427                };
428                assert_eq!(lost.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {lost}");
429                assert_eq!(fs::read_to_string(to.join("inside")).unwrap(), won_text, "{way} round {round}");
430                assert_eq!(fs::read_to_string(lost_at.join("inside")).unwrap(), lost_text, "{way} round {round}");
431                fs::remove_dir_all(lost_at).unwrap();
432            }
433        }
434    }
435}