worm_hole 1.1.2

CLI tool to easily jump between directories
use std::fs::canonicalize;
use std::str::FromStr;

#[derive(Debug, Clone)]
pub struct DirPath(String);
impl FromStr for DirPath {
	type Err = String;

	/// Parse a string into a DirPath.
	/// The string must be a valid path
	/// ```
	/// use worm_hole::path::DirPath;
	/// let path = "not_a_path".parse::<DirPath>().unwrap_err();
	/// assert_eq!(path, "Path not_a_path does not exist");
	/// ```
	/// And the path must be a directory.
	/// ```
	/// use worm_hole::path::DirPath;
	/// let error = "Cargo.toml".parse::<DirPath>().unwrap_err();
	/// assert_eq!(error, "Cargo.toml is not a directory");
	/// ```
	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 {
	/// Get the string representation of the path.
	/// The path given is the absolute path.
	/// ```
	/// use worm_hole::path::DirPath;
	/// let path = "/home".parse::<DirPath>().unwrap();
	/// assert_eq!(path.str(), "/home");
	/// ```
	pub fn str(&self) -> &str {
		&self.0
	}
}

#[derive(Debug, Clone)]
pub struct FilePath(String);
impl FromStr for FilePath {
	type Err = String;

	/// Parse a string into a FilePath.
	/// The string must be a valid path
	/// ```
	/// use worm_hole::path::FilePath;
	/// let path = "not_a_path".parse::<FilePath>().unwrap_err();
	/// assert_eq!(path, "Path not_a_path does not exist");
	/// ```
	/// And the path must be a file.
	/// ```
	/// use worm_hole::path::FilePath;
	/// let error = "/usr/bin".parse::<FilePath>().unwrap_err();
	/// assert_eq!(error, "/usr/bin is not a file");
	/// ```
	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 {
	/// Get the string representation of the path.
	/// The path given is the absolute path.
	/// ```
	/// use worm_hole::path::FilePath;
	/// let path = "/usr/bin/bash".parse::<FilePath>().unwrap();
	/// assert_eq!(path.str(), "/usr/bin/bash");
	/// ```
	pub fn str(&self) -> &str {
		&self.0
	}
}