-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
lib.rs
85 lines (74 loc) · 2.37 KB
/
lib.rs
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
83
84
85
#![feature(assert_matches)]
#![feature(cow_is_borrowed)]
mod absolute_system_path;
mod absolute_system_path_buf;
mod anchored_system_path_buf;
mod relative_system_path_buf;
mod relative_unix_path;
mod relative_unix_path_buf;
use std::{
io,
path::{Path, PathBuf},
};
pub use absolute_system_path::AbsoluteSystemPath;
pub use absolute_system_path_buf::AbsoluteSystemPathBuf;
pub use anchored_system_path_buf::AnchoredSystemPathBuf;
use path_slash::{PathBufExt, PathExt};
pub use relative_system_path_buf::RelativeSystemPathBuf;
pub use relative_unix_path::RelativeUnixPath;
pub use relative_unix_path_buf::RelativeUnixPathBuf;
#[derive(Debug, thiserror::Error)]
pub enum PathError {
#[error("Path validation failed: {0}")]
PathValidationError(#[from] PathValidationError),
#[error("IO Error {0}")]
IO(#[from] io::Error),
}
impl PathError {
pub fn is_io_error(&self, kind: io::ErrorKind) -> bool {
match self {
PathError::IO(err) => err.kind() == kind,
_ => false,
}
}
}
// Custom error type for path validation errors
#[derive(Debug, thiserror::Error)]
pub enum PathValidationError {
#[error("Path is non-UTF-8: {0}")]
InvalidUnicode(PathBuf),
#[error("Path is not absolute: {0}")]
NotAbsolute(PathBuf),
#[error("Path is not relative: {0}")]
NotRelative(PathBuf),
#[error("Path {0} is not parent of {1}")]
NotParent(String, String),
#[error("Path {0} is not a unix path")]
NotUnix(String),
}
trait IntoSystem {
fn into_system(self) -> Result<PathBuf, PathValidationError>;
}
trait IntoUnix {
fn into_unix(self) -> Result<PathBuf, PathValidationError>;
}
impl IntoSystem for &Path {
fn into_system(self) -> Result<PathBuf, PathValidationError> {
let path_str = self
.to_str()
.ok_or_else(|| PathValidationError::InvalidUnicode(self.to_owned()))?;
Ok(PathBuf::from_slash(path_str))
}
}
impl IntoUnix for &Path {
/// NOTE: `into_unix` *only* converts Windows paths to Unix paths *on* a
/// Windows system. Do not pass a Windows path on a Unix system and
/// assume it'll be converted.
fn into_unix(self) -> Result<PathBuf, PathValidationError> {
Ok(PathBuf::from(
self.to_slash()
.ok_or_else(|| PathValidationError::InvalidUnicode(self.to_owned()))?
.as_ref(),
))
}
}