Add InvalidPath error

This commit is contained in:
Csonka Mihaly 2020-03-22 20:14:10 +01:00
parent 38b85fabf6
commit 4bbccc2cfa
4 changed files with 20 additions and 12 deletions

View file

@ -1,3 +1,4 @@
use crate::structures::error::FilesystemError;
use crate::structures::option::Config;
use anyhow::Context;
use anyhow::Error;
@ -21,11 +22,11 @@ where
}
pub fn pathbuf_to_string(pathbuf: PathBuf) -> Result<String, Error> {
pathbuf
Ok(pathbuf
.as_os_str()
.to_str()
.ok_or_else(|| anyhow!("Invalid path `{}`", pathbuf.display()))
.map(str::to_string)
.ok_or_else(|| FilesystemError::InvalidPath(pathbuf.to_path_buf()))
.map(str::to_string)?)
}
pub fn cheat_pathbuf() -> Result<PathBuf, Error> {
@ -44,16 +45,15 @@ fn follow_symlink(pathbuf: PathBuf) -> Result<PathBuf, Error> {
let o_str = o
.as_os_str()
.to_str()
.ok_or_else(|| anyhow!("Invalid path `{}`", o.display()))?;
.ok_or_else(|| FilesystemError::InvalidPath(o.to_path_buf()))?;
if o_str.starts_with('.') {
let parent_str = pathbuf
let parent = pathbuf
.parent()
.ok_or_else(|| anyhow!("`{}` has no parent", pathbuf.display()))?
.ok_or_else(|| anyhow!("`{}` has no parent", pathbuf.display()))?;
let parent_str = parent
.as_os_str()
.to_str()
.ok_or_else(|| {
anyhow!("Parent of `{}` is an invalid path", pathbuf.display())
})?;
.ok_or_else(|| FilesystemError::InvalidPath(parent.to_path_buf()))?;
let path_str = format!("{}/{}", parent_str, o_str);
let p = PathBuf::from(path_str);
follow_symlink(p)
@ -89,7 +89,7 @@ fn cheat_paths_from_config_dir() -> Result<String, Error> {
path.path()
.into_os_string()
.to_str()
.ok_or_else(|| anyhow!("Invalid path `{}`", path.path().display()))?,
.ok_or_else(|| FilesystemError::InvalidPath(path.path()))?,
);
paths_str.push_str(":");
}

View file

@ -3,7 +3,7 @@ use crate::filesystem;
use crate::structures::cheat::VariableMap;
use crate::structures::fnv::HashLine;
use crate::structures::fzf::{Opts as FzfOpts, SuggestionType};
use crate::structures::option::Config;
use crate::structures::{error::FilesystemError, option::Config};
use crate::welcome;
use anyhow::{Context, Error};
use regex::Regex;
@ -233,7 +233,7 @@ pub fn read_all(
.path();
let path_str = path
.to_str()
.ok_or_else(|| anyhow!("Invalid path `{}`", path.display()))?;
.ok_or_else(|| FilesystemError::InvalidPath(path.to_path_buf()))?;
if path_str.ends_with(".cheat")
&& read_file(path_str, &mut variables, &mut visited_lines, stdin).is_ok()
&& !found_something

7
src/structures/error.rs Normal file
View file

@ -0,0 +1,7 @@
use std::{fmt::Debug, path::PathBuf};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FilesystemError {
#[error("Invalid path `{0}`")]
InvalidPath(PathBuf),
}

View file

@ -1,4 +1,5 @@
pub mod cheat;
pub mod error;
pub mod fnv;
pub mod fzf;
pub mod option;