use std::path::{Path, PathBuf};
use crate::env::Os;
pub trait UncResolver: Send + Sync {
fn universal_name(&self, path: &Path) -> Option<PathBuf>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoUnc;
impl UncResolver for NoUnc {
fn universal_name(&self, _path: &Path) -> Option<PathBuf> {
None
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemUnc;
impl UncResolver for SystemUnc {
fn universal_name(&self, path: &Path) -> Option<PathBuf> {
if !cfg!(windows) || !is_drive_path(path) {
return None;
}
let resolved = std::fs::canonicalize(path).ok()?;
let text = resolved.to_str()?;
text.strip_prefix(r"\\?\UNC\")
.map(|rest| PathBuf::from(format!(r"\\{rest}")))
}
}
pub fn is_drive_path(path: &Path) -> bool {
let bytes = path.as_os_str().as_encoded_bytes();
bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& matches!(bytes[2], b'\\' | b'/')
}
pub fn resolve(os: Os, resolver: &dyn UncResolver, typed: &Path) -> PathBuf {
if os == Os::Windows && is_drive_path(typed) {
resolver
.universal_name(typed)
.unwrap_or_else(|| typed.to_path_buf())
} else {
typed.to_path_buf()
}
}