diff --git a/src/filesystem.rs b/src/filesystem.rs index d8302b0..0f98a5c 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -1,4 +1,5 @@ use crate::structures::error::filesystem::InvalidPath; +use crate::structures::error::filesystem::UnreadableDir; use crate::structures::option::Config; use anyhow::Context; use anyhow::Error; @@ -78,13 +79,13 @@ fn cheat_paths_from_config_dir() -> Result { .and_then(pathbuf_to_string) .and_then(|path| { fs::read_dir(path.clone()) - .with_context(|| format!("Unable to read directory `{}`", &path)) + .map_err(|e| UnreadableDir::new(path.clone(), e).into()) .map(|entries| (path, entries)) }) .and_then(|(path, dir_entries)| { let mut paths_str = String::from(""); for entry in dir_entries { - let path = entry.with_context(|| format!("Unable to read directory `{}`", path))?; + let path = entry.map_err(|e| UnreadableDir::new(path.clone(), e))?; paths_str.push_str( path.path() .into_os_string() diff --git a/src/parser.rs b/src/parser.rs index c05d1d8..cf6708a 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -3,7 +3,10 @@ use crate::filesystem; use crate::structures::cheat::VariableMap; use crate::structures::fnv::HashLine; use crate::structures::fzf::{Opts as FzfOpts, SuggestionType}; -use crate::structures::{error::filesystem::InvalidPath, option::Config}; +use crate::structures::{ + error::filesystem::{InvalidPath, UnreadableDir}, + option::Config, +}; use crate::welcome; use anyhow::{Context, Error}; use regex::Regex; @@ -224,13 +227,10 @@ pub fn read_all( let folders = paths_from_path_param(&paths); for folder in folders { - let dir_entries = fs::read_dir(folder) - .with_context(|| format!("Unable to read directory `{}`", folder))?; + let dir_entries = fs::read_dir(folder).map_err(|e| UnreadableDir::new(folder, e))?; for entry in dir_entries { - let path = entry - .with_context(|| format!("Unable to read directory `{}`", folder))? - .path(); + let path = entry.map_err(|e| UnreadableDir::new(folder, e))?.path(); let path_str = path .to_str() .ok_or_else(|| InvalidPath(path.to_path_buf()))?; diff --git a/src/structures/error/filesystem.rs b/src/structures/error/filesystem.rs index 3de3ce2..c14f682 100644 --- a/src/structures/error/filesystem.rs +++ b/src/structures/error/filesystem.rs @@ -1,5 +1,27 @@ use std::{fmt::Debug, path::PathBuf}; use thiserror::Error; + #[derive(Error, Debug)] #[error("Invalid path `{0}`")] pub struct InvalidPath(pub PathBuf); + +#[derive(Error, Debug)] +#[error("Unable to read directory `{dir}`")] +pub struct UnreadableDir { + dir: PathBuf, + #[source] + source: anyhow::Error, +} + +impl UnreadableDir { + pub fn new(dir: DirT, source: SourceError) -> Self + where + DirT: Into, + SourceError: std::error::Error + Sync + Send + 'static, + { + UnreadableDir { + dir: dir.into(), + source: source.into(), + } + } +}