From eca57284ed49763b515687c2d3dee97353ac8ae4 Mon Sep 17 00:00:00 2001 From: Anton Yemelyanov Date: Sat, 3 Aug 2024 13:20:05 +0300 Subject: [PATCH] Update fs error handling to log file path --- src/config.rs | 25 ++++++++++++++++++++++--- src/error.rs | 9 +++++++++ src/imports.rs | 4 ++-- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index bd46db4..8739edd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -90,6 +90,25 @@ impl Config { } } +mod fs { + use super::*; + use std::fs; + + pub use fs::create_dir_all; + + pub fn read_to_string>(path: P) -> Result { + fs::read_to_string(path.as_ref()).map_err(|err| Error::file(path, err)) + } + + pub fn read>(path: P) -> Result> { + fs::read(path.as_ref()).map_err(|err| Error::file(path, err)) + } + + pub fn write, C: AsRef<[u8]>>(path: P, content: C) -> Result<()> { + fs::write(path.as_ref(), content).map_err(|err| Error::file(path, err)) + } +} + static USER_CONFIG: LazyLock>>>> = LazyLock::new(|| Mutex::new(None)); pub fn user_config() -> Option>> { @@ -180,7 +199,7 @@ pub fn load_key() -> Result { if !key_path.exists() { return Err(Error::KeyNotFound); } - Ok(Secret::from(fs::read(key_path)?)) + Ok(Secret::from(fs::read(&key_path)?)) } pub fn load_key64() -> Result { @@ -189,7 +208,7 @@ pub fn load_key64() -> Result { return Err(Error::KeyNotFound); } Ok(u64::from_be_bytes( - fs::read(key64_path)?.try_into().unwrap(), + fs::read(&key64_path)?.try_into().unwrap(), )) } @@ -210,7 +229,7 @@ pub fn locate_local_config() -> Option { pub fn test_config() -> Result>> { let local_config = locate_local_config().ok_or(Error::LocalConfigNotFound)?; - let toml = fs::read_to_string(local_config)?; + let toml = fs::read_to_string(&local_config)?; // let local = include_str!("../Resolver.toml"); Config::try_parse(toml.as_str()) } diff --git a/src/error.rs b/src/error.rs index df25dec..009c7e1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -22,6 +22,9 @@ pub enum Error { #[error("IO Error: {0}")] Io(#[from] std::io::Error), + #[error("Unable to read file: `{0}`, {1}")] + File(String, std::io::Error), + #[error(transparent)] Serde(#[from] serde_json::Error), @@ -77,6 +80,12 @@ impl Error { } } +impl Error { + pub fn file>(path: P, err: std::io::Error) -> Self { + Error::File(path.as_ref().display().to_string(), err) + } +} + impl Error { pub fn config(msg: T) -> Self { Error::Config(msg.to_string()) diff --git a/src/imports.rs b/src/imports.rs index 70e2cec..2a6d05a 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -41,8 +41,8 @@ pub use serde::{de::DeserializeOwned, Deserialize, Serialize}; pub use serde_hex::{SerHex, Strict}; pub use std::collections::{HashMap, HashSet}; pub use std::fmt::{self, Display, Formatter}; -pub use std::fs; -pub use std::path::PathBuf; +// pub use std::fs; +pub use std::path::{Path, PathBuf}; pub use std::str::FromStr; pub use std::sync::atomic::AtomicBool; pub use std::sync::atomic::{AtomicU64, Ordering};