From a8be1d11b929ffcc3cfb50880f4d489059fc9a0f Mon Sep 17 00:00:00 2001 From: troido Date: Thu, 5 Mar 2020 18:30:38 +0100 Subject: write files to a tempfile first --- src/persistence.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'src/persistence.rs') diff --git a/src/persistence.rs b/src/persistence.rs index e9ce787..f1ed845 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -1,5 +1,5 @@ -use std::path::PathBuf; +use std::path::{PathBuf, Path}; use std::fs; use std::env; use serde_json; @@ -85,7 +85,7 @@ impl PersistentStorage for FileStorage { path.push(fname); let text = state.to_json().to_string(); // todo: write to a temp file first - fs::write(path, text)?; + write_file_safe(path, text)?; Ok(()) } @@ -97,8 +97,15 @@ impl PersistentStorage for FileStorage { path.push(fname); let text = state.to_json().to_string(); // todo: write to a temp file first - fs::write(path, text)?; + write_file_safe(path, text)?; Ok(()) } } +fn write_file_safe, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> { + let temppath = path.as_ref().with_file_name(format!("tempfile_{}.tmp", rand::random::())); + fs::write(&temppath, contents)?; + fs::rename(&temppath, path)?; + Ok(()) +} + -- cgit