index : static-web-server.git

ascending towards madness

author Jose Quintana <joseluisquintana20@gmail.com> 2020-04-21 6:34:30.0 +00:00:00
committer Jose Quintana <joseluisquintana20@gmail.com> 2020-04-21 6:34:30.0 +00:00:00
commit
a449eb30c2228e790e4cedc8426d02fae17b8293 [patch]
tree
3d44df4fe541d933dbc6dc661a91080503193d99
parent
57184a546526face11967c22020674e96a81440d
download
a449eb30c2228e790e4cedc8426d02fae17b8293.tar.gz

refactor: path helpers



Diff

 src/helpers.rs | 39 ++++++++++++++++++++++++---------------
 1 file changed, 24 insertions(+), 15 deletions(-)

diff --git a/src/helpers.rs b/src/helpers.rs
index 535f8fd..d251a0c 100644
--- a/src/helpers.rs
+++ b/src/helpers.rs
@@ -1,26 +1,35 @@
use std::error;
use std::path::{Path, PathBuf};

pub enum PathError {
    PathNotFound,
    NotDirectory,
}

/// Validate a path if exist and is a directory.
pub fn validate_dirpath<P: AsRef<Path>>(path: P) -> Result<PathBuf, PathError>
/// Validate and return a directory path.
pub fn get_valid_dirpath<P: AsRef<Path>>(path: P) -> Result<PathBuf, Box<dyn error::Error>>
where
    PathBuf: From<P>,
{
    match PathBuf::from(path) {
        p if !p.exists() => Result::Err(PathError::PathNotFound),
        p if !p.is_dir() => Result::Err(PathError::NotDirectory),
        p => Result::Ok(p),
        v if !v.exists() => Result::Err(From::from(format!("path \"{:?}\" was not found", &v))),
        v if !v.is_dir() => {
            Result::Err(From::from(format!("path \"{:?}\" is not a directory", &v)))
        }
        v => Result::Ok(v),
    }
}

/// Format a `PathError` description
pub fn path_error_fmt(err: PathError, dirname: &str, dirpath: &str) -> String {
    match err {
        PathError::PathNotFound => format!("{} path \"{}\" was not found", dirname, dirpath),
        PathError::NotDirectory => format!("{} path \"{}\" is not a directory", dirname, dirpath),
/// Get the directory name of a valid directory path.
pub fn get_dirname<P: AsRef<Path>>(path: P) -> Result<String, Box<dyn error::Error>>
where
    PathBuf: From<P>,
{
    let path = match get_valid_dirpath(path) {
        Err(e) => return Result::Err(e),
        Ok(v) => v,
    };

    match path.iter().last() {
        Some(v) => Result::Ok(v.to_str().unwrap().to_string()),
        _ => Result::Err(From::from(format!(
            "directory name for path \"{:?}\" was not determined",
            path,
        ))),
    }
}