Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 40 additions & 20 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ ratatui = "0.30.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
uuid = { version = "1.22.0", features = ["v4", "serde"] }

[dev-dependencies]
tempfile = "3"
74 changes: 70 additions & 4 deletions src/core/store/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,76 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let temp_path = parent.join(format!(".tmp-{}", Uuid::new_v4()));
fs::write(&temp_path, bytes)?;

if path.exists() {
// TODO: Replace this with a fully atomic cross-platform strategy if Windows overwrite behavior matters.
fs::remove_file(path)?;
// On Unix, rename(2) atomically overwrites the target — no race window.
// On Windows, rename fails if the target exists, so we remove first.
// This leaves a small crash window on Windows; a future improvement could
// use ReplaceFileW for full atomicity.
#[cfg(unix)]
{
if let Err(e) = fs::rename(&temp_path, path) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
}

fs::rename(temp_path, path)
#[cfg(windows)]
{
if let Err(e) = fs::remove_file(path) {
if e.kind() != io::ErrorKind::NotFound {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
}
if let Err(e) = fs::rename(&temp_path, path) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
}

#[cfg(not(any(unix, windows)))]
{
if let Err(e) = fs::rename(&temp_path, path) {
let _ = fs::remove_file(&temp_path);
return Err(e);
}
}

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use std::fs;

#[test]
fn write_atomic_creates_new_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("new_file.json");

write_atomic(&path, b"hello world").unwrap();

assert_eq!(fs::read_to_string(&path).unwrap(), "hello world");
}

#[test]
fn write_atomic_overwrites_existing_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("existing.json");

fs::write(&path, b"old content").unwrap();
write_atomic(&path, b"new content").unwrap();

assert_eq!(fs::read_to_string(&path).unwrap(), "new content");
}

#[test]
fn write_atomic_creates_parent_dirs() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a").join("b").join("file.json");

write_atomic(&path, b"nested").unwrap();

assert_eq!(fs::read_to_string(&path).unwrap(), "nested");
}
}