1use std::path::{Path, PathBuf};
15
16pub fn normalize_path(path: &Path) -> PathBuf {
21 use std::path::Component;
22 let mut components = Vec::new();
23 for c in path.components() {
24 match c {
25 Component::CurDir => {}
26 Component::ParentDir => {
27 if let Some(Component::Normal(_)) = components.last() {
28 components.pop();
29 } else if !components.iter().any(|comp| matches!(comp, Component::RootDir | Component::Prefix(_))) {
30 components.push(c);
31 }
32 }
33 _ => components.push(c),
34 }
35 }
36 components.into_iter().collect()
37}
38
39pub fn canonicalize_best_effort(path: &Path) -> PathBuf {
42 if let Ok(canon) = std::fs::canonicalize(path) {
43 return canon;
44 }
45 for ancestor in path.ancestors().skip(1) {
46 if ancestor.as_os_str().is_empty() {
47 continue;
48 }
49 if let Ok(canon_ancestor) = std::fs::canonicalize(ancestor) {
50 if let Ok(tail) = path.strip_prefix(ancestor) {
51 return normalize_path(&canon_ancestor.join(tail));
52 }
53 }
54 }
55 normalize_path(path)
56}
57
58pub fn canonicalize_cached(path: &Path) -> PathBuf {
61 use std::collections::HashMap;
62 use std::sync::{Mutex, OnceLock};
63 static MEMO: OnceLock<Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
64 let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));
65 if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(path) {
66 return hit.clone();
67 }
68 let canon = canonicalize_best_effort(path);
69 let mut m = memo.lock().unwrap_or_else(|e| e.into_inner());
70 if m.len() >= 16_384 {
71 m.clear();
72 }
73 m.insert(path.to_path_buf(), canon.clone());
74 canon
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn canonicalize_best_effort_resolves_symlink_prefix_for_missing_descendant() {
83 let dir = std::env::temp_dir().join(format!("ridx_paths_test_{}", std::process::id()));
84 let _ = std::fs::remove_dir_all(&dir);
85 let real_sub = dir.join("real");
86 std::fs::create_dir_all(&real_sub).unwrap();
87
88 #[cfg(unix)]
89 {
90 let link_sub = dir.join("link");
91 std::os::unix::fs::symlink(&real_sub, &link_sub).unwrap();
92
93 let expected = std::fs::canonicalize(&real_sub).unwrap().join("missing/leaf.rs");
94 let via_link = canonicalize_best_effort(&link_sub.join("missing/./sub/../leaf.rs"));
95 assert_eq!(via_link, expected);
96
97 assert_eq!(canonicalize_best_effort(Path::new("no_such_dir/a/../b.rs")), PathBuf::from("no_such_dir/b.rs"));
99 }
100
101 let _ = std::fs::remove_dir_all(&dir);
102 }
103}