Using metadata method on PathBuf
This commit is contained in:
parent
e5090d650c
commit
9b8756579b
1 changed files with 18 additions and 14 deletions
|
@ -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,22 +279,26 @@ 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()
|
||||||
let file = fs::OpenOptions::new()
|
.map_err(|_| format!("Error obtaining metadata for {}", path.display()))?;
|
||||||
.read(true)
|
|
||||||
.open(&path)
|
|
||||||
.map_err(|_| format!("Unable to open file {}", path.display()))?;
|
|
||||||
|
|
||||||
let val = serde_json::from_reader(file)
|
if metadata.is_file() {
|
||||||
.map_err(|_| String::from("Unable to parse value from file."))?;
|
let file = fs::OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.open(&path)
|
||||||
|
.map_err(|_| format!("Unable to open file {}", path.display()))?;
|
||||||
|
|
||||||
Ok(FileLinked { val, path })
|
let val = serde_json::from_reader(file)
|
||||||
}
|
.map_err(|_| String::from("Unable to parse value from file."))?;
|
||||||
Ok(_) => Err(format!("{} is not a file.", path.display())),
|
|
||||||
_ => Err(format!("Error parsing file path {}", path.display())),
|
Ok(FileLinked { val, path })
|
||||||
|
} else {
|
||||||
|
Err(format!("{} is not a file.", path.display()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue