use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
pub fn write(path: &Path, contents: impl AsRef<[u8]>) -> io::Result<()> {
let real_path = resolve_write_target(path)?;
let dir = real_path.parent().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "path has no parent directory")
})?;
let file_name = real_path
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"))?;
let temp_path = dir.join(format!("{}.tmp", file_name.to_string_lossy()));
if let Err(e) = write_and_sync(&temp_path, contents.as_ref()) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
if let Err(e) = preserve_mode(&real_path, &temp_path) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
if let Err(e) = fs::rename(&temp_path, &real_path) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
Ok(())
}
fn resolve_write_target(path: &Path) -> io::Result<PathBuf> {
if let Ok(real) = fs::canonicalize(path) {
return Ok(real);
}
let Ok(link_meta) = fs::symlink_metadata(path) else {
return Ok(path.to_path_buf());
};
if !link_meta.file_type().is_symlink() {
return Ok(path.to_path_buf());
}
let raw_target = fs::read_link(path)?;
let link_dir = path.parent().unwrap_or_else(|| Path::new("."));
let resolved_target = if raw_target.is_absolute() {
raw_target
} else {
link_dir.join(raw_target)
};
if let Ok(target_meta) = fs::symlink_metadata(&resolved_target)
&& target_meta.file_type().is_symlink()
{
return Err(io::Error::other(format!(
"\"{}\" points to another symlink (\"{}\") that does not itself \
resolve to a real file. This only follows one level of a \
dangling link chain, to avoid an unbounded chase — nothing \
was written and the symlink was left untouched. Fix the chain \
manually before trying again.",
path.display(),
resolved_target.display(),
)));
}
let target_parent = resolved_target.parent();
let target_parent_exists =
target_parent.is_some_and(|p| fs::metadata(p).is_ok_and(|m| m.is_dir()));
if target_parent_exists {
return Ok(resolved_target);
}
Err(io::Error::other(format!(
"\"{}\" is a symlink pointing to a missing location (\"{}\"); the \
directory it would need to be created in (\"{}\") does not exist. \
Nothing was written and the symlink was left untouched.",
path.display(),
resolved_target.display(),
target_parent
.map(|p| p.display().to_string())
.unwrap_or_else(|| resolved_target.display().to_string()),
)))
}
fn write_and_sync(temp_path: &Path, contents: &[u8]) -> io::Result<()> {
let mut file = File::create(temp_path)?;
file.write_all(contents)?;
file.sync_all()
}
#[cfg(unix)]
fn preserve_mode(existing_path: &Path, temp_path: &Path) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
match fs::metadata(existing_path) {
Ok(meta) => fs::set_permissions(
temp_path,
fs::Permissions::from_mode(meta.permissions().mode()),
),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(not(unix))]
fn preserve_mode(_existing_path: &Path, _temp_path: &Path) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn write_then_read_round_trips() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("config.toml");
write(&path, "hello = 1").expect("write");
assert_eq!(fs::read_to_string(&path).expect("read"), "hello = 1");
}
#[test]
fn overwrite_replaces_contents_and_leaves_no_tmp_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("config.toml");
write(&path, "first").expect("first write");
write(&path, "second").expect("second write");
assert_eq!(fs::read_to_string(&path).expect("read"), "second");
assert!(
!tmp.path().join("config.toml.tmp").exists(),
"no .tmp litter should survive a successful write"
);
}
#[test]
fn existing_contents_survive_a_failed_temp_write() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("config.toml");
fs::write(&path, "original").expect("seed original contents");
fs::create_dir(tmp.path().join("config.toml.tmp")).expect("block the temp path");
let result = write(&path, "new contents");
assert!(result.is_err());
assert_eq!(fs::read_to_string(&path).expect("read"), "original");
}
#[test]
fn no_tmp_file_survives_a_failed_rename() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("blocked");
fs::create_dir(&path).expect("target is a directory");
fs::write(path.join("occupant"), "keeps the directory non-empty").expect("seed occupant");
let result = write(&path, "new contents");
assert!(result.is_err());
assert!(
!tmp.path().join("blocked.tmp").exists(),
"the temp file written before the failed rename must be cleaned up"
);
}
#[cfg(unix)]
#[test]
fn an_existing_files_mode_survives_a_successful_write() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("config.toml");
fs::write(&path, "original").expect("seed original contents");
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
write(&path, "new contents").expect("write");
let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "mode must survive the atomic swap");
}
#[cfg(unix)]
#[test]
fn writing_through_a_symlink_preserves_the_link_and_updates_its_target() {
let tmp = tempfile::tempdir().expect("tempdir");
let real_target = tmp.path().join("real-config.toml");
let link_path = tmp.path().join("config.toml");
fs::write(&real_target, "original").expect("seed original contents");
std::os::unix::fs::symlink(&real_target, &link_path).expect("create symlink");
write(&link_path, "updated").expect("write");
assert!(
fs::symlink_metadata(&link_path)
.expect("symlink_metadata")
.file_type()
.is_symlink(),
"the link itself must survive — only its target's contents change"
);
assert_eq!(
fs::read_to_string(&real_target).expect("read real target"),
"updated",
"the real file the link points at must hold the new contents"
);
}
#[cfg(unix)]
#[test]
fn writing_through_a_dangling_symlink_with_an_existing_target_directory_writes_through() {
let tmp = tempfile::tempdir().expect("tempdir");
let missing_target = tmp.path().join("does-not-exist.toml");
let link_path = tmp.path().join("config.toml");
std::os::unix::fs::symlink(&missing_target, &link_path).expect("create dangling symlink");
write(&link_path, "content").expect("write");
assert!(
fs::symlink_metadata(&link_path)
.expect("symlink_metadata")
.file_type()
.is_symlink(),
"the link must survive — nothing about this case destroys it"
);
assert_eq!(
fs::read_to_string(&missing_target).expect("read the now-created target"),
"content"
);
}
#[cfg(unix)]
#[test]
fn writing_through_a_dangling_symlink_with_a_relative_target_resolves_against_the_links_directory()
{
let tmp = tempfile::tempdir().expect("tempdir");
let sub_dir = tmp.path().join("sub");
fs::create_dir(&sub_dir).expect("create sub dir");
let link_path = sub_dir.join("config.toml");
std::os::unix::fs::symlink("real-config.toml", &link_path)
.expect("create dangling symlink with a relative target");
write(&link_path, "content").expect("write");
assert!(
fs::symlink_metadata(&link_path)
.expect("symlink_metadata")
.file_type()
.is_symlink()
);
assert_eq!(
fs::read_to_string(sub_dir.join("real-config.toml"))
.expect("read the target resolved relative to the link's own directory"),
"content"
);
}
#[cfg(unix)]
#[test]
fn writing_through_a_dangling_symlink_with_a_missing_target_directory_is_refused() {
let tmp = tempfile::tempdir().expect("tempdir");
let missing_target = tmp.path().join("no-such-dir").join("config.toml");
let link_path = tmp.path().join("config.toml");
std::os::unix::fs::symlink(&missing_target, &link_path).expect("create dangling symlink");
let result = write(&link_path, "content");
let err = result.expect_err("must refuse rather than self-heal");
let message = err.to_string();
assert!(
message.contains("no-such-dir"),
"error must name the missing directory: {message:?}"
);
assert!(
fs::symlink_metadata(&link_path)
.expect("symlink_metadata")
.file_type()
.is_symlink(),
"the link must be left exactly as it was"
);
}
#[cfg(unix)]
#[test]
fn writing_through_a_dangling_symlink_chain_is_refused_and_destroys_nothing() {
let tmp = tempfile::tempdir().expect("tempdir");
let link1 = tmp.path().join("link1.toml");
let link2 = tmp.path().join("link2.toml");
let never_exists = tmp.path().join("still-does-not-exist.toml");
std::os::unix::fs::symlink(&never_exists, &link2).expect("create the dangling second link");
std::os::unix::fs::symlink(&link2, &link1)
.expect("create the first link, pointing at link2");
let result = write(&link1, "content");
assert!(result.is_err(), "a dangling chain must not resolve");
assert!(
fs::symlink_metadata(&link1)
.expect("symlink_metadata link1")
.file_type()
.is_symlink(),
"link1 must survive untouched"
);
assert!(
fs::symlink_metadata(&link2)
.expect("symlink_metadata link2")
.file_type()
.is_symlink(),
"link2 must survive untouched too — nothing in the chain is destroyed"
);
assert!(!never_exists.exists());
}
}