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;
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))
}
pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
std::fs::read_link(path)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
File,
Directory,
Symlink,
Other,
}
pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
canonicalize(&std::env::current_dir()?)
}
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())
}
}
pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
path.path_text()
}
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 {
const MAX_COMPONENT_BYTES: usize = 255;
name.len() <= MAX_COMPONENT_BYTES && ordinary_windows_basename(name)
}
fn ordinary_windows_basename(name: &str) -> bool {
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;