Skip to main content

artifactize_foundation/platform/
files.rs

1//! Native, no-follow access and path normalization.
2
3use std::path::Path;
4
5mod text;
6use text::native_path_text;
7pub use text::path_from_text;
8
9#[cfg(unix)]
10mod unix;
11#[cfg(target_os = "linux")]
12pub(super) use unix::native_case_sensitive;
13#[cfg(unix)]
14pub(in crate::platform) use unix::terminal_component;
15#[cfg(windows)]
16mod windows;
17
18#[cfg(unix)]
19pub use unix::{
20    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
21    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
22};
23#[cfg(windows)]
24pub use windows::{
25    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
26    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
27};
28
29#[cfg(windows)]
30pub use windows::plain;
31
32/// The filesystem root of an absolute path (`/`, or a Windows volume or share) and the names
33/// below it, in order. `None` when a component is `.` or `..`.
34pub fn split_root(path: &std::path::Path) -> Option<(&std::path::Path, Vec<&std::ffi::OsStr>)> {
35    use std::path::Component;
36    let root = path.ancestors().last()?;
37    path.components()
38        .filter_map(|component| match component {
39            Component::Prefix(_) | Component::RootDir => None,
40            Component::Normal(name) => Some(Some(name)),
41            Component::CurDir | Component::ParentDir => Some(None),
42        })
43        .collect::<Option<Vec<_>>>()
44        .map(|names| (root, names))
45}
46
47/// The target a link names, read without following it: a symlink's text, or on Windows a
48/// junction's or symbolic link's substitute name.
49pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
50    std::fs::read_link(path)
51}
52
53/// The type of a directory entry, read without following it.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum FileKind {
56    File,
57    Directory,
58    Symlink,
59    /// FIFOs, sockets, devices, and on Windows reparse points that are not links.
60    Other,
61}
62
63/// Read the process's current directory and resolve its native filesystem aliases.
64pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
65    canonicalize(&std::env::current_dir()?)
66}
67
68/// Text shown for a native path or a logical external target, never an I/O conversion.
69pub trait PathText {
70    fn path_text(&self) -> String;
71}
72impl<P: AsRef<std::path::Path> + ?Sized> PathText for P {
73    fn path_text(&self) -> String {
74        native_path_text(self.as_ref())
75    }
76}
77/// Render a path for people and JSON clients; logical external targets stay opaque.
78pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
79    path.path_text()
80}
81
82/// Open a regular file without following a link or reparse point in its last component.
83pub fn open_regular(path: &Path) -> std::io::Result<std::fs::File> {
84    let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
85    if !file.metadata()?.is_file() {
86        return Err(std::io::Error::new(
87            std::io::ErrorKind::InvalidInput,
88            "not a regular file",
89        ));
90    }
91    Ok(file)
92}
93
94pub(super) fn portable_basename(name: &str) -> bool {
95    // Use a common byte limit so a validated generated name fits Unix too.
96    const MAX_COMPONENT_BYTES: usize = 255;
97    name.len() <= MAX_COMPONENT_BYTES && ordinary_windows_basename(name)
98}
99
100/// A name the Win32 layer keeps as is: no trailing dot or space, no reserved character, and
101/// no DOS device name such as `NUL` or `com1.txt`.
102fn ordinary_windows_basename(name: &str) -> bool {
103    // Win32 recognizes ISO-8859-1 superscript 1, 2 and 3 as DOS COM/LPT digits too.
104    const DOS_PORT_DIGITS: &str = "0123456789¹²³";
105    let stem = name
106        .split('.')
107        .next()
108        .unwrap_or_default()
109        .trim_end_matches(' ');
110    let device = match stem.to_ascii_uppercase().as_str() {
111        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true,
112        port => port
113            .strip_prefix("COM")
114            .or_else(|| port.strip_prefix("LPT"))
115            .is_some_and(|number| {
116                number.chars().count() == 1
117                    && number.chars().all(|digit| DOS_PORT_DIGITS.contains(digit))
118            }),
119    };
120    !name.is_empty()
121        && !name.ends_with(['.', ' '])
122        && !name
123            .chars()
124            .any(|c| c < ' ' || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
125        && !device
126}
127
128#[cfg(test)]
129mod tests;