use std::borrow::Cow;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use url::Url;
#[derive(Debug, Clone)]
pub enum UrlOrPath {
Url(Url),
Path(PathBuf),
}
impl UrlOrPath {
pub fn is_file(&self) -> bool {
match self {
UrlOrPath::Url(url) => url.scheme() == "file",
UrlOrPath::Path(_) => true,
}
}
pub fn is_node_url(&self) -> bool {
match self {
UrlOrPath::Url(url) => url.scheme() == "node",
UrlOrPath::Path(_) => false,
}
}
pub fn into_path(
self,
) -> Result<PathBuf, deno_path_util::UrlToFilePathError> {
match self {
UrlOrPath::Url(url) => deno_path_util::url_to_file_path(&url),
UrlOrPath::Path(path) => Ok(path),
}
}
pub fn into_url(self) -> Result<Url, deno_path_util::PathToUrlError> {
match self {
UrlOrPath::Url(url) => Ok(url),
UrlOrPath::Path(path) => deno_path_util::url_from_file_path(&path),
}
}
pub fn to_string_lossy(&self) -> Cow<'_, str> {
match self {
UrlOrPath::Url(url) => Cow::Borrowed(url.as_str()),
UrlOrPath::Path(path) => path.to_string_lossy(),
}
}
}
impl std::fmt::Display for UrlOrPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UrlOrPath::Url(url) => url.fmt(f),
UrlOrPath::Path(path) => {
match deno_path_util::url_from_file_path(path) {
Ok(url) => url.fmt(f),
Err(_) => {
write!(f, "{}", path.display())
}
}
}
}
}
}
pub struct UrlOrPathRef<'a> {
url: once_cell::unsync::OnceCell<Cow<'a, Url>>,
path: once_cell::unsync::OnceCell<Cow<'a, Path>>,
}
impl<'a> UrlOrPathRef<'a> {
pub fn from_path(path: &'a Path) -> Self {
Self {
url: Default::default(),
path: once_cell::unsync::OnceCell::with_value(Cow::Borrowed(path)),
}
}
pub fn from_url(url: &'a Url) -> Self {
Self {
path: Default::default(),
url: once_cell::unsync::OnceCell::with_value(Cow::Borrowed(url)),
}
}
pub fn url(&self) -> Result<&Url, deno_path_util::PathToUrlError> {
self
.url
.get_or_try_init(|| {
deno_path_util::url_from_file_path(self.path.get().unwrap())
.map(Cow::Owned)
})
.map(|v| v.as_ref())
}
pub fn path(&self) -> Result<&Path, deno_path_util::UrlToFilePathError> {
self
.path
.get_or_try_init(|| {
deno_path_util::url_to_file_path(self.url.get().unwrap())
.map(Cow::Owned)
})
.map(|v| v.as_ref())
}
pub fn display(&self) -> UrlOrPath {
if let Ok(url) = self.url() {
UrlOrPath::Url(url.clone())
} else {
UrlOrPath::Path(self.path.get().unwrap().to_path_buf())
}
}
}
pub trait PathClean<T> {
fn clean(&self) -> T;
}
impl PathClean<PathBuf> for PathBuf {
fn clean(&self) -> PathBuf {
if cfg!(windows) {
clean_via_components(self)
} else {
path_clean::PathClean::clean(self)
}
}
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only used on windows"))]
fn clean_via_components(path: &Path) -> PathBuf {
let mut components: Vec<Component> = Vec::new();
for component in path.components() {
match component {
Component::CurDir => {
}
Component::ParentDir => match components.last() {
Some(Component::Normal(_)) => {
components.pop();
}
Some(Component::RootDir | Component::Prefix(_)) => {}
_ => components.push(component),
},
Component::Normal(_) | Component::RootDir | Component::Prefix(_) => {
components.push(component);
}
}
}
if components.is_empty() {
return PathBuf::from(".");
}
components.into_iter().collect::<PathBuf>()
}
#[cfg(test)]
mod test {
#[cfg(windows)]
#[test]
fn test_path_clean() {
use super::*;
run_test("C:\\test\\./file.txt", "C:\\test\\file.txt");
run_test("C:\\test\\../other/file.txt", "C:\\other\\file.txt");
run_test("C:\\test\\../other\\file.txt", "C:\\other\\file.txt");
run_test("C:\\a\\b\\c\\d\\../../types", "C:\\a\\b\\types");
run_test("C:\\a\\b\\c\\d\\../../../types", "C:\\a\\types");
run_test("C:\\a\\b\\c\\../../helpers/x", "C:\\a\\helpers\\x");
run_test("C:\\a\\../../types", "C:\\types");
run_test("C:\\..", "C:\\");
fn run_test(input: &str, expected: &str) {
assert_eq!(PathBuf::from(input).clean(), PathBuf::from(expected));
}
}
#[test]
fn test_clean_via_components() {
use super::*;
let cases = [
("test/path/..", "test"),
("test/../path", "path"),
("test/path/../../another/path", "another/path"),
("./test/./path", "test/path"),
("/test/../path", "/path"),
("/test/path/../../../..", "/"),
("test/path/../../../..", "../.."),
("../test/path", "../test/path"),
("a/b/c/d/../../types", "a/b/types"),
("test/..", "."),
];
for (input, expected) in cases {
assert_eq!(
clean_via_components(Path::new(input)),
PathBuf::from(expected),
"input: {input}"
);
}
}
}