From a449eb30c2228e790e4cedc8426d02fae17b8293 Mon Sep 17 00:00:00 2001 From: Jose Quintana Date: Tue, 21 Apr 2020 08:34:30 +0200 Subject: [PATCH] refactor: path helpers --- 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>(path: P) -> Result +/// Validate and return a directory path. +pub fn get_valid_dirpath>(path: P) -> Result> where PathBuf: From

, { 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>(path: P) -> Result> +where + PathBuf: From

, +{ + 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, + ))), } } -- libgit2 1.7.2