use std::{
ffi::{OsStr, OsString},
io,
path::{Component, Path, PathBuf},
};
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
use linux as native;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use macos as native;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as native;
pub fn canonical_target(path: &Path) -> io::Result<PathBuf> {
normalize(path, MissingNames::Canonical)
}
pub fn resolve_target(path: &Path) -> io::Result<PathBuf> {
normalize(path, MissingNames::Literal)
}
enum MissingNames {
Canonical,
Literal,
}
fn normalize(path: &Path, missing: MissingNames) -> io::Result<PathBuf> {
if path.as_os_str().is_empty() {
return Err(io::ErrorKind::InvalidInput.into());
}
#[cfg(windows)]
let absolute = std::path::absolute(path)?;
#[cfg(windows)]
let (base, tail) = (PathBuf::new(), absolute.as_path());
#[cfg(windows)]
let verbatim = matches!(tail.components().next(), Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim());
#[cfg(windows)]
if verbatim
&& tail
.components()
.any(|part| matches!(part, Component::ParentDir | Component::CurDir))
{
return match std::fs::canonicalize(tail) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(absolute),
result => result,
};
}
#[cfg(unix)]
let (base, tail) = anchor(path)?;
let mut resolved = base;
for component in tail.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
#[cfg(unix)]
resolved.join("..").metadata()?;
resolved.pop();
}
Component::Prefix(_) => resolved.push(component),
Component::RootDir => {
resolved.push(component);
#[cfg(windows)]
if verbatim {
resolved = std::fs::canonicalize(&resolved)?;
} else {
resolved = super::files::canonicalize(&resolved)?;
}
}
Component::Normal(name) => {
push_name(&mut resolved, name);
match resolved.symlink_metadata() {
Ok(_) => {
#[cfg(windows)]
if verbatim {
resolved = std::fs::canonicalize(&resolved)?;
continue;
}
resolved = super::files::canonicalize(&resolved)?;
}
Err(error)
if error.kind() == io::ErrorKind::NotFound
&& matches!(missing, MissingNames::Canonical) =>
{
normalize_missing(&mut resolved, name)?;
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
}
}
#[cfg(unix)]
return finish(path, resolved, missing);
#[cfg(windows)]
if verbatim && let Some(plain) = super::files::plain(&resolved) {
return Ok(plain);
}
#[cfg(windows)]
Ok(resolved)
}
#[cfg(unix)]
fn finish(path: &Path, resolved: PathBuf, missing: MissingNames) -> io::Result<PathBuf> {
use std::os::unix::ffi::OsStrExt;
let (terminal, has_suffix) = super::files::terminal_component(path);
if !has_suffix {
return Ok(resolved);
}
let suffix = &path.as_os_str().as_bytes()[terminal.as_os_str().len()..];
let mut qualified = resolved.clone();
qualified.as_mut_os_string().push(OsStr::from_bytes(suffix));
if let Err(error) = qualified.metadata()
&& error.kind() != io::ErrorKind::NotFound
{
return Err(error);
}
Ok(match missing {
MissingNames::Canonical => resolved,
MissingNames::Literal => qualified,
})
}
#[derive(Clone, Copy)]
pub(super) enum NamePolicy {
Literal,
Folded,
#[cfg(target_os = "macos")]
Decomposed,
#[cfg(target_os = "linux")]
Upcase,
}
impl NamePolicy {
pub(super) fn key(self, name: &OsStr) -> io::Result<OsString> {
match self {
Self::Literal => Ok(name.to_owned()),
Self::Folded => {
#[cfg(not(target_os = "macos"))]
return Ok(native::fold(name));
#[cfg(target_os = "macos")]
native::key(name, true)
}
#[cfg(target_os = "macos")]
Self::Decomposed => native::key(name, false),
#[cfg(target_os = "linux")]
Self::Upcase => Ok(native::upcase(name)),
}
}
}
fn normalize_missing(path: &mut PathBuf, name: &OsStr) -> io::Result<()> {
let policy = path
.ancestors()
.skip(1)
.find_map(|parent| match directory_name_policy(parent) {
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
result => Some(result),
})
.ok_or(io::ErrorKind::NotFound)??;
if !matches!(policy, NamePolicy::Literal) {
path.pop();
push_name(path, &policy.key(name)?);
}
Ok(())
}
pub(super) fn directory_name_policy(path: &Path) -> io::Result<NamePolicy> {
native::name_policy(path)
}
#[cfg(unix)]
fn anchor(path: &Path) -> io::Result<(PathBuf, &Path)> {
if path.is_absolute() {
return Ok((PathBuf::new(), path));
}
Ok((super::files::canonicalize(&std::env::current_dir()?)?, path))
}
#[cfg(unix)]
fn push_name(path: &mut PathBuf, name: &OsStr) {
path.push(name);
}
#[cfg(windows)]
fn push_name(path: &mut PathBuf, name: &OsStr) {
if !path.as_os_str().as_encoded_bytes().ends_with(b"\\") {
path.as_mut_os_string().push(r"\");
}
path.as_mut_os_string().push(name);
}
pub fn paths_equal(left: &Path, right: &Path) -> bool {
if left.as_os_str() == right.as_os_str() {
return true;
}
let identity = |path: &Path| {
super::files::open_directory(path)
.or_else(|_| {
super::files::canonicalize(path).and_then(|path| super::files::open_regular(&path))
})
.and_then(|file| super::private::file_identity(&file))
};
match (identity(left), identity(right)) {
(Ok(left), Ok(right)) => left == right,
_ => canonical_target(left)
.is_ok_and(|left| canonical_target(right).is_ok_and(|right| left == right)),
}
}
pub fn is_within(path: &Path, root: &Path) -> bool {
path.ancestors().any(|ancestor| paths_equal(ancestor, root))
}
#[cfg(test)]
mod tests;