artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Reversible path text, distinct from the native spelling supplied to OS APIs.

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use std::{
    ffi::OsString,
    io,
    path::{Path, PathBuf},
};

// Reserve the prefix on both hosts, including for a literal path that starts with it.
const ENCODED: &str = "native-path:/";
#[cfg(unix)]
const CODEC: &str = "unix/";
#[cfg(windows)]
const CODEC: &str = "windows/";
#[cfg(windows)]
const VERBATIM: &str = "//?/";

pub(super) fn native_path_text(path: &Path) -> String {
    if let Some(text) = readable(path).filter(|text| !text.starts_with(ENCODED)) {
        return text;
    }
    format!(
        "{ENCODED}{CODEC}{}",
        URL_SAFE_NO_PAD.encode(native_bytes(path))
    )
}

/// Read the platform path representation without losing native bytes or UTF-16 units.
pub fn path_from_text(text: &str) -> io::Result<PathBuf> {
    let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "Invalid native path text.");
    if let Some(encoded) = text.strip_prefix(ENCODED) {
        let bytes = URL_SAFE_NO_PAD
            .decode(encoded.strip_prefix(CODEC).ok_or_else(invalid)?)
            .map_err(|_| invalid())?;
        return from_native_bytes(bytes)
            .map(PathBuf::from)
            .ok_or_else(invalid);
    }
    // Shown path text uses '/'; Windows' own spelling uses '\', which verbatim paths need and
    // every other path accepts.
    #[cfg(windows)]
    return Ok(PathBuf::from(text.replace('/', "\\")));
    #[cfg(not(windows))]
    Ok(PathBuf::from(text))
}

#[cfg(unix)]
fn readable(path: &Path) -> Option<String> {
    path.to_str().map(str::to_owned)
}

#[cfg(windows)]
fn readable(path: &Path) -> Option<String> {
    use std::path::Component;

    let text = path.to_str()?;
    let verbatim = matches!(path.components().next(), Some(Component::Prefix(prefix))
        if prefix.kind().is_verbatim());
    if verbatim {
        // A verbatim slash is literal; do not conflate it with an encoded backslash.
        if text.contains('/') {
            return None;
        }
        // Keep separator spellings a component walk would discard. In particular, an
        // ordinary path may ignore a trailing separator a verbatim path passes through.
        if text
            .strip_prefix(r"\\?\")
            .is_some_and(|tail| !tail.contains(r"\\"))
            && let Some(plain) = super::plain(path).as_deref().and_then(Path::to_str)
            && (!text.ends_with('\\') || plain.ends_with('\\'))
        {
            return Some(plain.replace('\\', "/"));
        }
        return Some(text.replace('\\', "/"));
    }
    let display = text.replace('\\', "/");
    (!display.starts_with(VERBATIM)).then_some(display)
}

#[cfg(unix)]
fn native_bytes(path: &Path) -> Vec<u8> {
    use std::os::unix::ffi::OsStrExt;
    path.as_os_str().as_bytes().to_vec()
}

#[cfg(unix)]
fn from_native_bytes(bytes: Vec<u8>) -> Option<OsString> {
    use std::os::unix::ffi::OsStringExt;
    Some(OsString::from_vec(bytes))
}

#[cfg(windows)]
fn native_bytes(path: &Path) -> Vec<u8> {
    use std::os::windows::ffi::OsStrExt;
    path.as_os_str()
        .encode_wide()
        .flat_map(u16::to_le_bytes)
        .collect()
}

#[cfg(windows)]
fn from_native_bytes(bytes: Vec<u8>) -> Option<OsString> {
    use std::os::windows::ffi::OsStringExt;
    let (units, rest) = bytes.as_chunks();
    rest.is_empty().then(|| {
        OsString::from_wide(
            &units
                .iter()
                .copied()
                .map(u16::from_le_bytes)
                .collect::<Vec<_>>(),
        )
    })
}

#[cfg(test)]
mod tests;