use std::path::{Path, PathBuf};
pub fn normalize(path: &Path) -> PathBuf {
use std::path::Component;
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn path_to_unix_string_lossy(path: impl AsRef<Path>) -> String {
use std::borrow::Cow;
use std::path::Component;
itertools::Itertools::intersperse(
path.as_ref().components().map(|c| match c {
Component::Prefix(..) => unreachable!(),
Component::RootDir => Cow::Borrowed(""),
Component::CurDir => Cow::Borrowed("."),
Component::ParentDir => Cow::Borrowed(".."),
Component::Normal(c) => c.to_string_lossy(),
}),
Cow::Borrowed("/"),
)
.collect()
}
pub fn path_to_unix_string(path: impl AsRef<Path>) -> Option<String> {
use std::borrow::Cow;
use std::path::Component;
itertools::Itertools::intersperse(
path.as_ref().components().map(|c| match c {
Component::Prefix(..) => unreachable!(),
Component::RootDir => Some(Cow::Borrowed("")),
Component::CurDir => Some(Cow::Borrowed(".")),
Component::ParentDir => Some(Cow::Borrowed("..")),
Component::Normal(c) => c.to_str().map(Cow::Borrowed),
}),
Some(Cow::Borrowed("/")),
)
.collect()
}