Skip to content

Commit bf89d86

Browse files
authored
fix: clean up temp file on failed config save
Switch from manual `.tmp` file to `tempfile::NamedTempFile`
1 parent d72671d commit bf89d86

1 file changed

Lines changed: 5 additions & 7 deletions

File tree

src/config/mod.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -202,17 +202,15 @@ pub(crate) fn trimmed_option(value: Option<&str>) -> Option<&str> {
202202
}
203203

204204
pub fn save_file(path: &Path, config: &Config) -> Result<()> {
205-
if let Some(parent) = path.parent() {
206-
fs::create_dir_all(parent)?;
207-
}
205+
let parent = path.parent().unwrap_or_else(|| Path::new("."));
206+
fs::create_dir_all(parent)?;
208207

209208
let json = serde_json::to_string_pretty(config)?;
210-
let temp_path = path.with_extension("tmp");
211-
let mut file = fs::File::create(&temp_path)?;
209+
let mut file = tempfile::NamedTempFile::new_in(parent)?;
212210
file.write_all(json.as_bytes())?;
213211
file.write_all(b"\n")?;
214-
file.sync_all()?;
215-
fs::rename(&temp_path, path)?;
212+
file.as_file().sync_all()?;
213+
file.persist(path)?;
216214

217215
Ok(())
218216
}

0 commit comments

Comments
 (0)