From d7bd96660e3fe2cd31765d380887237135698822 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Fri, 22 Jul 2022 22:22:31 +1000 Subject: [PATCH] Fix `CratesToml::append_to_path`: Lock file to avoid race condition Signed-off-by: Jiahao XU --- src/metafiles/v1.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/metafiles/v1.rs b/src/metafiles/v1.rs index 596b9591..79126091 100644 --- a/src/metafiles/v1.rs +++ b/src/metafiles/v1.rs @@ -1,6 +1,7 @@ use std::{ collections::{BTreeMap, BTreeSet}, - fs, io, + fs, + io::{self, Seek}, iter::IntoIterator, path::{Path, PathBuf}, str::FromStr, @@ -74,17 +75,15 @@ impl CratesToml { where Iter: IntoIterator)>, { - let mut c1 = match Self::load_from_path(path.as_ref()) { - Ok(c1) => c1, - Err(CratesTomlParseError::Io(io_err)) if io_err.kind() == io::ErrorKind::NotFound => { - Self::default() - } - Err(err) => return Err(err), - }; + let mut file = FileLock::new_exclusive(create_if_not_exist(path.as_ref())?)?; + let mut c1 = Self::load_from_reader(&mut *file)?; + for (cvs, bins) in iter { c1.insert(cvs, bins); } - c1.write_to_path(path.as_ref())?; + + file.rewind()?; + c1.write_to_file(&mut *file)?; Ok(()) }