Skip to content
Draft
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
2 changes: 1 addition & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ polyhook = "0.1.12"
same-file = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
thiserror = "2"
toml = "1.1"
uuid = { version = "1", features = ["v4"] }
Expand All @@ -114,4 +115,3 @@ strip = "symbols"

[dev-dependencies]
proptest = "1"
tempfile = "3"
11 changes: 6 additions & 5 deletions core/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Session state persistence and core domain types.
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::Path;
use std::process;

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -48,17 +48,18 @@ pub fn load_state(path: &Path) -> Result<SessionState> {
Ok(serde_json::from_str(&content)?)
}

/// Atomically write `state` to `path` via a PID-suffixed temp file and POSIX `mv`.
/// Atomically write `state` to `path` via a uniquely named temp file in the same
/// directory, renamed over `path`. The temp file is removed if any step fails.
///
/// # Errors
///
/// Returns an error if serialization fails or the write or rename fails.
pub fn save_state(path: &Path, state: &SessionState) -> Result<()> {
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let tmp = dir.join(format!("state.json.tmp.{}", process::id()));
let content = serde_json::to_string_pretty(state)?;
fs::write(&tmp, content)?;
fs::rename(&tmp, path)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
tmp.write_all(content.as_bytes())?;
tmp.persist(path).map_err(|e| e.error)?;
Ok(())
}

Expand Down
Loading