artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Normalize a location, including a suffix not yet present on disk.

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;

/// A location key: resolve existing aliases and give equivalent missing names one spelling.
pub fn canonical_target(path: &Path) -> io::Result<PathBuf> {
    normalize(path, MissingNames::Canonical)
}

/// A path for I/O: resolve existing aliases without changing the spelling a future creation
/// will write to disk. Use [`canonical_target`] when comparing locations instead.
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))
    {
        // Component-wise resolution would interpret literal verbatim components as
        // navigation, and PathBuf::push on a verbatim path can normalize them itself.
        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)]
                // The kernel must be able to walk through this directory before
                // stepping up, even when the remainder is an uncreated suffix.
                resolved.join("..").metadata()?;
                resolved.pop();
            }
            // A Windows prefix alone names a volume device, not a directory.
            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 {
                            // Keep the native prefix until every input component has been
                            // interpreted. A later literal name may not have a plain spelling.
                            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)
}

/// Keep the native directory requirement of trailing separators and `/.` without
/// rejecting a directory that has yet to be created.
#[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,
    })
}

/// How to key a new directory entry when the native spelling is not yet on disk.
#[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)),
        }
    }
}

/// A missing component cannot report its on-disk spelling. Use the closest
/// existing directory's native name policy for the uncreated suffix.
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)
}

// Unix must resolve a link before stepping up from its target; Windows normalizes
// ordinary Win32 paths first, just as its native file opens do.
#[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) {
    // A normal component of a complete path may look like a drive prefix when
    // reparsed alone (such as the stream name `a:stream`). Append it literally.
    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);
}

/// Compare opened identities when both exist, or their resolved location keys otherwise.
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)),
    }
}

/// Include the root itself; match native equivalence of each ancestor.
pub fn is_within(path: &Path, root: &Path) -> bool {
    path.ancestors().any(|ancestor| paths_equal(ancestor, root))
}

#[cfg(test)]
mod tests;