1use std::{
10 collections::{BTreeMap, BTreeSet},
11 fs,
12 sync::Arc,
13};
14
15use super::{Cache, sync::kind_of};
16use crate::{
17 Config, RepoPath, RepoRoot, Result, Stat, Tree,
18 walk::{self, Keep, WalkedDir, WalkedFile, innermost},
19};
20
21impl Cache {
22 pub fn set_hint(&self, paths: Vec<RepoPath>) {
25 *self.hint.borrow_mut() = Some(paths);
26 }
27
28 pub fn drop_hint(&self) {
31 *self.hint.borrow_mut() = None;
32 self.missed.set(false);
33 }
34
35 pub fn note_missing(&self) {
39 if self.hint.borrow().is_some() && !self.is_fresh() {
40 self.missed.set(true);
41 }
42 }
43
44 pub fn missed(&self) -> bool {
47 self.missed.get()
48 }
49
50 pub fn hint(&self) -> Option<Vec<RepoPath>> {
53 self.hint.borrow().clone()
54 }
55
56 pub fn tree_from_store(
71 &self,
72 root: &RepoRoot,
73 config: &Config,
74 changed: &[RepoPath],
75 ) -> Result<Tree> {
76 if self.is_fresh() {
77 return walk::collect(root, config);
78 }
79 let roots = config.roots.clone();
80 let hints = scopes(changed);
81 if covers_root(&hints, &roots) {
83 return walk::collect(root, config);
84 }
85 let mut files = self.stored_files();
86 drop_scopes(&mut files, &hints);
87 let mut dirs = self.stored_dirs();
88 let hint_keys = keys(&hints);
89 dirs.retain(|d, _| !in_scope(&hint_keys, d.as_str()));
90
91 let mut seen = BTreeSet::new();
92 let mut found_dirs = Vec::new();
93 let mut outside = BTreeSet::new();
94 for path in &hints {
95 if innermost(&roots, path).is_none() {
96 outside.insert(path.clone());
97 continue;
98 }
99 let listed =
100 walk::list_under_root(root, &roots, path, &mut seen, &mut files, &mut found_dirs)?;
101 let mut dir = path.parent();
102 while let Some(d) = dir {
103 let Some(owner) = innermost(&roots, &d) else {
104 break;
105 };
106 if listed {
107 dirs.entry(d.clone()).or_insert(owner);
108 } else if is_walked_dir(root, &roots[owner], &d) {
109 break;
110 } else {
111 dirs.remove(&d);
112 }
113 dir = d.parent();
114 }
115 }
116 if !outside.is_empty() {
117 let above: BTreeSet<RepoPath> = outside
120 .iter()
121 .flat_map(|h| std::iter::successors(h.parent(), RepoPath::parent))
122 .collect();
123 let scope: Vec<String> = outside.iter().map(ToString::to_string).collect();
124 let keep: Keep =
125 Arc::new(move |p: &RepoPath| above.contains(p) || in_scope(&scope, p.as_str()));
126 let outside_keys = keys(&outside);
127 files.extend(
128 walk::walk_outside(root, config, Some(keep))?
129 .into_iter()
130 .filter(|f| in_scope(&outside_keys, f.path.as_str())),
131 );
132 }
133 for d in found_dirs {
134 dirs.insert(d.path, d.root);
135 }
136 let mut tree = Tree::new(
137 root.clone(),
138 roots,
139 files,
140 dirs.into_iter()
141 .map(|(path, root)| WalkedDir { path, root })
142 .collect(),
143 );
144 tree.registered_count = config.registered_count;
145 Ok(tree)
146 }
147
148 fn stored_files(&self) -> Vec<WalkedFile> {
151 let mut files = Vec::new();
152 if let Ok(mut stmt) = self
153 .conn()
154 .prepare("SELECT path, kind, root, len, mtime FROM files ORDER BY path")
155 && let Ok(mut rows) = stmt.query([])
156 {
157 while let Ok(Some(r)) = rows.next() {
158 let Some(path) = r
159 .get_ref(0)
160 .ok()
161 .and_then(|v| v.as_str().ok())
162 .and_then(RepoPath::parse)
163 else {
164 continue;
165 };
166 let (Ok(kind), Ok(owner), Ok(len), Ok(mtime)) = (
167 r.get::<_, u8>(1),
168 r.get::<_, Option<usize>>(2),
169 r.get::<_, u64>(3),
170 r.get::<_, Option<i64>>(4),
171 ) else {
172 continue;
173 };
174 files.push(WalkedFile {
175 path,
176 root: owner,
177 kind: kind_of(kind),
178 stat: Stat { len, mtime },
179 });
180 }
181 }
182 files
183 }
184
185 pub(super) fn stored_dirs(&self) -> BTreeMap<RepoPath, usize> {
188 self.conn()
189 .rows("SELECT path, root FROM dirs", [], |r| {
190 Ok((r.get::<_, String>(0)?, r.get::<_, usize>(1)?))
191 })
192 .into_iter()
193 .filter_map(|(path, owner)| Some((RepoPath::parse(&path)?, owner)))
194 .collect()
195 }
196}
197
198pub(super) fn scopes(changed: &[RepoPath]) -> BTreeSet<RepoPath> {
202 let all: BTreeSet<&RepoPath> = changed.iter().collect();
203 all.iter()
204 .filter(|p| !std::iter::successors(p.parent(), RepoPath::parent).any(|a| all.contains(&a)))
205 .map(|p| (*p).clone())
206 .collect()
207}
208
209pub(super) fn covers_root(hints: &BTreeSet<RepoPath>, roots: &[RepoPath]) -> bool {
212 let keys = keys(hints);
213 roots.iter().any(|r| in_scope(&keys, r.as_str()))
214}
215
216fn in_scope<S: AsRef<str>>(hints: &[S], path: &str) -> bool {
220 let mut p = path;
221 loop {
222 if hints.binary_search_by(|h| h.as_ref().cmp(p)).is_ok() {
223 return true;
224 }
225 match p.rfind('/') {
226 Some(0) if p.len() > 1 => p = "/",
227 Some(i) if i > 0 => p = &p[..i],
228 _ => return false,
229 }
230 }
231}
232
233fn keys(hints: &BTreeSet<RepoPath>) -> Vec<&str> {
235 hints.iter().map(RepoPath::as_str).collect()
236}
237
238fn drop_scopes(files: &mut Vec<WalkedFile>, hints: &BTreeSet<RepoPath>) {
242 let mut ranges: Vec<(usize, usize)> = Vec::new();
243 for h in hints {
244 if let Ok(i) = files.binary_search_by(|f| f.path.cmp(h)) {
245 ranges.push((i, i + 1));
246 }
247 let (low, high) = under(h);
248 let start = files.partition_point(|f| f.path.as_str() < low.as_str());
249 let end = files.partition_point(|f| f.path.as_str() < high.as_str());
250 if start < end {
251 ranges.push((start, end));
252 }
253 }
254 if ranges.is_empty() {
255 return;
256 }
257 ranges.sort_unstable();
258 let (mut index, mut next) = (0, 0);
259 files.retain(|_| {
260 while next < ranges.len() && ranges[next].1 <= index {
261 next += 1;
262 }
263 let dropped = next < ranges.len() && ranges[next].0 <= index;
264 index += 1;
265 !dropped
266 });
267}
268
269pub(super) fn under(path: &RepoPath) -> (String, String) {
273 let low = if path.as_str() == "/" {
274 "/".to_string()
275 } else {
276 format!("{path}/")
277 };
278 let high = format!("{}0", &low[..low.len() - 1]);
281 (low, high)
282}
283
284fn is_walked_dir(root: &RepoRoot, owner: &RepoPath, dir: &RepoPath) -> bool {
288 std::iter::successors(Some(dir.clone()), RepoPath::parent)
289 .take_while(|d| d != owner && d.starts_with(owner))
290 .all(|d| fs::symlink_metadata(d.to_fs(root)).is_ok_and(|m| m.is_dir()))
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 fn p(s: &str) -> RepoPath {
298 RepoPath::parse(s).unwrap()
299 }
300
301 #[test]
302 fn scopes_drop_a_path_under_another() {
303 let got = scopes(&[p("/a/b.md"), p("/a-b"), p("/a"), p("/a"), p("/c")]);
304 assert_eq!(got, [p("/a"), p("/a-b"), p("/c")].into());
305 assert!(in_scope(&keys(&got), "/a/b/c"));
306 assert!(!in_scope(&keys(&got), "/a-c"));
307 assert!(in_scope(&["/"], "/a/b"));
308 assert!(covers_root(&got, &[p("/a/k")]));
309 assert!(!covers_root(&got, &[p("/k")]));
310 }
311
312 #[test]
313 fn drop_scopes_removes_each_hinted_path_and_the_paths_under_it() {
314 let file = |s: &str| WalkedFile {
315 path: p(s),
316 root: None,
317 kind: crate::FileKind::Candidate,
318 stat: Stat::default(),
319 };
320 let mut files: Vec<WalkedFile> =
321 ["/a", "/a-b", "/a-b/c", "/a/b", "/a/c/d", "/a0", "/b", "/c"]
322 .into_iter()
323 .map(file)
324 .collect();
325 drop_scopes(&mut files, &[p("/a"), p("/c")].into());
326 let left: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
327 assert_eq!(left, ["/a-b", "/a-b/c", "/a0", "/b"]);
328 }
329
330 #[test]
331 fn under_bounds_the_paths_below_a_directory() {
332 let (low, high) = under(&p("/a"));
333 for inside in ["/a/b", "/a/b/c", "/a/~"] {
334 assert!(low.as_str() <= inside && inside < high.as_str(), "{inside}");
335 }
336 for outside in ["/a", "/a-b", "/a0", "/ab", "/b"] {
337 assert!(
338 !(low.as_str() <= outside && outside < high.as_str()),
339 "{outside}"
340 );
341 }
342 assert_eq!(under(&p("/")), ("/".to_string(), "0".to_string()));
343 }
344}