Skip to content

Commit 60048ab

Browse files
authored
Rollup merge of #162027 - valentynkit:fs-rename-noreplace, r=joshtriplett
std: add `fs::rename_noreplace` Tracking issue: #161427 Accepted ACP: rust-lang/libs-team#131 ## Summary Add `fs::rename_noreplace`. Unlike `fs::rename`, the destination is never overwritten, instead returns `ErrorKind::AlreadyExists` if `to` already exists. Platform-specific APIs used: - [`renameat2`](https://man7.org/linux/man-pages/man2/renameat2.2.html) with `RENAME_NOREPLACE` flag on Linux and Android - `renamex_np` with `RENAME_EXCL` on Apple - [`MoveFileExW`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw) without the `MOVEFILE_REPLACE_EXISTING` flag on Windows. Extracted functionality into `rename_inner` to avoid duplication for `rename` and `rename_noreplace` - On other Unix platforms and on WASI, and on Linux, Android and Apple when the kernel or the filesystem doesn't support it, `link` followed by `unlink` is used instead. - Platforms with neither return `Unsupported`. Linux and Android case, has different error handling than Apple because the platforms report these conditions differently. On Linux the syscall may not exist at all (`ENOSYS`), and `EINVAL` covers "filesystem doesn't support the flag" and flag misuse (incorrect combinations of flags, as example). On Apple `renamex_np` is called directly, and Darwin use `ENOTSUP` for not supported case, and keeps `EINVAL` only for misuse combinations. > EINVAL An invalid flag was specified in flags. > EINVAL Both RENAME_NOREPLACE and RENAME_EXCHANGE were specified in flags. > EINVAL The filesystem does not support one of the flags in flags. [`renameat2`](https://man7.org/linux/man-pages/man2/renameat2.2.html) ## Open questions 1. `ENOSYS` on Linux and Android could be cached, unlike `EINVAL` case which on the same machine, when using different filesystem may return different result. In this PR I deliberately avoided adding caching to avoid premature optimization, but could add it if you think it worth it. 2. The `link` + `unlink` fallback can't move directories: `link` returns `EPERM`. Should it report `Unsupported` there instead? r? libs
2 parents 0f547a9 + 3fe7406 commit 60048ab

11 files changed

Lines changed: 266 additions & 9 deletions

File tree

‎library/std/src/fs.rs‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3135,6 +3135,76 @@ pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()>
31353135
fs_imp::rename(from.as_ref(), to.as_ref())
31363136
}
31373137

3138+
/// Renames a file or directory to a new name, returning [`AlreadyExists`] if `to` already
3139+
/// exists.
3140+
///
3141+
/// Unlike [`fs::rename`], the destination is never overwritten. The check happens as part of the
3142+
/// same operation, which avoids check-then-rename races.
3143+
///
3144+
/// If the system crashes in the middle, it may be possible to end up with both copies of the file
3145+
/// existing, but it should not be possible to end up with zero copies, or with a half-written file.
3146+
///
3147+
/// This will not work if the new name is on a different mount point.
3148+
///
3149+
/// # Platform-specific behavior
3150+
///
3151+
/// This function currently corresponds to:
3152+
///
3153+
/// * [renameat2] with `RENAME_NOREPLACE` on Linux and Android
3154+
/// * `renamex_np` with `RENAME_EXCL` on Apple platforms
3155+
/// * [MoveFileExW] without the `MOVEFILE_REPLACE_EXISTING` flag, with a fallback to
3156+
/// `SetFileInformationByHandle`, on Windows
3157+
/// * `link` followed by `unlink` on other Unix platforms and on WASI
3158+
/// * Otherwise, this function returns [`Unsupported`]
3159+
///
3160+
/// The `link` and `unlink` fallback is also used at runtime on Linux, Android and Apple platforms
3161+
/// when the kernel or the filesystem does not support the flag, so which of these applies can
3162+
/// differ between filesystems on the same machine.
3163+
///
3164+
/// Note that, this [may change in the future][changes].
3165+
///
3166+
/// [changes]: io#platform-specific-behavior
3167+
/// [renameat2]: https://man7.org/linux/man-pages/man2/renameat2.2.html
3168+
/// [MoveFileExW]: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw
3169+
/// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
3170+
/// [`Unsupported`]: crate::io::ErrorKind::Unsupported
3171+
/// [`fs::rename`]: crate::fs::rename
3172+
///
3173+
/// # Errors
3174+
///
3175+
/// This function will return an error in the following situations, but is not
3176+
/// limited to just these cases:
3177+
///
3178+
/// * `from` does not exist.
3179+
/// * The user lacks permissions to view contents.
3180+
/// * `from` and `to` are on separate filesystems.
3181+
/// * `to` already exists.
3182+
/// * The platform does not support this operation.
3183+
///
3184+
/// # Examples
3185+
///
3186+
/// ```no_run
3187+
/// #![feature(rename_noreplace)]
3188+
/// use std::fs;
3189+
/// use std::io::ErrorKind;
3190+
///
3191+
/// fn main() -> std::io::Result<()> {
3192+
/// // Renames a.txt to b.txt, b.txt does not exist yet.
3193+
/// fs::rename_noreplace("a.txt", "b.txt")?;
3194+
///
3195+
/// // b.txt exists now, so this fails instead of silently overwriting it.
3196+
/// let err = fs::rename_noreplace("c.txt", "b.txt").unwrap_err();
3197+
/// assert_eq!(err.kind(), ErrorKind::AlreadyExists);
3198+
/// Ok(())
3199+
/// }
3200+
/// ```
3201+
#[doc(alias = "renameat2", alias = "renamex_np", alias = "MoveFileEx", alias = "RENAME_NOREPLACE")]
3202+
#[unstable(feature = "rename_noreplace", issue = "161427")]
3203+
#[cfg_attr(not(test), rustc_diagnostic_item = "fs_rename_noreplace")]
3204+
pub fn rename_noreplace<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
3205+
fs_imp::rename_noreplace(from.as_ref(), to.as_ref())
3206+
}
3207+
31383208
/// Copies the contents of one file to another. This function will also
31393209
/// copy the permission bits of the original file to the destination file.
31403210
///

‎library/std/src/fs/tests.rs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2664,6 +2664,98 @@ fn test_rename_symlink() {
26642664
assert_eq!(fs::read_link(&dest).unwrap().as_path(), not_exist);
26652665
}
26662666

2667+
#[test]
2668+
fn test_rename_noreplace() {
2669+
let tmpdir = tmpdir();
2670+
let source_path = tmpdir.join("source_file.txt");
2671+
let target_path = tmpdir.join("target_file.txt");
2672+
2673+
fs::write(&source_path, b"source hello world").unwrap();
2674+
2675+
fs::rename_noreplace(&source_path, &target_path).unwrap();
2676+
assert!(!source_path.exists());
2677+
assert_eq!(fs::read(&target_path).unwrap(), b"source hello world");
2678+
}
2679+
2680+
#[test]
2681+
fn test_rename_noreplace_existing_file() {
2682+
let tmpdir = tmpdir();
2683+
let source_path = tmpdir.join("source_file.txt");
2684+
let target_path = tmpdir.join("target_file.txt");
2685+
2686+
fs::write(&source_path, b"source hello world").unwrap();
2687+
fs::write(&target_path, b"target hello world").unwrap();
2688+
2689+
let err = fs::rename_noreplace(&source_path, &target_path).unwrap_err();
2690+
assert_eq!(err.kind(), ErrorKind::AlreadyExists);
2691+
// Make sure the failed rename left both files untouched.
2692+
assert_eq!(fs::read(&source_path).unwrap(), b"source hello world");
2693+
assert_eq!(fs::read(&target_path).unwrap(), b"target hello world");
2694+
}
2695+
2696+
#[test]
2697+
fn test_rename_noreplace_directory_to_empty_directory() {
2698+
// Renaming a directory over an existing empty directory should fail;
2699+
// plain `rename` would succeed here.
2700+
let tmpdir = tmpdir();
2701+
let source_path = tmpdir.join("source_directory");
2702+
let target_path = tmpdir.join("target_directory");
2703+
2704+
fs::create_dir(&source_path).unwrap();
2705+
fs::create_dir(&target_path).unwrap();
2706+
2707+
let err = fs::rename_noreplace(&source_path, &target_path).unwrap_err();
2708+
assert_matches!(
2709+
err.kind(),
2710+
// A native no-replace rename returns `AlreadyExists`. The `link`/`unlink`
2711+
// fallback cannot rename directories and returns `PermissionDenied`.
2712+
ErrorKind::AlreadyExists | ErrorKind::PermissionDenied,
2713+
"Expected AlreadyExists or PermissionDenied error, got {err}"
2714+
);
2715+
}
2716+
2717+
#[test]
2718+
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple", windows))]
2719+
fn test_rename_noreplace_directory() {
2720+
let tmpdir = tmpdir();
2721+
let source_path = tmpdir.join("source_directory");
2722+
let target_path = tmpdir.join("target_directory");
2723+
2724+
fs::create_dir(&source_path).unwrap();
2725+
fs::write(source_path.join("file.txt"), b"hello world").unwrap();
2726+
2727+
match fs::rename_noreplace(&source_path, &target_path) {
2728+
Ok(()) => {
2729+
assert!(!source_path.exists());
2730+
assert_eq!(fs::read(target_path.join("file.txt")).unwrap(), b"hello world");
2731+
}
2732+
// Without a native no-replace rename (Linux before 3.15), Unix
2733+
// platforms fall back to `link`/`unlink`, and it rejects directories.
2734+
Err(err) if cfg!(unix) && err.kind() == ErrorKind::PermissionDenied => {
2735+
assert!(source_path.exists());
2736+
assert!(!target_path.exists());
2737+
}
2738+
Err(err) => panic!("unexpected error: {err:?}"),
2739+
}
2740+
}
2741+
2742+
#[test]
2743+
fn test_rename_noreplace_symlink() {
2744+
let tmpdir = tmpdir();
2745+
if !got_symlink_permission(&tmpdir) {
2746+
return;
2747+
};
2748+
2749+
let original = tmpdir.join("original");
2750+
let dest = tmpdir.join("dest");
2751+
let not_exist = Path::new("does not exist");
2752+
2753+
symlink_file(not_exist, &original).unwrap();
2754+
fs::rename_noreplace(&original, &dest).unwrap();
2755+
// Make sure that renaming `original` to `dest` preserves the symlink.
2756+
assert_eq!(fs::read_link(&dest).unwrap().as_path(), not_exist);
2757+
}
2758+
26672759
#[test]
26682760
#[cfg(windows)]
26692761
fn test_rename_junction() {

‎library/std/src/sys/fs/hermit.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,10 @@ pub fn rename(_old: &Path, _new: &Path) -> io::Result<()> {
594594
unsupported()
595595
}
596596

597+
pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> {
598+
unsupported()
599+
}
600+
597601
pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> {
598602
unsupported()
599603
}

‎library/std/src/sys/fs/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
7878
with_native_path(old, &|old| with_native_path(new, &|new| imp::rename(old, new)))
7979
}
8080

81+
pub fn rename_noreplace(old: &Path, new: &Path) -> io::Result<()> {
82+
with_native_path(old, &|old| with_native_path(new, &|new| imp::rename_noreplace(old, new)))
83+
}
84+
8185
pub fn remove_dir(path: &Path) -> io::Result<()> {
8286
with_native_path(path, &imp::rmdir)
8387
}

‎library/std/src/sys/fs/motor.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,10 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
324324
moto_rt::fs::rename(old, new).map_err(map_motor_error)
325325
}
326326

327+
pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> {
328+
unsupported()
329+
}
330+
327331
pub fn rmdir(path: &Path) -> io::Result<()> {
328332
let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?;
329333
moto_rt::fs::rmdir(path).map_err(map_motor_error)

‎library/std/src/sys/fs/solid.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,10 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
530530
Ok(())
531531
}
532532

533+
pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> {
534+
unsupported()
535+
}
536+
533537
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
534538
// Solid does not support symlinks
535539
set_perm_nofollow(p, perm)

‎library/std/src/sys/fs/uefi.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,10 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
474474
f.set_file_info(new_info)
475475
}
476476

477+
pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> {
478+
unsupported()
479+
}
480+
477481
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
478482
// UEFI does not support symlinks
479483
set_perm_nofollow(p, perm)

‎library/std/src/sys/fs/unix.rs‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ pub use crate::sys::fs::common::exists;
6969
pub use crate::sys::fs::common::{ExtraHomeDirs, ExtraMediaDirs};
7070
use crate::sys::helpers::run_path_with_cstr;
7171
use crate::sys::time::SystemTime;
72-
#[cfg(all(target_os = "linux", target_env = "gnu"))]
72+
#[cfg(any(target_os = "linux", target_os = "android"))]
7373
use crate::sys::weak::syscall;
7474
#[cfg(target_os = "android")]
7575
use crate::sys::weak::weak;
@@ -1862,6 +1862,59 @@ pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
18621862
cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
18631863
}
18641864

1865+
#[cfg(any(target_os = "linux", target_os = "android"))]
1866+
pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1867+
syscall!(
1868+
fn renameat2(
1869+
olddirfd: c_int,
1870+
oldpath: *const libc::c_char,
1871+
newdirfd: c_int,
1872+
newpath: *const libc::c_char,
1873+
flags: libc::c_uint,
1874+
) -> c_int;
1875+
);
1876+
1877+
// `RENAME_NOREPLACE` is `c_uint` on linux and `c_int` on Android, so casting is needed here.
1878+
let flags = libc::RENAME_NOREPLACE as libc::c_uint;
1879+
let res = cvt(unsafe {
1880+
renameat2(libc::AT_FDCWD, old.as_ptr(), libc::AT_FDCWD, new.as_ptr(), flags)
1881+
});
1882+
1883+
match res {
1884+
Ok(_) => Ok(()),
1885+
Err(err) => match err.raw_os_error() {
1886+
// The kernel predates `renameat2`.
1887+
Some(libc::ENOSYS) => link_then_unlink(old, new),
1888+
// The filesystem does not support `RENAME_NOREPLACE`.
1889+
// `EINVAL` also covers misuse, so report it unchanged unless the fallback found `new`.
1890+
Some(libc::EINVAL) => match link_then_unlink(old, new) {
1891+
Err(fallback) if fallback.raw_os_error() != Some(libc::EEXIST) => Err(err),
1892+
res => res,
1893+
},
1894+
_ => Err(err),
1895+
},
1896+
}
1897+
}
1898+
1899+
#[cfg(target_vendor = "apple")]
1900+
pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1901+
let res = cvt(unsafe { libc::renamex_np(old.as_ptr(), new.as_ptr(), libc::RENAME_EXCL) });
1902+
match res {
1903+
Ok(_) => Ok(()),
1904+
Err(err) => match err.raw_os_error() {
1905+
// The filesystem does not support `RENAME_EXCL`.
1906+
// Unlike Linux, Darwin keeps `EINVAL` for misuse only.
1907+
Some(libc::ENOTSUP) => link_then_unlink(old, new),
1908+
_ => Err(err),
1909+
},
1910+
}
1911+
}
1912+
1913+
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
1914+
pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1915+
link_then_unlink(old, new)
1916+
}
1917+
18651918
pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
18661919
cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
18671920
}
@@ -2062,6 +2115,11 @@ pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
20622115
})))
20632116
}
20642117

2118+
fn link_then_unlink(old: &CStr, new: &CStr) -> io::Result<()> {
2119+
link(old, new)?;
2120+
unlink(old)
2121+
}
2122+
20652123
fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
20662124
use crate::fs::File;
20672125
use crate::sys::fs::common::NOT_FILE_ERROR;

‎library/std/src/sys/fs/unsupported.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,10 @@ pub fn rename(_old: &Path, _new: &Path) -> io::Result<()> {
309309
unsupported()
310310
}
311311

312+
pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> {
313+
unsupported()
314+
}
315+
312316
pub fn set_perm(_p: &Path, perm: FilePermissions) -> io::Result<()> {
313317
match perm.0 {}
314318
}

‎library/std/src/sys/fs/vexos.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ use crate::sys::{unsupported, unsupported_err};
1212
#[path = "unsupported.rs"]
1313
mod unsupported_fs;
1414
pub use unsupported_fs::{
15-
Dir, DirBuilder, FileTimes, canonicalize, link, readlink, remove_dir_all, rename, rmdir,
16-
symlink, unlink,
15+
Dir, DirBuilder, FileTimes, canonicalize, link, readlink, remove_dir_all, rename,
16+
rename_noreplace, rmdir, symlink, unlink,
1717
};
1818

1919
pub use crate::sys::fs::common::{ExtraHomeDirs, ExtraMediaDirs};

0 commit comments

Comments
 (0)