artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Native, no-follow access and path normalization.

use std::path::Path;

mod text;
use text::native_path_text;
pub use text::path_from_text;

#[cfg(unix)]
mod unix;
#[cfg(target_os = "linux")]
pub(super) use unix::native_case_sensitive;
#[cfg(unix)]
pub(in crate::platform) use unix::terminal_component;
#[cfg(windows)]
mod windows;

#[cfg(unix)]
pub use unix::{
    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
};
#[cfg(windows)]
pub use windows::{
    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
};

#[cfg(windows)]
pub use windows::plain;

/// The filesystem root of an absolute path (`/`, or a Windows volume or share) and the names
/// below it, in order. `None` when a component is `.` or `..`.
pub fn split_root(path: &std::path::Path) -> Option<(&std::path::Path, Vec<&std::ffi::OsStr>)> {
    use std::path::Component;
    let root = path.ancestors().last()?;
    path.components()
        .filter_map(|component| match component {
            Component::Prefix(_) | Component::RootDir => None,
            Component::Normal(name) => Some(Some(name)),
            Component::CurDir | Component::ParentDir => Some(None),
        })
        .collect::<Option<Vec<_>>>()
        .map(|names| (root, names))
}

/// The target a link names, read without following it: a symlink's text, or on Windows a
/// junction's or symbolic link's substitute name.
pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
    std::fs::read_link(path)
}

/// The type of a directory entry, read without following it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
    File,
    Directory,
    Symlink,
    /// FIFOs, sockets, devices, and on Windows reparse points that are not links.
    Other,
}

/// Read the process's current directory and resolve its native filesystem aliases.
pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
    canonicalize(&std::env::current_dir()?)
}

/// Text shown for a native path or a logical external target, never an I/O conversion.
pub trait PathText {
    fn path_text(&self) -> String;
}
impl<P: AsRef<std::path::Path> + ?Sized> PathText for P {
    fn path_text(&self) -> String {
        native_path_text(self.as_ref())
    }
}
/// Render a path for people and JSON clients; logical external targets stay opaque.
pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
    path.path_text()
}

/// Open a regular file without following a link or reparse point in its last component.
pub fn open_regular(path: &Path) -> std::io::Result<std::fs::File> {
    let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
    if !file.metadata()?.is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    Ok(file)
}

pub(super) fn portable_basename(name: &str) -> bool {
    // Use a common byte limit so a validated generated name fits Unix too.
    const MAX_COMPONENT_BYTES: usize = 255;
    name.len() <= MAX_COMPONENT_BYTES && ordinary_windows_basename(name)
}

/// A name the Win32 layer keeps as is: no trailing dot or space, no reserved character, and
/// no DOS device name such as `NUL` or `com1.txt`.
fn ordinary_windows_basename(name: &str) -> bool {
    // Win32 recognizes ISO-8859-1 superscript 1, 2 and 3 as DOS COM/LPT digits too.
    const DOS_PORT_DIGITS: &str = "0123456789¹²³";
    let stem = name
        .split('.')
        .next()
        .unwrap_or_default()
        .trim_end_matches(' ');
    let device = match stem.to_ascii_uppercase().as_str() {
        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true,
        port => port
            .strip_prefix("COM")
            .or_else(|| port.strip_prefix("LPT"))
            .is_some_and(|number| {
                number.chars().count() == 1
                    && number.chars().all(|digit| DOS_PORT_DIGITS.contains(digit))
            }),
    };
    !name.is_empty()
        && !name.ends_with(['.', ' '])
        && !name
            .chars()
            .any(|c| c < ' ' || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
        && !device
}

#[cfg(test)]
mod tests;