nushell/src/utils.rs

73 lines
1.5 KiB
Rust
Raw Normal View History

2019-07-24 06:10:48 +02:00
use std::ops::Div;
use std::path::{Path, PathBuf};
pub struct AbsolutePath {
inner: PathBuf,
}
impl AbsolutePath {
pub fn new(path: impl AsRef<Path>) -> AbsolutePath {
let path = path.as_ref();
if path.is_absolute() {
AbsolutePath {
inner: path.to_path_buf(),
}
} else {
panic!("AbsolutePath::new must take an absolute path")
}
}
}
2019-08-02 21:15:07 +02:00
impl Div<&str> for &AbsolutePath {
2019-07-24 06:10:48 +02:00
type Output = AbsolutePath;
fn div(self, rhs: &str) -> Self::Output {
2019-08-02 21:15:07 +02:00
let parts = rhs.split("/");
let mut result = self.inner.clone();
for part in parts {
result = result.join(part);
2019-07-24 06:10:48 +02:00
}
2019-08-02 21:15:07 +02:00
AbsolutePath::new(result)
2019-07-24 06:10:48 +02:00
}
}
impl AsRef<Path> for AbsolutePath {
fn as_ref(&self) -> &Path {
self.inner.as_path()
}
}
pub struct RelativePath {
inner: PathBuf,
}
impl RelativePath {
pub fn new(path: impl Into<PathBuf>) -> RelativePath {
let path = path.into();
if path.is_relative() {
RelativePath { inner: path }
} else {
panic!("RelativePath::new must take a relative path")
}
}
}
2019-08-02 21:15:07 +02:00
impl<T: AsRef<str>> Div<T> for &RelativePath {
2019-07-24 06:10:48 +02:00
type Output = RelativePath;
fn div(self, rhs: T) -> Self::Output {
2019-08-02 21:15:07 +02:00
let parts = rhs.as_ref().split("/");
let mut result = self.inner.clone();
for part in parts {
result = result.join(part);
2019-07-24 06:10:48 +02:00
}
2019-08-02 21:15:07 +02:00
RelativePath::new(result)
2019-07-24 06:10:48 +02:00
}
}