use std::path::{Path, PathBuf};
pub fn normalize_path(path: &Path) -> PathBuf {
use std::path::Component;
let mut components = Vec::new();
for c in path.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
if let Some(Component::Normal(_)) = components.last() {
components.pop();
} else if !components.iter().any(|comp| matches!(comp, Component::RootDir | Component::Prefix(_))) {
components.push(c);
}
}
_ => components.push(c),
}
}
components.into_iter().collect()
}
pub fn canonicalize_best_effort(path: &Path) -> PathBuf {
if let Ok(canon) = std::fs::canonicalize(path) {
return canon;
}
for ancestor in path.ancestors().skip(1) {
if ancestor.as_os_str().is_empty() {
continue;
}
if let Ok(canon_ancestor) = std::fs::canonicalize(ancestor) {
if let Ok(tail) = path.strip_prefix(ancestor) {
return normalize_path(&canon_ancestor.join(tail));
}
}
}
normalize_path(path)
}
pub fn canonicalize_cached(path: &Path) -> PathBuf {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static MEMO: OnceLock<Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(path) {
return hit.clone();
}
let canon = canonicalize_best_effort(path);
let mut m = memo.lock().unwrap_or_else(|e| e.into_inner());
if m.len() >= 16_384 {
m.clear();
}
m.insert(path.to_path_buf(), canon.clone());
canon
}
pub fn resolve_cached(path: &Path) -> Option<PathBuf> {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static MEMO: OnceLock<Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(path) {
return Some(hit.clone());
}
let resolved = std::fs::canonicalize(path).ok()?;
let mut m = memo.lock().unwrap_or_else(|e| e.into_inner());
if m.len() >= 16_384 {
m.clear();
}
m.insert(path.to_path_buf(), resolved.clone());
Some(resolved)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonicalize_best_effort_resolves_symlink_prefix_for_missing_descendant() {
let dir = std::env::temp_dir().join(format!("ridx_paths_test_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let real_sub = dir.join("real");
std::fs::create_dir_all(&real_sub).unwrap();
#[cfg(unix)]
{
let link_sub = dir.join("link");
std::os::unix::fs::symlink(&real_sub, &link_sub).unwrap();
let expected = std::fs::canonicalize(&real_sub).unwrap().join("missing/leaf.rs");
let via_link = canonicalize_best_effort(&link_sub.join("missing/./sub/../leaf.rs"));
assert_eq!(via_link, expected);
assert_eq!(canonicalize_best_effort(Path::new("no_such_dir/a/../b.rs")), PathBuf::from("no_such_dir/b.rs"));
}
let _ = std::fs::remove_dir_all(&dir);
}
}