1use super::provenance::path_traverses_symlink_parent;
14use super::WorkspaceIndex;
15use crate::paths::normalize_path;
16use std::collections::{HashMap, HashSet};
17use std::ffi::OsString;
18use std::path::{Component, Path, PathBuf};
19use std::sync::OnceLock;
20
21#[inline]
22fn has_parent_dir(path: &Path) -> bool {
23 path.components().any(|c| matches!(c, Component::ParentDir))
24}
25
26#[derive(Debug, Clone)]
27struct OriginMeta {
28 raw: PathBuf,
29 norm: PathBuf,
30 canon: Option<PathBuf>,
31 has_dotdot: bool,
32}
33
34#[derive(Debug, Clone)]
35struct ReaderPathMeta {
36 origin_id: Option<u32>,
37 norm_source_root: Option<PathBuf>,
38 canon_source_root: Option<PathBuf>,
39 is_dep: bool,
40}
41
42#[derive(Debug, Clone)]
43struct EntryFsMeta {
44 canon: Option<PathBuf>,
45 traverses_symlink: bool,
46}
47
48#[derive(Debug, Clone)]
49struct UniquePathEntry {
50 entry_str: String,
51 origin_id: Option<u32>,
52 entry_orig: PathBuf,
53 norm_entry: PathBuf,
54 fs_meta: OnceLock<EntryFsMeta>,
56 phase1: Vec<(u32, u32, u64)>,
57 phase2: Vec<(u32, u32, u64)>,
58}
59
60#[derive(Debug, Clone, Default)]
62pub struct PathIndex {
63 generation: u64,
64 reader_count: usize,
65 origins: Vec<OriginMeta>,
66 readers_meta: Vec<ReaderPathMeta>,
67 entries: Vec<UniquePathEntry>,
68 by_key: HashMap<PathBuf, Vec<u32>>,
69 by_file_name: HashMap<OsString, Vec<u32>>,
70 dotdot_uids: Vec<u32>,
71 bare_reader_files: Vec<String>,
72 pub(crate) blast_radius: super::navigation::BlastRadiusIndex,
73}
74
75mod build;
76
77impl PathIndex {
78 #[inline]
79 pub(crate) fn is_current(&self, ws: &WorkspaceIndex) -> bool {
80 (self.generation, self.reader_count) == (ws.generation, ws.readers.len()) && self.generation > 0
81 }
82
83 pub fn may_match_fast_path(&self, ws: &WorkspaceIndex, file_path: &str) -> bool {
85 if (self.generation, self.reader_count) != (ws.generation, ws.readers.len()) {
86 return true;
87 }
88 if self.entries.len() <= 64 {
89 return true;
90 }
91 let p = Path::new(file_path);
92 let Some(fname) = p.file_name() else {
93 return false;
94 };
95 if self.by_file_name.contains_key(fname) {
96 return true;
97 }
98 let fname_str = fname.to_str().unwrap_or("");
99 if self.bare_reader_files.iter().any(|b| fname_str.ends_with(b.as_str())) {
100 return true;
101 }
102 p.parent().is_none_or(|par| par.as_os_str().is_empty() || ws.workspace_root.as_deref() == Some(par) || self.origins.iter().any(|o| o.raw == par))
103 }
104
105 pub fn shard_mtime_slow(&self, ws: &WorkspaceIndex, file_path: &str) -> Option<std::time::SystemTime> {
107 let (idx, _) = self.resolve_checked(ws, file_path, false)?;
108 ws.mtimes.get(idx).copied().flatten()
109 }
110
111 pub fn source_hash_slow(&self, ws: &WorkspaceIndex, file_path: &str) -> Option<u64> {
113 self.resolve_checked(ws, file_path, true).map(|(_, h)| h)
114 }
115
116 fn resolve_checked(&self, ws: &WorkspaceIndex, file_path: &str, want_hash: bool) -> Option<(usize, u64)> {
117 if (self.generation, self.reader_count) != (ws.generation, ws.readers.len()) {
118 return Self::build(ws).resolve_slow(ws, file_path, want_hash);
119 }
120 self.resolve_slow(ws, file_path, want_hash)
121 }
122
123 fn resolve_slow(&self, ws: &WorkspaceIndex, file_path: &str, want_hash: bool) -> Option<(usize, u64)> {
124 let p = Path::new(file_path);
125 let explicit_origin = match ws.workspace_root.as_deref().or(ws.root_dir.as_deref()) {
126 Some(origin) => Some(origin),
127 None if ws.readers.len() == 1 => ws.source_roots.first().and_then(|r| r.as_deref()),
128 None => None,
129 };
130
131 let (ws_abs, req_canon) = if p.is_absolute() {
132 (None, p.canonicalize().ok())
133 } else if let Some(origin) = explicit_origin {
134 let abs = origin.join(p);
135 let canon = abs.canonicalize().ok();
136 (Some(abs), canon)
137 } else {
138 (None, None)
139 };
140 let ws_canon = req_canon.clone();
141 let norm_p = normalize_path(p);
142 let norm_ws_abs = ws_abs.as_deref().map(normalize_path);
143
144 let p_trav = has_parent_dir(p) && path_traverses_symlink_parent(p);
145 let abs_trav = ws_abs.as_deref().is_some_and(|a| has_parent_dir(a) && path_traverses_symlink_parent(a));
146 let matches_uid = |uid: u32| -> bool {
147 self.entry_matches_single(uid, p, &norm_p, req_canon.as_deref(), p_trav)
148 || ws_abs.as_deref().is_some_and(|abs_req| self.entry_matches_single(uid, abs_req, norm_ws_abs.as_deref().unwrap_or(abs_req), ws_canon.as_deref(), abs_trav))
149 };
150
151 let mut matching_uids: Vec<u32> = Vec::new();
152 if self.entries.len() <= 64 {
153 for uid in 0..self.entries.len() as u32 {
154 if matches_uid(uid) {
155 matching_uids.push(uid);
156 }
157 }
158 } else {
159 let mut seen = HashSet::new();
160 let mut check_slice = |slice: Option<&Vec<u32>>, out: &mut Vec<u32>| {
161 for &uid in slice.into_iter().flatten() {
162 if seen.insert(uid) && matches_uid(uid) {
163 out.push(uid);
164 }
165 }
166 };
167 for key in [Some(p), Some(norm_p.as_path()), req_canon.as_deref(), ws_abs.as_deref(), norm_ws_abs.as_deref()].into_iter().flatten() {
168 check_slice(self.by_key.get(key), &mut matching_uids);
169 }
170 check_slice(Some(&self.dotdot_uids), &mut matching_uids);
171 if matching_uids.is_empty() && (req_canon.is_some() || p.is_relative()) {
172 for fname in [p.file_name(), norm_p.file_name(), req_canon.as_deref().and_then(Path::file_name)].into_iter().flatten() {
173 check_slice(self.by_file_name.get(fname), &mut matching_uids);
174 }
175 }
176 }
177 if matching_uids.is_empty() {
178 return None;
179 }
180
181 let tier_of = |i: usize| -> u8 {
182 let rmeta = &self.readers_meta[i];
183 if req_canon.as_ref().zip(rmeta.canon_source_root.as_ref()).is_some_and(|(c_p, c_root)| c_p.starts_with(c_root)) {
184 return 0;
185 }
186 if let Some(ref n_abs) = norm_ws_abs {
187 if rmeta.norm_source_root.as_ref().is_some_and(|n_root| n_abs.starts_with(n_root)) {
188 return 1;
189 }
190 } else if p.is_absolute() && rmeta.norm_source_root.as_ref().is_some_and(|n_root| norm_p.starts_with(n_root)) {
191 return 1;
192 }
193 if !rmeta.is_dep {
194 2
195 } else {
196 3
197 }
198 };
199
200 let pick_best = |phase1: bool| -> Option<(usize, u64)> {
201 let mut best = None;
202 for &uid in &matching_uids {
203 let list = if phase1 { &self.entries[uid as usize].phase1 } else { &self.entries[uid as usize].phase2 };
204 for &(r_idx, ord, h) in list {
205 if want_hash && h == 0 {
206 continue;
207 }
208 let rank = (tier_of(r_idx as usize), r_idx, ord);
209 if best.is_none_or(|(best_rank, _)| rank < best_rank) {
210 best = Some((rank, (r_idx as usize, h)));
211 }
212 }
213 }
214 best.map(|(_, res)| res)
215 };
216 pick_best(true).or_else(|| pick_best(false))
217 }
218
219 fn entry_matches_single(&self, uid: u32, req_path: &Path, norm_req: &Path, req_canon: Option<&Path>, req_traverses_symlink: bool) -> bool {
220 let entry = &self.entries[uid as usize];
221 let req_str = req_path.to_str().unwrap_or("");
222 if entry.entry_str.is_empty() {
223 return false;
224 }
225 if entry.entry_str == req_str || entry.entry_orig == req_path {
226 return true;
227 }
228
229 let orig_meta = entry.origin_id.map(|oid| &self.origins[oid as usize]);
230 if req_canon.is_none() {
231 if req_path.is_absolute() || entry.norm_entry.is_relative() {
232 if entry.norm_entry != norm_req {
233 return false;
234 }
235 } else if orig_meta.is_none() {
236 return false;
237 }
238 }
239
240 let compute_fs = || EntryFsMeta {
241 canon: entry.entry_orig.canonicalize().ok(),
242 traverses_symlink: has_parent_dir(&entry.entry_orig) && path_traverses_symlink_parent(&entry.entry_orig),
243 };
244 let owned_fs;
245 let fs_meta = if entry.entry_orig.is_absolute() {
246 entry.fs_meta.get_or_init(compute_fs)
247 } else {
248 owned_fs = compute_fs();
249 &owned_fs
250 };
251
252 if let (Some(ref c_entry), Some(c_req)) = (&fs_meta.canon, req_canon) {
253 return c_entry == c_req;
254 }
255
256 let lexical_match = if req_path.is_absolute() || entry.norm_entry.is_relative() {
257 entry.norm_entry == norm_req
258 } else if let Some(orig) = orig_meta {
259 let matches_rel = |base: &Path, full: &Path| full.strip_prefix(base).is_ok_and(|rel| rel == norm_req || normalize_path(rel) == norm_req);
260 matches_rel(&orig.norm, &entry.norm_entry) || fs_meta.canon.as_ref().zip(orig.canon.as_ref()).is_some_and(|(ce, co)| matches_rel(co, ce))
261 } else {
262 false
263 };
264 if !lexical_match {
265 return false;
266 }
267
268 let req_has_dotdot = has_parent_dir(req_path);
269 !(fs_meta.traverses_symlink
270 || req_traverses_symlink
271 || orig_meta.is_some_and(|orig| (orig.has_dotdot || req_has_dotdot) && path_traverses_symlink_parent(&orig.raw.join(req_path))))
272 }
273}