Using metadata method on PathBuf

This commit is contained in:
vandomej 2021-10-01 01:12:53 -07:00
parent e5090d650c
commit 9b8756579b

View file

@ -257,7 +257,7 @@ where
/// let mut file = OpenOptions::new() /// let mut file = OpenOptions::new()
/// .write(true) /// .write(true)
/// .create(true) /// .create(true)
/// .open(path.clone()) /// .open(&path)
/// .expect("Unable to create file"); /// .expect("Unable to create file");
/// ///
/// write!(file, "{}", serde_json::to_string(&test) /// write!(file, "{}", serde_json::to_string(&test)
@ -279,10 +279,15 @@ where
/// # } /// # }
/// ``` /// ```
pub fn from_file(path: path::PathBuf) -> Result<FileLinked<T>, String> { pub fn from_file(path: path::PathBuf) -> Result<FileLinked<T>, String> {
let meta = fs::metadata(&path); if !path.is_file() {
return Err(format!("{} is not a valid file path", path.display()));
}
match &meta { let metadata = path
Ok(m) if m.is_file() && path.is_file()=> { .metadata()
.map_err(|_| format!("Error obtaining metadata for {}", path.display()))?;
if metadata.is_file() {
let file = fs::OpenOptions::new() let file = fs::OpenOptions::new()
.read(true) .read(true)
.open(&path) .open(&path)
@ -292,9 +297,8 @@ where
.map_err(|_| String::from("Unable to parse value from file."))?; .map_err(|_| String::from("Unable to parse value from file."))?;
Ok(FileLinked { val, path }) Ok(FileLinked { val, path })
} } else {
Ok(_) => Err(format!("{} is not a file.", path.display())), Err(format!("{} is not a file.", path.display()))
_ => Err(format!("Error parsing file path {}", path.display())),
} }
} }
} }