artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    ffi::{OsStr, OsString},
    fs::OpenOptions,
    io,
    os::windows::{
        ffi::{OsStrExt, OsStringExt},
        fs::OpenOptionsExt,
        io::AsRawHandle,
    },
    path::Path,
};

use windows_sys::{
    Wdk::System::SystemServices::RtlUpcaseUnicodeChar,
    Win32::{
        Foundation::{ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED},
        Storage::FileSystem::{
            FILE_CASE_SENSITIVE_INFO, FILE_READ_ATTRIBUTES, FileCaseSensitiveInfo,
            GetFileInformationByHandleEx,
        },
        System::SystemServices::FILE_CS_FLAG_CASE_SENSITIVE_DIR,
    },
};

use super::NamePolicy;

pub(super) fn name_policy(path: &Path) -> io::Result<NamePolicy> {
    case_sensitive(path).map(|sensitive| {
        if sensitive {
            NamePolicy::Literal
        } else {
            NamePolicy::Folded
        }
    })
}

fn case_sensitive(path: &Path) -> io::Result<bool> {
    let directory = super::super::files::open_no_follow(
        OpenOptions::new().access_mode(FILE_READ_ATTRIBUTES),
        path,
    )?;
    let mut info = FILE_CASE_SENSITIVE_INFO::default();
    // SAFETY: the directory and the correctly sized output buffer remain live.
    if unsafe {
        GetFileInformationByHandleEx(
            directory.as_raw_handle(),
            FileCaseSensitiveInfo,
            (&raw mut info).cast(),
            std::mem::size_of_val(&info) as u32,
        )
    } != 0
    {
        return Ok(info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0);
    }
    let error = io::Error::last_os_error();
    match error.raw_os_error().map(|code| code as u32) {
        // The Win32 default on filesystems that do not implement per-directory opt-in.
        Some(ERROR_INVALID_FUNCTION | ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED) => Ok(false),
        _ => Err(error),
    }
}

pub(super) fn fold(name: &OsStr) -> OsString {
    // NT path lookup upcases individual UTF-16 units, not full linguistically cased
    // strings. Avoid expanding a name into multiple characters or losing invalid UTF-16.
    let upper: Vec<u16> = name
        .encode_wide()
        // SAFETY: RtlUpcaseUnicodeChar is a pure single UTF-16 code unit mapping.
        .map(|unit| unsafe { RtlUpcaseUnicodeChar(unit) })
        .collect();
    OsString::from_wide(&upper)
}