use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf, Prefix};
use crate::NameCase;
use crate::env::fold;
pub fn plain(path: &Path) -> Option<PathBuf> {
let mut parts = path.components().peekable();
let Some(Component::Prefix(prefix)) = parts.next() else {
return Some(path.to_owned());
};
let mut out = match prefix.kind() {
Prefix::VerbatimDisk(drive) if parts.peek() == Some(&Component::RootDir) => {
PathBuf::from(format!("{}:", char::from(drive)))
}
Prefix::VerbatimUNC(server, share) if !server.is_empty() && !share.is_empty() => {
let mut unc = OsString::from(r"\\");
unc.push(server);
unc.push(r"\");
unc.push(share);
PathBuf::from(unc)
}
Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..) | Prefix::Verbatim(_) => return None,
Prefix::DeviceNS(_) | Prefix::Disk(_) | Prefix::UNC(..) => return Some(path.to_owned()),
};
for part in parts {
match part {
Component::RootDir => out.push(r"\"),
Component::Normal(name) if survives(name) => out.push(name),
_ => return None,
}
}
Some(out)
}
fn survives(name: &OsStr) -> bool {
let bytes = name.as_encoded_bytes();
if bytes.contains(&b'/') || bytes.ends_with(b".") || bytes.ends_with(b" ") {
return false;
}
let stem = bytes.split(|b| *b == b'.').next().unwrap_or(bytes);
let stem = stem.trim_ascii_end();
let device = |prefix: &[u8]| {
stem.len() == 4 && stem[..3].eq_ignore_ascii_case(prefix) && matches!(stem[3], b'1'..=b'9')
};
!([b"CON", b"PRN", b"AUX", b"NUL"]
.iter()
.any(|d| stem.eq_ignore_ascii_case(*d))
|| device(b"COM")
|| device(b"LPT"))
}
pub fn lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for part in path.components() {
match part {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
#[derive(Clone, Debug)]
pub struct Place {
real: PathBuf,
parts: Vec<String>,
}
impl Place {
pub fn of(path: &Path, case: NameCase) -> Place {
let (real, exact) = resolve(path);
let parts = real
.components()
.enumerate()
.map(|(i, component)| part(component, if i < exact { None } else { Some(case) }))
.collect();
Place { real, parts }
}
pub fn same(&self, other: &Place) -> bool {
self.parts == other.parts
}
pub fn within(&self, dir: &Place) -> bool {
self.relative(dir).is_some()
}
pub fn relative(&self, dir: &Place) -> Option<PathBuf> {
self.parts
.starts_with(&dir.parts)
.then(|| self.real.components().skip(dir.parts.len()).collect())
}
pub fn parent(&self) -> Option<Place> {
let real = self.real.parent()?.to_owned();
let parts = self.parts[..self.parts.len() - 1].to_vec();
Some(Place { real, parts })
}
}
pub fn same(a: &Path, b: &Path, case: NameCase) -> bool {
Place::of(a, case).same(&Place::of(b, case))
}
pub fn within(path: &Path, dir: &Path, case: NameCase) -> bool {
Place::of(path, case).within(&Place::of(dir, case))
}
pub fn relative(path: &Path, dir: &Path, case: NameCase) -> Option<PathBuf> {
Place::of(path, case).relative(&Place::of(dir, case))
}
fn resolve(path: &Path) -> (PathBuf, usize) {
let path = lexical(path);
if !path.is_absolute() {
return (path, 0);
}
let mut existing = path.as_path();
let mut rest = Vec::new();
loop {
if let Ok(canonical) = std::fs::canonicalize(existing) {
let exact = canonical.components().count();
let real = rest.iter().rev().fold(canonical, |p, part| p.join(part));
return (real, exact);
}
match (existing.parent(), existing.file_name()) {
(Some(parent), Some(name)) => {
rest.push(name.to_owned());
existing = parent;
}
_ => return (path, 0),
}
}
}
fn part(component: Component<'_>, case: Option<NameCase>) -> String {
let folded = |name: &OsStr| match case {
Some(case) => fold(name, case),
None => name.to_owned(),
};
let part = match component {
Component::Prefix(prefix) => match prefix.kind() {
Prefix::VerbatimDisk(d) | Prefix::Disk(d) => {
OsString::from(format!("{}:", char::from(d.to_ascii_uppercase())))
}
Prefix::VerbatimUNC(server, share) | Prefix::UNC(server, share) => {
let mut unc = OsString::from("//");
unc.push(server);
unc.push("/");
unc.push(share);
fold(&unc, NameCase::Insensitive)
}
_ => folded(prefix.as_os_str()),
},
Component::RootDir => OsString::new(),
other => folded(other.as_os_str()),
};
part.to_string_lossy().into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("cuno-paths-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn case_is_ignored_only_where_the_file_system_ignores_it() {
let a = Path::new("/project/Src/Main.cpp");
let b = Path::new("/project/src/main.cpp");
assert!(same(a, b, NameCase::Insensitive));
assert!(!same(a, b, NameCase::Sensitive));
}
#[test]
fn dot_and_dot_dot_are_resolved_by_name() {
let case = NameCase::Sensitive;
assert!(same(
Path::new("/p/./src/../src/a.c"),
Path::new("/p/src/a.c"),
case
));
assert!(within(Path::new("/p/src/../target"), Path::new("/p"), case));
assert!(!within(Path::new("/p/../q"), Path::new("/p"), case));
let relative_path = Path::new("no-such-dir/y/../z");
assert!(same(relative_path, Path::new("no-such-dir/z"), case));
assert!(within(relative_path, Path::new("no-such-dir/."), case));
assert!(!within(
Path::new("no-such-dir/y/out"),
Path::new("no-such-dir/z"),
case
));
assert_eq!(resolve(Path::new("src/../src")).0, PathBuf::from("src"));
}
#[test]
fn within_takes_whole_names() {
let case = NameCase::Sensitive;
let dir = Path::new("/a/b");
assert!(within(Path::new("/a/b"), dir, case));
assert!(within(Path::new("/a/b/c"), dir, case));
assert!(!within(Path::new("/a/bc"), dir, case));
assert!(!within(Path::new("/a"), dir, case));
assert_eq!(
relative(Path::new("/a/b/c/d"), dir, case),
Some(PathBuf::from("c/d"))
);
assert_eq!(relative(Path::new("/a/b"), dir, case), Some(PathBuf::new()));
}
#[test]
fn a_path_not_there_yet_continues_from_the_part_that_is() {
let dir = scratch("tail");
let case = NameCase::host();
let missing = dir.join("not").join("yet");
let (real, _) = resolve(&missing);
assert!(real.ends_with("not/yet"));
assert!(real.starts_with(std::fs::canonicalize(&dir).unwrap()));
assert!(!same(&missing, &dir.join("not"), case));
assert!(within(&missing, &dir, case));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn a_verbatim_prefix_is_the_plain_one() {
let drive = (b'D'..=b'Z')
.map(char::from)
.find(|d| !Path::new(&format!("{d}:\\")).exists())
.expect("a free drive letter");
let verbatim = PathBuf::from(format!(r"\\?\{drive}:\nowhere"));
let plain = PathBuf::from(format!(r"{drive}:\nowhere"));
assert!(same(&verbatim, &plain, NameCase::Insensitive));
}
#[cfg(windows)]
#[test]
fn a_junction_is_where_it_leads() {
let dir = scratch("junction");
let target = dir.join("target");
let link = dir.join("link");
std::fs::create_dir(&target).unwrap();
let made = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&target)
.output()
.unwrap();
assert!(made.status.success(), "{made:?}");
let case = NameCase::Insensitive;
assert!(same(&link, &target, case));
assert!(within(&link.join("debug"), &target, case));
assert!(!within(&link, &dir.join("elsewhere"), case));
std::fs::remove_dir(&link).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn existing_names_are_compared_as_the_file_system_spells_them() {
let dir = scratch("spelled");
let case = NameCase::Insensitive;
for name in ["tool_σ.cpp", "tool_ς.cpp"] {
std::fs::write(dir.join(name), "").unwrap();
}
assert!(!same(
&dir.join("tool_σ.cpp"),
&dir.join("tool_Ï‚.cpp"),
case
));
assert!(same(&dir.join("New/Out"), &dir.join("new/out"), case));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn a_share_is_one_share_however_it_is_written() {
let prefix = |p: &'static str| part(Path::new(p).components().next().unwrap(), None);
assert_eq!(
prefix(r"\\?\UNC\Server\Share\x"),
prefix(r"\\server\share\x")
);
assert_eq!(prefix(r"\\?\c:\x"), prefix(r"C:\x"));
}
#[test]
fn a_place_knows_its_directory() {
let case = NameCase::Sensitive;
let file = Place::of(Path::new("/p/src/a.c"), case);
let src = Place::of(Path::new("/p/src"), case);
assert!(file.parent().unwrap().same(&src));
assert!(!file.same(&src));
}
#[cfg(windows)]
#[test]
fn a_verbatim_path_is_written_plain() {
let plain_of = |p: &str| plain(Path::new(p)).map(|p| p.to_string_lossy().into_owned());
assert_eq!(plain_of(r"\\?\C:\a\out").as_deref(), Some(r"C:\a\out"));
assert_eq!(plain_of(r"\\?\d:\x").as_deref(), Some(r"D:\x"));
assert_eq!(
plain_of(r"\\?\UNC\srv\share\out").as_deref(),
Some(r"\\srv\share\out")
);
assert_eq!(plain_of(r"C:\a\..\b").as_deref(), Some(r"C:\a\..\b"));
assert_eq!(
plain_of(r"\\srv\share\x").as_deref(),
Some(r"\\srv\share\x")
);
assert_eq!(plain_of("out").as_deref(), Some("out"));
assert_eq!(plain_of(r"\\.\C:\x").as_deref(), Some(r"\\.\C:\x"));
}
#[cfg(windows)]
#[test]
fn a_verbatim_path_that_means_something_else_plain_has_no_plain_form() {
for path in [
r"\\?\C:\a\..\b",
r"\\?\C:\a\.\b",
r"\\?\C:\out.",
r"\\?\C:\out ",
r"\\?\C:\a/b\out",
r"\\?\C:\nul",
r"\\?\C:\Con.txt",
r"\\?\C:\lpt9 .log",
r"\\?\C:\COM1",
r"\\?\C:\com3",
r"\\?\C:\prn",
r"\\?\C:\Aux.c",
r"\\?\GLOBALROOT\Device\x",
r"\\?\C:",
r"\\?\C:out",
r"\\?\UNC\srv",
r"\\?\UNC\srv\",
r"\\?\UNC\",
] {
assert_eq!(plain(Path::new(path)), None, "{path}");
}
for path in [
r"\\?\C:\console",
r"\\?\C:\com10",
r"\\?\C:\a.b\out",
r"\\?\C:\lpt0",
] {
assert!(plain(Path::new(path)).is_some(), "{path}");
}
}
}