use std::fs::canonicalize;
use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct DirPath(String);
impl FromStr for DirPath {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let path = canonicalize(s).map_err(|_| format!("Path {} does not exist", s))?;
if !path.is_dir() {
return Err(format!("{} is not a directory", s));
}
Ok(Self(path.to_string_lossy().to_string()))
}
}
impl DirPath {
pub fn str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone)]
pub struct FilePath(String);
impl FromStr for FilePath {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let path = canonicalize(s).map_err(|_| format!("Path {} does not exist", s))?;
if !path.is_file() {
return Err(format!("{} is not a file", s));
}
Ok(Self(path.to_string_lossy().to_string()))
}
}
impl FilePath {
pub fn str(&self) -> &str {
&self.0
}
}
#[cfg(test)]
mod test {
use super::*;
use const_format::formatcp;
use std::fs::{create_dir_all, remove_dir_all, remove_file, File};
use std::sync::Once;
const TEST_DIR: &'static str = "/tmp/worm_hole_test";
const FILE_PATH: &'static str = formatcp!("{}/file", TEST_DIR);
const DIR_PATH: &'static str = formatcp!("{}/dir", TEST_DIR);
const NOT_A_PATH: &'static str = formatcp!("{}/not_a_path", TEST_DIR);
static SETUP: Once = Once::new();
fn setup() {
SETUP.call_once(|| {
remove_dir_all(TEST_DIR).ok(); remove_file(TEST_DIR).ok(); create_dir_all(DIR_PATH).unwrap();
File::create(FILE_PATH).unwrap();
});
}
mod dir_path {
use super::*;
#[test]
fn path_not_exist() {
let path = NOT_A_PATH.parse::<DirPath>().unwrap_err();
assert_eq!(path, format!("Path {} does not exist", NOT_A_PATH));
}
#[test]
fn path_is_not_dir() {
setup();
let error = FILE_PATH.parse::<DirPath>().unwrap_err();
assert_eq!(error, format!("{} is not a directory", FILE_PATH));
}
#[test]
fn path_is_dir() {
setup();
let path = DIR_PATH.parse::<DirPath>().unwrap();
assert_eq!(path.str(), DIR_PATH);
}
}
mod file_path {
use super::*;
#[test]
fn path_not_exist() {
let path = NOT_A_PATH.parse::<FilePath>().unwrap_err();
assert_eq!(path, format!("Path {} does not exist", NOT_A_PATH));
}
#[test]
fn path_is_not_file() {
setup();
let error = DIR_PATH.parse::<FilePath>().unwrap_err();
assert_eq!(error, format!("{} is not a file", DIR_PATH));
}
#[test]
fn path_is_file() {
setup();
let path = FILE_PATH.parse::<FilePath>().unwrap();
assert_eq!(path.str(), FILE_PATH);
}
}
}