Fix err handling in CratesToml::append_to_path

Make it more robust to `io::Error`: Only create a `Self::default()` if
fails to open the file.

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-07-21 19:54:45 +10:00
parent 31d9716d28
commit 0157a594e6
No known key found for this signature in database
GPG key ID: 591C0B03040416D6

View file

@ -1,6 +1,6 @@
use std::{
collections::{BTreeMap, BTreeSet},
fs,
fs, io,
path::{Path, PathBuf},
str::FromStr,
};
@ -48,7 +48,13 @@ impl CratesToml {
cvs: CrateVersionSource,
bins: BTreeSet<String>,
) -> Result<(), CratesTomlParseError> {
let mut c1 = Self::load_from_path(path.as_ref()).unwrap_or_default();
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),
};
c1.insert(cvs, bins);
c1.write_to_path(path.as_ref())?;
@ -73,7 +79,7 @@ impl FromStr for CratesToml {
#[derive(Debug, Diagnostic, Error)]
pub enum CratesTomlParseError {
#[error(transparent)]
Io(#[from] std::io::Error),
Io(#[from] io::Error),
#[error(transparent)]
TomlParse(#[from] toml::de::Error),