1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
}
}