Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 65.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Reading a working copy: where it differs from its base, and the records
5//! of the stat cache for the next scan.
6//!
7//! The walk opens each directory once, by its name in its parent's handle
8//! and never through a symlink, and reads its entries once, taking their
9//! types from the listing where the platform gives them and asking for the
10//! metadata of files only. Directories are read in parallel. The walk skips
11//! `.braid`, `.git` and the names that alias them, braid's own scratch
12//! files, ignored paths that are not tracked, and untracked directories that
13//! are another workspace or repository. Files the stat cache cannot vouch
14//! for are hashed, in parallel.
15//!
16//! The base is read a directory at a time, where it is needed: a directory
17//! whose record says it was clean against the tree the base still has at its
18//! path, and whose entries still match their records, differs in nothing,
19//! and its tree is not read. A directory whose stamp says its entries did
20//! not change since the scan that recorded it is not listed either: its
21//! record stands for its listing, and only its files' metadata is read.
22//!
23//! A scan may cover only some paths, as committing those paths needs: it
24//! then reads only the directories on the way to them and below them, and
25//! makes no records. After a commit, the records of a scan of the whole
26//! working copy are brought onto the new base, so that the next scan finds
27//! the committed directories as the commit left them.
28
29use std::collections::{HashMap, HashSet};
30use std::ffi::OsStr;
31use std::io::{self, Read};
32use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
33use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
34use std::time::{Duration, SystemTime, UNIX_EPOCH};
35
36use braid_engine::read_tree;
37use braid_format::{ChangeOp, Entry, EntryKind, IdHasher, Kind, ObjectId, Objects};
38use cap_std::fs::Dir;
39use rayon::prelude::*;
40
41use crate::cache::{
42 Cache, CachedDir, DirRecord, FileRecord, KIND_EXECUTABLE, KIND_FILE, KIND_GITLINK, KIND_SUBDIR,
43 KIND_SYMLINK, KIND_TREE, Record,
44};
45use crate::error::Error;
46use crate::fsprobe::{FileSystem, SCRATCH_PREFIX};
47use crate::ignores::{self, Chain};
48use crate::paths::{ancestors, is_within, join, os_name};
49use crate::safe::{
50 DirStamp, Found, Root, Stat, StatKind, dir_stamp, list, open_child_dir, open_file, read_link,
51 stat_entry,
52};
53use crate::tree::leaves;
54
55/// How many threads read the working copy, at most. File systems serialise
56/// much of their work on names and metadata: past a few threads, more of
57/// them add contention, not speed.
58const THREADS: usize = 4;
59
60/// How many directory handles the walk keeps open for directories whose
61/// subdirectories are still to be read. Past this, a subdirectory is opened
62/// from the root again, one name at a time: deep trees read in parallel
63/// would otherwise hold a handle for every level on every thread.
64const HELD_HANDLES: usize = 128;
65
66/// A path where the working copy differs from the base.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub(crate) struct Delta {
69 pub path: Vec<u8>,
70 /// What the base has there: a file, a symlink or a gitlink.
71 pub old: Option<ChangeOp>,
72 /// What the working copy has there that counts.
73 pub new: Option<ChangeOp>,
74}
75
76/// What a scan found.
77#[derive(Debug)]
78pub(crate) struct Scan<'c> {
79 /// Every path where the working copy differs from the base, sorted.
80 pub deltas: Vec<Delta>,
81 /// The stat cache for the next scan, when this scan covered the whole
82 /// working copy.
83 pub cache: Option<Next<'c>>,
84 /// How many directories were listed, rather than taken from their
85 /// records.
86 #[cfg(test)]
87 pub listed: usize,
88}
89
90/// The stat cache a scan of the whole working copy leaves for the next.
91#[derive(Debug)]
92pub(crate) struct Next<'c> {
93 /// When the scan started, by the file system's clock.
94 pub time: (i64, u32),
95 /// Every directory's record, by path.
96 pub records: Vec<Record<'c>>,
97 /// Whether they say something the old cache does not.
98 pub changed: bool,
99}
100
101/// Scans the working copy at `root` against the base tree `base`, using
102/// `old` so that files and trees that did not change are not read again.
103/// `fs` says which names the file system takes for the same. Given paths in
104/// `scope`, only what lies at or below them is scanned; no paths, or the
105/// root among them, is the whole working copy.
106pub(crate) fn scan<'c, O: Objects + Sync>(
107 root: &Root,
108 objects: &O,
109 base: ObjectId,
110 old: &'c Cache,
111 fs: FileSystem,
112 scope: &[Vec<u8>],
113) -> Result<Scan<'c>, Error> {
114 scan_holding(root, objects, base, old, fs, scope, HELD_HANDLES)
115}
116
117/// [`scan`], keeping at most `held` directory handles open for directories
118/// still to read.
119fn scan_holding<'c, O: Objects + Sync>(
120 root: &Root,
121 objects: &O,
122 base: ObjectId,
123 old: &'c Cache,
124 fs: FileSystem,
125 scope: &[Vec<u8>],
126 held: usize,
127) -> Result<Scan<'c>, Error> {
128 let scope = Scope::of(scope);
129 let whole = matches!(scope, Scope::Whole);
130 let time = if whole {
131 root.file_system_now().unwrap_or_else(|_| fallback_now())
132 } else {
133 old.time()
134 };
135 let dir = root
136 .dir()
137 .try_clone()
138 .map_err(Error::io("open", root.path()))?;
139 let walk = Walk {
140 root,
141 objects,
142 old,
143 fs,
144 whole,
145 time,
146 held_limit: held,
147 held: AtomicUsize::new(0),
148 #[cfg(test)]
149 listed: AtomicUsize::new(0),
150 failed: AtomicBool::new(false),
151 out: Mutex::new(Out::default()),
152 };
153 let job = Job {
154 open: Open::Ready(dir),
155 path: Vec::new(),
156 base: Some(base),
157 rules: None,
158 ignored: false,
159 scope: scope.clone(),
160 };
161 let threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(THREADS));
162 match rayon::ThreadPoolBuilder::new().num_threads(threads).build() {
163 Ok(pool) => pool.scope(|s| walk.run(s, job)),
164 Err(_) => rayon::scope(|s| walk.run(s, job)),
165 }
166 #[cfg(test)]
167 let listed = walk.listed.into_inner();
168 let out = walk
169 .out
170 .into_inner()
171 .unwrap_or_else(PoisonError::into_inner);
172 if let Some(error) = out.error {
173 return Err(error);
174 }
175 let mut deltas = out.deltas;
176 if let Scope::Within(paths) = &scope {
177 // Removals found by reading the base may reach past the scope.
178 deltas.retain(|delta| paths.iter().any(|path| is_within(&delta.path, path)));
179 }
180 deltas.sort_unstable_by(|a, b| a.path.cmp(&b.path));
181 let cache = whole.then(|| {
182 let mut records = out.records;
183 records.sort_unstable_by(|a, b| a.path().cmp(b.path()));
184 Next {
185 time,
186 records,
187 changed: out.changed || out.seen != old.dir_count(),
188 }
189 });
190 Ok(Scan {
191 deltas,
192 cache,
193 #[cfg(test)]
194 listed,
195 })
196}
197
198/// The records of a scan of the whole working copy, brought onto a new
199/// base: one made from the scanned base by changing `paths`, whose tree is
200/// `root`. Only the directories on the way to those paths have new trees;
201/// each is compared with its new tree, from what its record says, so that
202/// the next scan finds it as this one left it.
203pub(crate) fn follow<'c, O: Objects>(
204 objects: &O,
205 records: Vec<Record<'c>>,
206 root: ObjectId,
207 paths: &[Vec<u8>],
208) -> Result<Vec<Record<'c>>, Error> {
209 let mut changed: HashSet<&[u8]> = paths.iter().flat_map(|path| ancestors(path)).collect();
210 changed.insert(b"");
211 // The new trees of those directories, each read once, from the root
212 // down.
213 let mut trees: HashMap<Vec<u8>, (ObjectId, Vec<Entry>)> = HashMap::new();
214 let mut pending = vec![(Vec::new(), root)];
215 while let Some((path, tree)) = pending.pop() {
216 let entries = read_tree(objects, tree)?;
217 for entry in &entries {
218 if let EntryKind::Tree { tree } = entry.kind {
219 let child = join(&path, &entry.name);
220 if changed.contains(child.as_slice()) {
221 pending.push((child, tree));
222 }
223 }
224 }
225 trees.insert(path, (tree, entries));
226 }
227 Ok(records
228 .into_iter()
229 .map(|record| {
230 if !changed.contains(record.path()) {
231 return record;
232 }
233 let dir = record.into_made();
234 let rebased = match trees.get(&dir.path) {
235 Some((tree, entries)) => rebased(dir, Some(*tree), entries),
236 None => rebased(dir, None, &[]),
237 };
238 Record::Made(rebased)
239 })
240 .collect())
241}
242
243/// A directory's record, compared with `tree`, whose entries are `entries`,
244/// instead of the tree it was made against.
245fn rebased(mut dir: DirRecord, tree: Option<ObjectId>, entries: &[Entry]) -> DirRecord {
246 let mut leaves = entries
247 .iter()
248 .filter(|entry| !matches!(entry.kind, EntryKind::Tree { .. }));
249 let mut same = true;
250 for file in &mut dir.files {
251 if file.kind >= KIND_TREE {
252 let subtree = match at_tree(entries, &file.name) {
253 At::Tree(subtree) => Some(subtree),
254 _ => None,
255 };
256 file.kind = if subtree.is_some() {
257 KIND_TREE
258 } else {
259 KIND_SUBDIR
260 };
261 file.blob = subtree.unwrap_or(ObjectId::from_bytes([0; 32]));
262 continue;
263 }
264 same &= leaves.next().is_some_and(|entry| {
265 let (kind, blob) = match &entry.kind {
266 EntryKind::File { blob, .. } => (KIND_FILE, Some(*blob)),
267 EntryKind::Executable { blob, .. } => (KIND_EXECUTABLE, Some(*blob)),
268 EntryKind::Symlink { blob, .. } => (KIND_SYMLINK, Some(*blob)),
269 _ => (KIND_GITLINK, None),
270 };
271 entry.name == file.name
272 && kind == file.kind
273 && blob.is_none_or(|blob| blob == file.blob)
274 });
275 }
276 let subtrees_there = entries.iter().all(|entry| match entry.kind {
277 EntryKind::Tree { .. } => dir
278 .files
279 .binary_search_by(|file| file.name.as_slice().cmp(&entry.name))
280 .is_ok_and(|index| dir.files[index].kind == KIND_TREE),
281 _ => true,
282 });
283 dir.clean = tree.is_some() && same && leaves.next().is_none() && subtrees_there;
284 dir.base = tree;
285 dir
286}
287
288/// What part of a directory a scan covers.
289#[derive(Clone, Debug)]
290enum Scope {
291 /// All of it.
292 Whole,
293 /// What lies at or below these paths, relative to it.
294 Within(Vec<Vec<u8>>),
295}
296
297impl Scope {
298 fn of(paths: &[Vec<u8>]) -> Scope {
299 if paths.is_empty() || paths.iter().any(|path| path.is_empty()) {
300 Scope::Whole
301 } else {
302 Scope::Within(paths.to_vec())
303 }
304 }
305
306 /// The part of the entry `name` covered, if any.
307 fn enter(&self, name: &[u8]) -> Option<Scope> {
308 let Scope::Within(paths) = self else {
309 return Some(Scope::Whole);
310 };
311 let mut below = Vec::new();
312 for path in paths {
313 if path.as_slice() == name {
314 return Some(Scope::Whole);
315 }
316 if path.len() > name.len() && path.starts_with(name) && path[name.len()] == b'/' {
317 let rest = &path[name.len() + 1..];
318 if rest.is_empty() {
319 return Some(Scope::Whole);
320 }
321 below.push(rest.to_vec());
322 }
323 }
324 (!below.is_empty()).then_some(Scope::Within(below))
325 }
326}
327
328/// One directory to read.
329struct Job<'s> {
330 open: Open<'s>,
331 path: Vec<u8>,
332 /// The base's tree at this path, if it has one.
333 base: Option<ObjectId>,
334 /// The ignore rules in force above it.
335 rules: Chain,
336 /// Whether it is ignored: inside, only what the base has counts.
337 ignored: bool,
338 scope: Scope,
339}
340
341/// How a job gets its directory's handle.
342enum Open<'s> {
343 /// It has it: the root.
344 Ready(Dir),
345 /// By its name in its parent's handle, which the parent's jobs share.
346 Child(Arc<Shared<'s>>, Vec<u8>),
347 /// From the root, one name at a time.
348 FromRoot,
349}
350
351/// A directory handle that jobs not started yet share, counted while it is
352/// open.
353struct Shared<'s> {
354 dir: Dir,
355 held: &'s AtomicUsize,
356}
357
358impl Drop for Shared<'_> {
359 fn drop(&mut self) {
360 self.held.fetch_sub(1, Ordering::Relaxed);
361 }
362}
363
364/// What every job adds to.
365#[derive(Default)]
366struct Out<'c> {
367 deltas: Vec<Delta>,
368 records: Vec<Record<'c>>,
369 /// Whether a record differs from the old cache's, or a file was read
370 /// whose record will vouch for it.
371 changed: bool,
372 /// How many directories read had a record in the old cache.
373 seen: usize,
374 error: Option<Error>,
375}
376
377/// What the base has at a name of a directory.
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379enum At {
380 Nothing,
381 /// A file, executable or symlink.
382 Leaf,
383 Gitlink,
384 Tree(ObjectId),
385}
386
387/// An entry of a directory, as listed.
388struct Listed {
389 name: Vec<u8>,
390 /// The listing says it is a directory.
391 dir: bool,
392}
393
394/// A file, symlink or gitlink of the working copy that counts.
395struct Counted {
396 name: Vec<u8>,
397 /// Its metadata; `None` for a gitlink's directory.
398 stat: Option<Stat>,
399 /// What it is now, once known; `None` for a gitlink, which is what the
400 /// base has.
401 op: Option<ChangeOp>,
402 /// Whether its record may vouch for it in the next scan.
403 vouches: bool,
404 /// Whether this scan read it.
405 read: bool,
406}
407
408impl Counted {
409 fn kind(&self) -> u8 {
410 match &self.op {
411 None => KIND_GITLINK,
412 Some(ChangeOp::Executable { .. }) => KIND_EXECUTABLE,
413 Some(ChangeOp::Symlink { .. }) => KIND_SYMLINK,
414 Some(_) => KIND_FILE,
415 }
416 }
417
418 fn blob(&self) -> Option<ObjectId> {
419 match &self.op {
420 Some(
421 ChangeOp::File { blob, .. }
422 | ChangeOp::Executable { blob, .. }
423 | ChangeOp::Symlink { blob, .. },
424 ) => Some(*blob),
425 _ => None,
426 }
427 }
428
429 fn record(self) -> FileRecord {
430 let kind = self.kind();
431 match (&self.stat, self.blob()) {
432 (Some(stat), Some(blob)) => FileRecord::new(self.name, stat, kind, self.vouches, blob),
433 _ => FileRecord::bare(self.name, kind, None),
434 }
435 }
436}
437
438/// What a directory holds, sorted by [`Walk::classify`].
439struct Sorted {
440 /// What counts, by name.
441 counted: Vec<Counted>,
442 /// The subdirectories to read, by name.
443 children: Vec<Child>,
444 /// Whether an entry was gone by the time it was looked at.
445 vanished: bool,
446}
447
448/// A subdirectory to read.
449struct Child {
450 name: Vec<u8>,
451 path: Vec<u8>,
452 base: Option<ObjectId>,
453 ignored: bool,
454 scope: Scope,
455}
456
457struct Walk<'a, 'c, O> {
458 root: &'a Root,
459 objects: &'a O,
460 old: &'c Cache,
461 fs: FileSystem,
462 /// Whether the scan covers the whole working copy.
463 whole: bool,
464 /// When the scan started, by the file system's clock.
465 time: (i64, u32),
466 /// How many directory handles to keep open for jobs not started yet.
467 held_limit: usize,
468 /// Directory handles kept open for jobs not started yet.
469 held: AtomicUsize,
470 /// Directories listed.
471 #[cfg(test)]
472 listed: AtomicUsize,
473 failed: AtomicBool,
474 out: Mutex<Out<'c>>,
475}
476
477impl<'a, 'c, O: Objects + Sync> Walk<'a, 'c, O> {
478 fn out(&self) -> MutexGuard<'_, Out<'c>> {
479 self.out.lock().unwrap_or_else(PoisonError::into_inner)
480 }
481
482 fn run<'s>(&'s self, scope: &rayon::Scope<'s>, job: Job<'s>) {
483 if self.failed.load(Ordering::Relaxed) {
484 return;
485 }
486 if let Err(error) = self.visit(scope, job) {
487 self.failed.store(true, Ordering::Relaxed);
488 self.out().error.get_or_insert(error);
489 }
490 }
491
492 fn visit<'s>(&'s self, scope: &rayon::Scope<'s>, job: Job<'s>) -> Result<(), Error> {
493 let Job {
494 open,
495 path,
496 base,
497 rules: above,
498 ignored,
499 scope: covered,
500 } = job;
501 let dir = match open {
502 Open::Ready(dir) => Some(dir),
503 Open::Child(parent, name) => {
504 let os = os_name(&name).ok_or_else(|| unrepresentable(&path))?;
505 let opened = open_child_dir(&parent.dir, os);
506 drop(parent);
507 opened.map_err(|err| self.root.error("open", &path, err))?
508 }
509 Open::FromRoot => match self.root.open_dir(&path)? {
510 Found::Here(dir) => Some(dir),
511 Found::Missing | Found::Blocked(_) => None,
512 },
513 };
514 let Some(dir) = dir else {
515 // Gone since its parent was read, or not a directory any more:
516 // what the base has there is not in the working copy.
517 return self.gone(&path, base);
518 };
519 if base.is_none() && holds_marker(&dir) {
520 // Another workspace or repository: not part of this one.
521 return Ok(());
522 }
523 let cached = self.old.dir(&path);
524 // Taken before the directory is listed: a change made while it is
525 // listed shows in the next scan.
526 let stamp = if self.whole { dir_stamp(&dir) } else { None };
527
528 // The base's tree is read unless the directory's record may stand
529 // for it: the directory was clean against the same tree.
530 let whole = matches!(covered, Scope::Whole);
531 let trusted = whole
532 && base.is_some()
533 && cached.is_some_and(|record| record.clean() && record.base() == base);
534 let mut tree: Option<Vec<Entry>> = match base {
535 Some(id) if !trusted => Some(read_tree(self.objects, id)?),
536 _ => None,
537 };
538
539 // The record stands for the listing while the directory did not
540 // change; the listing is read when it did, or when an entry the
541 // record names turns out to be gone.
542 let mut record_lists = cached.filter(|record| {
543 self.whole && record_holds(record, base, ignored, stamp, self.old.time())
544 });
545 let (found, rules, ignore_files) = loop {
546 let at = |name: &[u8]| match (&tree, cached) {
547 (Some(entries), _) => at_tree(entries, name),
548 (None, Some(record)) if trusted => at_record(&record, name),
549 _ => At::Nothing,
550 };
551 if let Some(record) = record_lists.take() {
552 let files = ignores::from_bits(record.ignore_files());
553 let rules = if ignored {
554 above.clone()
555 } else {
556 ignores::enter(&dir, &path, &above, &files)
557 };
558 // A name that the listing could not have given, as a damaged
559 // or forged cache could hold, is never looked up.
560 if ignores::digest(&rules) != record.rules()
561 || record
562 .files()
563 .any(|entry| !one_name(entry.name) || skipped(entry.name))
564 {
565 continue;
566 }
567 let listed = record
568 .files()
569 .map(|entry| Listed {
570 name: entry.name.to_vec(),
571 dir: entry.kind >= KIND_GITLINK,
572 })
573 .collect();
574 let found =
575 self.classify(&dir, &path, listed, &rules, ignored, &covered, &at, cached)?;
576 if !found.vanished {
577 break (found, rules, record.ignore_files());
578 }
579 continue;
580 }
581 let listed = self.list(&dir, &path)?;
582 let files = ignores::ignore_files(self.fs, listed.iter().map(|e| e.name.as_slice()));
583 let ignore_files = ignores::bits(&files);
584 let rules = if ignored {
585 above.clone()
586 } else {
587 ignores::enter(&dir, &path, &above, &files)
588 };
589 let found =
590 self.classify(&dir, &path, listed, &rules, ignored, &covered, &at, cached)?;
591 break (found, rules, ignore_files);
592 };
593 let Sorted {
594 counted, children, ..
595 } = found;
596 let counted = self.hash(&dir, &path, counted)?;
597
598 let clean_by_record =
599 trusted && cached.is_some_and(|record| matches_record(&record, &counted, &children));
600 let (deltas, clean) = if clean_by_record {
601 (Vec::new(), true)
602 } else {
603 if tree.is_none()
604 && let Some(id) = base
605 {
606 tree = Some(read_tree(self.objects, id)?);
607 }
608 self.differ(
609 &path,
610 &covered,
611 tree.as_deref().unwrap_or(&[]),
612 &counted,
613 &children,
614 )?
615 };
616
617 let record = if self.whole {
618 // Records that will vouch, or a listing that will stand, where
619 // the old ones could not.
620 let fresh = counted.iter().any(|file| {
621 file.read && file.vouches && file.stat.is_some_and(|stat| stat.mtime < self.time)
622 }) || stamp.is_some_and(|stamp| {
623 !stamp.older_than(self.old.time()) && stamp.older_than(self.time)
624 });
625 let mut files: Vec<FileRecord> = counted.into_iter().map(Counted::record).collect();
626 files.extend(children.iter().map(|child| {
627 let kind = if child.base.is_some() {
628 KIND_TREE
629 } else {
630 KIND_SUBDIR
631 };
632 FileRecord::bare(child.name.clone(), kind, child.base)
633 }));
634 files.sort_unstable_by(|a, b| a.name.cmp(&b.name));
635 let made = DirRecord {
636 path: path.clone(),
637 base,
638 clean,
639 stamp,
640 ignored,
641 rules: ignores::digest(&rules),
642 ignore_files,
643 files,
644 };
645 Some(match cached {
646 Some(old) if !fresh && made.same_as(&old) => (Record::Kept(old), false),
647 _ => (Record::Made(made), true),
648 })
649 } else {
650 None
651 };
652
653 if !children.is_empty() {
654 let shared = (self.held.load(Ordering::Relaxed) < self.held_limit).then(|| {
655 self.held.fetch_add(1, Ordering::Relaxed);
656 Arc::new(Shared {
657 dir,
658 held: &self.held,
659 })
660 });
661 for child in children {
662 let open = match &shared {
663 Some(shared) => Open::Child(Arc::clone(shared), child.name),
664 None => Open::FromRoot,
665 };
666 let job = Job {
667 open,
668 path: child.path,
669 base: child.base,
670 rules: rules.clone(),
671 ignored: child.ignored,
672 scope: child.scope,
673 };
674 scope.spawn(move |s| self.run(s, job));
675 }
676 }
677
678 let mut out = self.out();
679 out.deltas.extend(deltas);
680 if let Some((record, changed)) = record {
681 out.records.push(record);
682 out.changed |= changed;
683 out.seen += usize::from(cached.is_some());
684 }
685 Ok(())
686 }
687
688 /// Sorts a directory's entries into what counts and what to read next.
689 /// `at` says what the base has at a name, and `cached` is the
690 /// directory's record. An entry that is gone by the time it is looked at
691 /// is left out, and noted.
692 #[allow(clippy::too_many_arguments)]
693 fn classify(
694 &self,
695 dir: &Dir,
696 path: &[u8],
697 listed: Vec<Listed>,
698 rules: &Chain,
699 ignored: bool,
700 covered: &Scope,
701 at: &dyn Fn(&[u8]) -> At,
702 cached: Option<CachedDir<'_>>,
703 ) -> Result<Sorted, Error> {
704 let mut found = Sorted {
705 counted: Vec::with_capacity(listed.len()),
706 children: Vec::new(),
707 vanished: false,
708 };
709 for Listed { name, dir: is_dir } in listed {
710 let Some(child_scope) = covered.enter(&name) else {
711 continue;
712 };
713 let base_at = at(&name);
714 let stat = if is_dir {
715 None
716 } else {
717 let os = os_name(&name).ok_or_else(|| unrepresentable(&join(path, &name)))?;
718 match stat_entry(dir, os) {
719 Ok(stat) => Some(stat),
720 Err(err) if err.kind() == io::ErrorKind::NotFound => {
721 found.vanished = true;
722 continue;
723 }
724 Err(err) => return Err(self.root.error("read", &join(path, &name), err)),
725 }
726 };
727 match stat {
728 None
729 | Some(Stat {
730 kind: StatKind::Dir,
731 ..
732 }) => {
733 if base_at == At::Gitlink {
734 // A submodule's directory: its content is not ours.
735 found.counted.push(Counted {
736 name,
737 stat: None,
738 op: None,
739 vouches: false,
740 read: false,
741 });
742 continue;
743 }
744 let child_path = join(path, &name);
745 let child_ignored = ignored || ignores::is_ignored(rules, &child_path, true);
746 let child_base = match base_at {
747 At::Tree(id) => Some(id),
748 _ if child_ignored => continue,
749 _ => None,
750 };
751 found.children.push(Child {
752 name,
753 path: child_path,
754 base: child_base,
755 ignored: child_ignored,
756 scope: child_scope,
757 });
758 }
759 Some(
760 stat @ Stat {
761 kind: StatKind::File | StatKind::Symlink,
762 ..
763 },
764 ) => {
765 let tracked = matches!(base_at, At::Leaf | At::Gitlink);
766 if !tracked
767 && (ignored || ignores::is_ignored(rules, &join(path, &name), false))
768 {
769 continue;
770 }
771 // Symlinks are cheap to read again, and their size in
772 // the metadata is not reliable everywhere.
773 let vouched = match stat.kind {
774 StatKind::File => cached
775 .and_then(|record| record.file(&name))
776 .and_then(|file| file.vouch(&stat, self.old.time())),
777 _ => None,
778 };
779 found.counted.push(Counted {
780 name,
781 stat: Some(stat),
782 op: vouched.map(|blob| op_for(&stat, blob, stat.size)),
783 vouches: vouched.is_some(),
784 read: false,
785 });
786 }
787 Some(_) => {}
788 }
789 }
790 Ok(found)
791 }
792
793 /// A directory the base has, whose path holds no directory any more:
794 /// everything the base has below it is gone.
795 fn gone(&self, path: &[u8], base: Option<ObjectId>) -> Result<(), Error> {
796 let Some(tree) = base else {
797 return Ok(());
798 };
799 let removed = leaves(self.objects, tree, path)?;
800 self.out()
801 .deltas
802 .extend(removed.into_iter().map(|(path, op)| Delta {
803 path,
804 old: Some(op),
805 new: None,
806 }));
807 Ok(())
808 }
809
810 /// The entries of `dir`, by name, less those the walk never looks at.
811 fn list(&self, dir: &Dir, path: &[u8]) -> Result<Vec<Listed>, Error> {
812 #[cfg(test)]
813 self.listed.fetch_add(1, Ordering::Relaxed);
814 let mut listed: Vec<Listed> = list(dir)
815 .map_err(|err| self.root.error("read", path, err))?
816 .into_iter()
817 .filter(|(name, _)| !skipped(name))
818 .map(|(name, dir)| Listed { name, dir })
819 .collect();
820 listed.sort_unstable_by(|a, b| a.name.cmp(&b.name));
821 Ok(listed)
822 }
823
824 /// Reads the files and symlinks the cache did not vouch for, in
825 /// parallel. Files that vanished since they were listed are left out.
826 fn hash(&self, dir: &Dir, path: &[u8], counted: Vec<Counted>) -> Result<Vec<Counted>, Error> {
827 let missing = |file: &Counted| file.stat.is_some() && file.op.is_none();
828 let misses = counted.iter().filter(|file| missing(file)).count();
829 if misses == 0 {
830 return Ok(counted);
831 }
832 let read = |mut file: Counted| -> Result<Option<Counted>, Error> {
833 if !missing(&file) {
834 return Ok(Some(file));
835 }
836 let os = os_name(&file.name).ok_or_else(|| unrepresentable(&file.name))?;
837 let symlink = file.stat.is_some_and(|stat| stat.kind == StatKind::Symlink);
838 let result = if symlink {
839 hash_symlink(dir, os)
840 } else {
841 match hash_file(dir, os) {
842 // Replaced by a symlink since it was listed.
843 Err(_) if dir.symlink_metadata(os).is_ok_and(|meta| meta.is_symlink()) => {
844 hash_symlink(dir, os)
845 }
846 other => other,
847 }
848 };
849 match result {
850 Ok((op, stable)) => {
851 file.vouches = stable.is_some() && !matches!(op, ChangeOp::Symlink { .. });
852 if let Some(stable) = stable {
853 file.stat = Some(stable);
854 }
855 file.op = Some(op);
856 file.read = true;
857 Ok(Some(file))
858 }
859 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
860 Err(err) => Err(self.root.error("read", &join(path, &file.name), err)),
861 }
862 };
863 let read: Vec<Option<Counted>> = if misses > 1 {
864 counted
865 .into_par_iter()
866 .map(read)
867 .collect::<Result<_, _>>()?
868 } else {
869 counted.into_iter().map(read).collect::<Result<_, _>>()?
870 };
871 Ok(read.into_iter().flatten().collect())
872 }
873
874 /// Where a directory's own entries differ from the base tree's
875 /// `entries`, and whether it is clean: nothing differs, and every
876 /// subdirectory of the tree is there as a directory.
877 fn differ(
878 &self,
879 path: &[u8],
880 covered: &Scope,
881 entries: &[Entry],
882 counted: &[Counted],
883 children: &[Child],
884 ) -> Result<(Vec<Delta>, bool), Error> {
885 let added = |file: &Counted| {
886 file.op.as_ref().map(|op| Delta {
887 path: join(path, &file.name),
888 old: None,
889 new: Some(op.clone()),
890 })
891 };
892 let mut deltas = Vec::new();
893 let mut all_there = true;
894 let mut news = counted.iter().peekable();
895 for entry in entries {
896 while let Some(file) = news.next_if(|file| file.name < entry.name) {
897 deltas.extend(added(file));
898 }
899 if covered.enter(&entry.name).is_none() {
900 continue;
901 }
902 match &entry.kind {
903 EntryKind::Tree { tree } => {
904 let there = children
905 .binary_search_by(|child| child.name.as_slice().cmp(&entry.name))
906 .is_ok_and(|index| children[index].base.is_some());
907 if !there {
908 all_there = false;
909 let removed = leaves(self.objects, *tree, &join(path, &entry.name))?;
910 deltas.extend(removed.into_iter().map(|(path, op)| Delta {
911 path,
912 old: Some(op),
913 new: None,
914 }));
915 }
916 }
917 kind => {
918 let Some(old) = ChangeOp::from_entry(kind) else {
919 continue;
920 };
921 match news.next_if(|file| file.name == entry.name) {
922 // A gitlink whose directory is there is the base's.
923 Some(Counted { op: None, .. }) => {}
924 Some(Counted { op: Some(new), .. }) => {
925 if *new != old {
926 deltas.push(Delta {
927 path: join(path, &entry.name),
928 old: Some(old),
929 new: Some(new.clone()),
930 });
931 }
932 }
933 None => deltas.push(Delta {
934 path: join(path, &entry.name),
935 old: Some(old),
936 new: None,
937 }),
938 }
939 }
940 }
941 }
942 deltas.extend(news.filter_map(added));
943 let clean = deltas.is_empty() && all_there;
944 Ok((deltas, clean))
945 }
946}
947
948/// What the base tree's `entries` have at `name`.
949fn at_tree(entries: &[Entry], name: &[u8]) -> At {
950 match entries.binary_search_by(|entry| entry.name.as_slice().cmp(name)) {
951 Ok(index) => match &entries[index].kind {
952 EntryKind::Tree { tree } => At::Tree(*tree),
953 EntryKind::Gitlink { .. } => At::Gitlink,
954 _ => At::Leaf,
955 },
956 Err(_) => At::Nothing,
957 }
958}
959
960/// What the base has at `name`, by the record of a directory that was
961/// clean against the same tree: the record lists every entry of that tree.
962fn at_record(record: &CachedDir<'_>, name: &[u8]) -> At {
963 match record.file(name).map(|file| (file.kind, file.blob)) {
964 Some((KIND_TREE, tree)) => At::Tree(tree),
965 Some((KIND_GITLINK, _)) => At::Gitlink,
966 Some((KIND_SUBDIR, _)) | None => At::Nothing,
967 Some(_) => At::Leaf,
968 }
969}
970
971/// Whether a directory's entries match, one for one, the record of a clean
972/// directory: the same files, symlinks and gitlinks with the same content,
973/// and the same subdirectories of the base tree, there as directories.
974fn matches_record(record: &CachedDir<'_>, counted: &[Counted], children: &[Child]) -> bool {
975 let mut files = counted.iter();
976 let mut dirs = children.iter().filter(|child| child.base.is_some());
977 for entry in record.files() {
978 let matched = match entry.kind {
979 KIND_SUBDIR => true,
980 KIND_TREE => dirs
981 .next()
982 .is_some_and(|dir| dir.name == entry.name && dir.base == Some(entry.blob)),
983 _ => files.next().is_some_and(|file| {
984 file.name == entry.name
985 && file.kind() == entry.kind
986 && (entry.kind == KIND_GITLINK || file.blob() == Some(entry.blob))
987 }),
988 };
989 if !matched {
990 return false;
991 }
992 }
993 files.next().is_none() && dirs.next().is_none()
994}
995
996/// Whether a directory's record may stand for its listing: the directory's
997/// stamp is the recorded one, both its times strictly older than the scan
998/// that recorded it, and the walk takes its entries as it did then, against
999/// the same base tree and ignored or not as then. The ignore rules are
1000/// compared once they are read.
1001fn record_holds(
1002 record: &CachedDir<'_>,
1003 base: Option<ObjectId>,
1004 ignored: bool,
1005 stamp: Option<DirStamp>,
1006 time: (i64, u32),
1007) -> bool {
1008 stamp.is_some_and(|stamp| record.stamp() == Some(stamp) && stamp.older_than(time))
1009 && record.base() == base
1010 && record.ignored() == ignored
1011}
1012
1013/// Whether `name` is one name, as a listing gives them: not empty, not `.`
1014/// or `..`, and without `/` or NUL.
1015fn one_name(name: &[u8]) -> bool {
1016 !name.is_empty() && name != b"." && name != b".." && !name.contains(&b'/') && !name.contains(&0)
1017}
1018
1019/// Names the walk never looks at: `.braid` and `.git` and every name that
1020/// some file system would read as one of them, and braid's scratch files.
1021fn skipped(name: &[u8]) -> bool {
1022 name.starts_with(SCRATCH_PREFIX.as_bytes())
1023 || (may_be_reserved(name) && braid_format::name::is_reserved(name))
1024}
1025
1026/// Whether `name` may alias `.braid` or `.git`, a quick test before the
1027/// full one. Aliases fold to `.braid`, `.git`, `braid~N` or `git~N`, and an
1028/// ASCII name folds by changing letter case only, after cutting it at its
1029/// first `:` and dropping trailing dots and spaces.
1030fn may_be_reserved(name: &[u8]) -> bool {
1031 if !name.is_ascii() {
1032 return true;
1033 }
1034 let end = name
1035 .iter()
1036 .position(|byte| *byte == b':')
1037 .unwrap_or(name.len());
1038 let mut stem = &name[..end];
1039 while let [rest @ .., b'.' | b' '] = stem {
1040 stem = rest;
1041 }
1042 match stem.len() {
1043 4 | 6 => stem[0] == b'.',
1044 5 | 7 => stem[stem.len() - 2] == b'~',
1045 _ => false,
1046 }
1047}
1048
1049/// Whether the directory holds a `.braid` or `.git` entry: another workspace
1050/// or repository, which an untracked directory is not part of this one.
1051fn holds_marker(dir: &Dir) -> bool {
1052 [braid_repo::DIR, ".git"]
1053 .iter()
1054 .any(|marker| dir.symlink_metadata(marker).is_ok())
1055}
1056
1057fn unrepresentable(path: &[u8]) -> Error {
1058 Error::Unsafe {
1059 path: path.to_vec(),
1060 reason: "this platform cannot represent the name".to_owned(),
1061 }
1062}
1063
1064/// The change operation that sets a path to this file.
1065fn op_for(stat: &Stat, blob: ObjectId, size: u64) -> ChangeOp {
1066 match stat.kind {
1067 StatKind::Symlink => ChangeOp::Symlink { blob, size },
1068 _ if stat.executable => ChangeOp::Executable { blob, size },
1069 _ => ChangeOp::File { blob, size },
1070 }
1071}
1072
1073/// What reading a file gave: the change that sets it, and its metadata if
1074/// it did not change while it was read.
1075type Hashed = (ChangeOp, Option<Stat>);
1076
1077fn hash_file(dir: &Dir, name: &OsStr) -> io::Result<Hashed> {
1078 let mut file = open_file(dir, name)?;
1079 let before = Stat::of(&file.metadata()?);
1080 if before.kind != StatKind::File {
1081 return Err(io::Error::other("not a regular file"));
1082 }
1083 let mut hasher = IdHasher::new(Kind::Blob);
1084 let mut buf = vec![0u8; 64 * 1024];
1085 let mut size = 0u64;
1086 loop {
1087 let n = match file.read(&mut buf) {
1088 Ok(0) => break,
1089 Ok(n) => n,
1090 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
1091 Err(err) => return Err(err),
1092 };
1093 hasher.update(&buf[..n]);
1094 size += n as u64;
1095 }
1096 let after = Stat::of(&file.metadata()?);
1097 let blob = hasher.finalize();
1098 let stable = (before == after && size == after.size).then_some(after);
1099 Ok((op_for(&before, blob, size), stable))
1100}
1101
1102fn hash_symlink(dir: &Dir, name: &OsStr) -> io::Result<Hashed> {
1103 let target = read_link(dir, name)?;
1104 let blob = ObjectId::hash(Kind::Blob, &target);
1105 Ok((
1106 ChangeOp::Symlink {
1107 blob,
1108 size: target.len() as u64,
1109 },
1110 None,
1111 ))
1112}
1113
1114/// The system clock less two seconds, for when the file system's own clock
1115/// cannot be read: older than any modification a coarse file system clock
1116/// could still date to the same instant.
1117fn fallback_now() -> (i64, u32) {
1118 let since = SystemTime::now()
1119 .duration_since(UNIX_EPOCH)
1120 .unwrap_or_default()
1121 .saturating_sub(Duration::from_secs(2));
1122 (since.as_secs() as i64, since.subsec_nanos())
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128 use std::fs;
1129 use std::io::{Seek, SeekFrom, Write};
1130 use std::path::Path;
1131
1132 use braid_engine::EMPTY_TREE;
1133 use braid_format::{Change, MemoryObjects};
1134
1135 use crate::cache;
1136
1137 /// Objects in memory, counting the directories read.
1138 #[derive(Default)]
1139 struct Counting {
1140 objects: MemoryObjects,
1141 trees: AtomicUsize,
1142 }
1143
1144 impl Objects for Counting {
1145 type Error = std::convert::Infallible;
1146
1147 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
1148 let found = self.objects.get(id)?;
1149 if matches!(found, Some((Kind::Tree, _))) {
1150 self.trees.fetch_add(1, Ordering::Relaxed);
1151 }
1152 Ok(found)
1153 }
1154
1155 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
1156 self.objects.put(kind, payload)
1157 }
1158 }
1159
1160 /// A working copy with a `.braid` file, as every workspace has, a
1161 /// directory for its stat cache, and objects for its base.
1162 struct Fixture {
1163 dir: tempfile::TempDir,
1164 state: tempfile::TempDir,
1165 root: Root,
1166 objects: Counting,
1167 }
1168
1169 impl Fixture {
1170 fn new() -> Fixture {
1171 let dir = tempfile::tempdir().unwrap();
1172 fs::write(dir.path().join(braid_repo::DIR), b"braid-workspace 1\n").unwrap();
1173 let root = Root::open(dir.path()).unwrap();
1174 Fixture {
1175 dir,
1176 state: tempfile::tempdir().unwrap(),
1177 root,
1178 objects: Counting::default(),
1179 }
1180 }
1181
1182 fn at(&self, path: &str) -> std::path::PathBuf {
1183 self.dir.path().join(path)
1184 }
1185
1186 fn file(&self, content: &str) -> ChangeOp {
1187 ChangeOp::File {
1188 blob: self.objects.put(Kind::Blob, content.as_bytes()).unwrap(),
1189 size: content.len() as u64,
1190 }
1191 }
1192
1193 /// A base tree with these files, also written into the working copy
1194 /// and dated in the past, as a checkout leaves them.
1195 fn base(&self, files: &[(&str, &str)]) -> ObjectId {
1196 let changes: Vec<Change> = files
1197 .iter()
1198 .map(|(path, content)| {
1199 let full = self.at(path);
1200 fs::create_dir_all(full.parent().unwrap()).unwrap();
1201 fs::write(&full, content).unwrap();
1202 set_mtime(&full, past());
1203 Change {
1204 path: path.as_bytes().to_vec(),
1205 op: self.file(content),
1206 }
1207 })
1208 .collect();
1209 braid_engine::apply(&self.objects, EMPTY_TREE, &changes).unwrap()
1210 }
1211
1212 /// Scans against `base`, with the stat cache of the previous scan,
1213 /// and saves the new one. Also returns whether it was saved, and how
1214 /// many directories of the base were read.
1215 fn scan_in(
1216 &self,
1217 base: ObjectId,
1218 scope: &[&str],
1219 held: usize,
1220 ) -> (Vec<Delta>, bool, usize) {
1221 let (deltas, saved, reads, _) = self.scan_counting(base, scope, held);
1222 (deltas, saved, reads)
1223 }
1224
1225 /// [`Fixture::scan_in`], also returning how many directories were
1226 /// listed.
1227 fn scan_counting(
1228 &self,
1229 base: ObjectId,
1230 scope: &[&str],
1231 held: usize,
1232 ) -> (Vec<Delta>, bool, usize, usize) {
1233 let old = Cache::load(self.state.path());
1234 let scope: Vec<Vec<u8>> = scope.iter().map(|path| path.as_bytes().to_vec()).collect();
1235 self.objects.trees.store(0, Ordering::Relaxed);
1236 let found = scan_holding(
1237 &self.root,
1238 &self.objects,
1239 base,
1240 &old,
1241 FileSystem::default(),
1242 &scope,
1243 held,
1244 )
1245 .unwrap();
1246 let saved = found.cache.as_ref().is_some_and(|next| next.changed);
1247 if let Some(next) = found.cache.as_ref().filter(|next| next.changed) {
1248 cache::save(self.state.path(), next.time, &next.records).unwrap();
1249 }
1250 let reads = self.objects.trees.load(Ordering::Relaxed);
1251 (found.deltas, saved, reads, found.listed)
1252 }
1253
1254 fn scan(&self, base: ObjectId) -> (Vec<Delta>, bool, usize) {
1255 self.scan_in(base, &[], HELD_HANDLES)
1256 }
1257
1258 /// Waits until the file system's clock has moved on from every
1259 /// change made so far: records the next scan makes of them are then
1260 /// not racy, whatever the clock's granularity.
1261 fn settle(&self) {
1262 let then = self.root.file_system_now().unwrap();
1263 while self.root.file_system_now().unwrap() <= then {
1264 std::thread::sleep(Duration::from_millis(5));
1265 }
1266 }
1267
1268 /// A whole scan: how many directories it listed.
1269 fn listings(&self, base: ObjectId) -> (Vec<Delta>, usize) {
1270 let (deltas, _, _, listed) = self.scan_counting(base, &[], HELD_HANDLES);
1271 (deltas, listed)
1272 }
1273 }
1274
1275 fn past() -> SystemTime {
1276 SystemTime::now() - Duration::from_secs(30)
1277 }
1278
1279 fn set_mtime(path: &Path, time: SystemTime) {
1280 fs::File::options()
1281 .write(true)
1282 .open(path)
1283 .unwrap()
1284 .set_modified(time)
1285 .unwrap();
1286 }
1287
1288 fn blob(content: &str) -> ChangeOp {
1289 ChangeOp::File {
1290 blob: ObjectId::hash(Kind::Blob, content.as_bytes()),
1291 size: content.len() as u64,
1292 }
1293 }
1294
1295 /// The deltas as `path old>new`, with `-` for nothing and `f` for a
1296 /// file, `l` for a symlink and `g` for a gitlink.
1297 fn show(deltas: &[Delta]) -> Vec<String> {
1298 let kind = |op: &Option<ChangeOp>| match op {
1299 None => "-",
1300 Some(ChangeOp::Symlink { .. }) => "l",
1301 Some(ChangeOp::Gitlink { .. }) => "g",
1302 Some(_) => "f",
1303 };
1304 deltas
1305 .iter()
1306 .map(|delta| {
1307 let path = String::from_utf8_lossy(&delta.path);
1308 format!("{path} {}>{}", kind(&delta.old), kind(&delta.new))
1309 })
1310 .collect()
1311 }
1312
1313 #[test]
1314 fn unchanged_files_are_not_read_again() {
1315 let f = Fixture::new();
1316 let path = f.at("a.txt");
1317 fs::write(&path, "one").unwrap();
1318 set_mtime(&path, past());
1319 let (first, _, _) = f.scan(EMPTY_TREE);
1320 assert_eq!(first[0].new, Some(blob("one")));
1321
1322 // Rewrite the content in place behind the cache's back: same inode,
1323 // same size, same modification time. The cache vouches for it, so
1324 // the file is not read, and the old blob is what the scan reports.
1325 let later = past() + Duration::from_secs(1);
1326 let rewrite = |content: &[u8]| {
1327 let mut file = fs::File::options().write(true).open(&path).unwrap();
1328 file.seek(SeekFrom::Start(0)).unwrap();
1329 file.write_all(content).unwrap();
1330 drop(file);
1331 set_mtime(&path, later);
1332 };
1333 rewrite(b"two");
1334 let (second, _, _) = f.scan(EMPTY_TREE);
1335 assert_eq!(second[0].new, Some(blob("two")), "the time changed");
1336 rewrite(b"one");
1337 let (third, _, _) = f.scan(EMPTY_TREE);
1338 assert_eq!(third[0].new, Some(blob("two")), "vouched for by the cache");
1339
1340 // A file whose time is not strictly older than the cache's scan is
1341 // read again, whatever the rest of its metadata says.
1342 let (seconds, nanos) = Cache::load(f.state.path()).time();
1343 set_mtime(&path, UNIX_EPOCH + Duration::new(seconds as u64, nanos));
1344 let (fourth, _, _) = f.scan(EMPTY_TREE);
1345 assert_eq!(fourth[0].new, Some(blob("one")));
1346 }
1347
1348 #[test]
1349 fn what_the_walk_skips() {
1350 let f = Fixture::new();
1351 let base = f.base(&[
1352 ("kept.log", "old"),
1353 ("build/sub/tracked.txt", "tracked"),
1354 (".gitignore", "*.log\nbuild/\n"),
1355 ]);
1356 let write = |path: &str, content: &str| {
1357 fs::create_dir_all(f.at(path).parent().unwrap()).unwrap();
1358 fs::write(f.at(path), content).unwrap();
1359 };
1360 write("app.log", "ignored");
1361 write("kept.log", "tracked, so not ignored");
1362 write("build/out.o", "ignored");
1363 write("build/new/file", "ignored");
1364 write(".git/config", "skipped");
1365 write(".braid-tmp-0123", "scratch");
1366 write("nested/.braid", "another workspace");
1367 write("nested/file", "not ours");
1368 write("repo/.git/HEAD", "another repository");
1369 write("src.rs", "code");
1370
1371 let (deltas, _, _) = f.scan(base);
1372 assert_eq!(show(&deltas), ["kept.log f>f", "src.rs ->f"]);
1373 }
1374
1375 #[cfg(unix)]
1376 #[test]
1377 fn symlinks_are_read_not_followed() {
1378 let f = Fixture::new();
1379 let base = f.base(&[("dir/x", "x")]);
1380 let outside = tempfile::tempdir().unwrap();
1381 fs::write(outside.path().join("x"), "outside").unwrap();
1382 fs::remove_dir_all(f.at("dir")).unwrap();
1383 std::os::unix::fs::symlink(outside.path(), f.at("dir")).unwrap();
1384 std::os::unix::fs::symlink(outside.path().join("x"), f.at("link")).unwrap();
1385 let (deltas, _, _) = f.scan(base);
1386 assert_eq!(show(&deltas), ["dir ->l", "dir/x f>-", "link ->l"]);
1387 let target = outside.path().as_os_str().as_encoded_bytes().to_vec();
1388 assert_eq!(
1389 deltas[0].new,
1390 Some(ChangeOp::Symlink {
1391 blob: ObjectId::hash(Kind::Blob, &target),
1392 size: target.len() as u64,
1393 })
1394 );
1395 }
1396
1397 #[test]
1398 fn clean_directories_are_not_compared_again() {
1399 let f = Fixture::new();
1400 let base = f.base(&[("a/x", "1"), ("a/y", "2"), ("b/z", "3"), ("top", "4")]);
1401 f.settle();
1402 let (deltas, saved, reads) = f.scan(base);
1403 assert!(deltas.is_empty());
1404 assert!(saved);
1405 assert_eq!(reads, 3, "every directory of the base, once");
1406
1407 // Nothing changed: no directory of the base is read, and the cache
1408 // is left as it is.
1409 let (deltas, saved, reads) = f.scan(base);
1410 assert!(deltas.is_empty());
1411 assert_eq!((saved, reads), (false, 0));
1412
1413 // An edit in one directory reads that directory's tree only.
1414 fs::write(f.at("a/x"), "edited").unwrap();
1415 f.settle();
1416 let (deltas, saved, reads) = f.scan(base);
1417 assert_eq!(show(&deltas), ["a/x f>f"]);
1418 assert_eq!((saved, reads), (true, 1));
1419 let (deltas, saved, reads) = f.scan(base);
1420 assert_eq!(show(&deltas), ["a/x f>f"]);
1421 assert_eq!((saved, reads), (false, 1));
1422 }
1423
1424 #[test]
1425 fn entries_added_or_removed_in_a_clean_directory_are_seen() {
1426 let f = Fixture::new();
1427 let base = f.base(&[("a/x", "1"), ("a/y", "2"), ("b/z", "3")]);
1428 f.scan(base);
1429 let a_time = fs::metadata(f.at("a")).unwrap().modified().unwrap();
1430 let keep_time = |path: &str| {
1431 fs::File::open(f.at(path))
1432 .unwrap()
1433 .set_modified(a_time)
1434 .unwrap()
1435 };
1436
1437 // A file added, the directory's time set back as a coarse clock
1438 // would leave it.
1439 fs::write(f.at("a/new"), "new").unwrap();
1440 keep_time("a");
1441 let (deltas, _, _) = f.scan(base);
1442 assert_eq!(show(&deltas), ["a/new ->f"]);
1443
1444 // A file removed, the same way.
1445 fs::remove_file(f.at("a/y")).unwrap();
1446 keep_time("a");
1447 let (deltas, _, _) = f.scan(base);
1448 assert_eq!(show(&deltas), ["a/new ->f", "a/y f>-"]);
1449
1450 // Back as it was: clean again.
1451 fs::remove_file(f.at("a/new")).unwrap();
1452 fs::write(f.at("a/y"), "2").unwrap();
1453 keep_time("a");
1454 let (deltas, _, _) = f.scan(base);
1455 assert!(deltas.is_empty());
1456
1457 // A directory of the base replaced by a file, and a file by a
1458 // directory.
1459 fs::remove_dir_all(f.at("b")).unwrap();
1460 fs::write(f.at("b"), "now a file").unwrap();
1461 fs::remove_file(f.at("a/x")).unwrap();
1462 fs::create_dir(f.at("a/x")).unwrap();
1463 fs::write(f.at("a/x/inside"), "i").unwrap();
1464 let (deltas, _, _) = f.scan(base);
1465 assert_eq!(
1466 show(&deltas),
1467 ["a/x f>-", "a/x/inside ->f", "b ->f", "b/z f>-"]
1468 );
1469 }
1470
1471 #[test]
1472 fn a_new_base_reads_only_the_directories_that_changed() {
1473 let f = Fixture::new();
1474 let first = f.base(&[("a/x", "1"), ("b/z", "3"), ("c/d/e", "5")]);
1475 f.scan(first);
1476 // The same working copy against a base where a/x and c/d/e differ.
1477 let second = braid_engine::apply(
1478 &f.objects,
1479 first,
1480 &[
1481 Change {
1482 path: b"a/x".to_vec(),
1483 op: f.file("one"),
1484 },
1485 Change {
1486 path: b"c/d/e".to_vec(),
1487 op: f.file("five"),
1488 },
1489 ],
1490 )
1491 .unwrap();
1492 let (deltas, saved, reads) = f.scan(second);
1493 assert_eq!(show(&deltas), ["a/x f>f", "c/d/e f>f"]);
1494 // The root, a, c and c/d: not b.
1495 assert_eq!((saved, reads), (true, 4));
1496 assert_eq!(deltas[0].old, Some(blob("one")));
1497 assert_eq!(deltas[0].new, Some(blob("1")));
1498 }
1499
1500 #[test]
1501 fn scans_of_some_paths() {
1502 let f = Fixture::new();
1503 let base = f.base(&[("a/x", "1"), ("a/y", "2"), ("c/d/e", "3"), ("top", "4")]);
1504 f.scan(base);
1505 fs::write(f.at("a/x"), "edited").unwrap();
1506 fs::write(f.at("a/y"), "edited").unwrap();
1507 fs::write(f.at("new"), "new").unwrap();
1508 fs::remove_dir_all(f.at("c")).unwrap();
1509 let (deltas, saved, _) = f.scan_in(base, &["a/x", "c/d", "nothing/here"], HELD_HANDLES);
1510 assert_eq!(show(&deltas), ["a/x f>f", "c/d/e f>-"]);
1511 assert!(!saved, "a scan of some paths keeps the cache as it is");
1512 let (deltas, _, _) = f.scan_in(base, &["a"], HELD_HANDLES);
1513 assert_eq!(show(&deltas), ["a/x f>f", "a/y f>f"]);
1514 // The root is the whole working copy.
1515 let (deltas, saved, _) = f.scan_in(base, &["", "a"], HELD_HANDLES);
1516 assert_eq!(
1517 show(&deltas),
1518 ["a/x f>f", "a/y f>f", "c/d/e f>-", "new ->f"]
1519 );
1520 assert!(saved);
1521 }
1522
1523 #[test]
1524 fn gitlinks_are_there_or_not() {
1525 let f = Fixture::new();
1526 let gitlink = ChangeOp::Gitlink {
1527 commit: braid_format::GitId::Sha1([7; 20]),
1528 };
1529 let base = braid_engine::apply(
1530 &f.objects,
1531 EMPTY_TREE,
1532 &[
1533 Change {
1534 path: b"vendor/lib".to_vec(),
1535 op: gitlink.clone(),
1536 },
1537 Change {
1538 path: b"vendor/README".to_vec(),
1539 op: f.file("r"),
1540 },
1541 ],
1542 )
1543 .unwrap();
1544 fs::create_dir_all(f.at("vendor/lib")).unwrap();
1545 fs::write(f.at("vendor/lib/inside"), "not ours").unwrap();
1546 fs::write(f.at("vendor/README"), "r").unwrap();
1547 for _ in 0..2 {
1548 let (deltas, _, _) = f.scan(base);
1549 assert!(deltas.is_empty(), "{:?}", show(&deltas));
1550 }
1551 fs::remove_dir_all(f.at("vendor/lib")).unwrap();
1552 let (deltas, _, _) = f.scan(base);
1553 assert_eq!(show(&deltas), ["vendor/lib g>-"]);
1554 fs::write(f.at("vendor/lib"), "a file").unwrap();
1555 let (deltas, _, _) = f.scan(base);
1556 assert_eq!(show(&deltas), ["vendor/lib g>f"]);
1557 }
1558
1559 #[test]
1560 fn directories_reopened_from_the_root_read_the_same() {
1561 let f = Fixture::new();
1562 let base = f.base(&[("a/b/c/d", "1"), ("a/b/e", "2"), ("f/g", "3"), ("h", "4")]);
1563 fs::write(f.at("a/b/c/d"), "edited").unwrap();
1564 fs::write(f.at("f/new"), "new").unwrap();
1565 fs::remove_file(f.at("h")).unwrap();
1566 let (held, _, _) = f.scan_in(base, &[], HELD_HANDLES);
1567 let (reopened, _, _) = f.scan_in(base, &[], 0);
1568 assert_eq!(show(&held), ["a/b/c/d f>f", "f/new ->f", "h f>-"]);
1569 assert_eq!(held, reopened);
1570 }
1571
1572 // Directories have a stamp only where the system gives one.
1573 #[cfg(unix)]
1574 #[test]
1575 fn unchanged_directories_are_not_listed_again() {
1576 let f = Fixture::new();
1577 let base = f.base(&[("a/x", "1"), ("a/b/y", "2"), ("c/z", "3")]);
1578 fs::create_dir(f.at("untracked")).unwrap();
1579 fs::write(f.at("untracked/u"), "u").unwrap();
1580 f.settle();
1581 let (deltas, listed) = f.listings(base);
1582 assert_eq!(show(&deltas), ["untracked/u ->f"]);
1583 assert_eq!(listed, 5);
1584 let (deltas, listed) = f.listings(base);
1585 assert_eq!(show(&deltas), ["untracked/u ->f"]);
1586 assert_eq!(listed, 0, "every directory is as its record says");
1587
1588 // A file edited in place changes no directory: it is found by its
1589 // metadata, and nothing is listed.
1590 fs::write(f.at("a/b/y"), "edited").unwrap();
1591 let (deltas, listed) = f.listings(base);
1592 assert_eq!(show(&deltas), ["a/b/y f>f", "untracked/u ->f"]);
1593 assert_eq!(listed, 0);
1594
1595 // A new file is a new entry: its directory alone is listed again.
1596 fs::write(f.at("c/new"), "n").unwrap();
1597 f.settle();
1598 let (deltas, listed) = f.listings(base);
1599 assert_eq!(show(&deltas), ["a/b/y f>f", "c/new ->f", "untracked/u ->f"]);
1600 assert_eq!(listed, 1);
1601 fs::remove_file(f.at("untracked/u")).unwrap();
1602 f.settle();
1603 let (deltas, listed) = f.listings(base);
1604 assert_eq!(show(&deltas), ["a/b/y f>f", "c/new ->f"]);
1605 assert_eq!(listed, 1);
1606 }
1607
1608 // Directories have a stamp only where the system gives one.
1609 #[cfg(unix)]
1610 #[test]
1611 fn a_listing_stands_only_while_the_rules_and_the_base_do() {
1612 let f = Fixture::new();
1613 let base = f.base(&[(".gitignore", "*.log\n"), ("d/kept", "k")]);
1614 fs::write(f.at("d/app.log"), "ignored").unwrap();
1615 f.settle();
1616 let (deltas, _) = f.listings(base);
1617 assert!(deltas.is_empty(), "{:?}", show(&deltas));
1618 let (_, listed) = f.listings(base);
1619 assert_eq!(listed, 0);
1620
1621 // Rules edited in place: no directory changed, but what is ignored
1622 // did, below too.
1623 fs::write(f.at(".gitignore"), "*.tmp\n").unwrap();
1624 let (deltas, listed) = f.listings(base);
1625 assert_eq!(show(&deltas), [".gitignore f>f", "d/app.log ->f"]);
1626 assert_eq!(listed, 2);
1627 fs::write(f.at(".gitignore"), "*.log\n").unwrap();
1628 let (deltas, _) = f.listings(base);
1629 assert!(deltas.is_empty(), "{:?}", show(&deltas));
1630 let (_, listed) = f.listings(base);
1631 assert_eq!(listed, 0);
1632
1633 // A base that tracks the ignored file: the walk must count it now,
1634 // though its directory did not change.
1635 let tracked = braid_engine::apply(
1636 &f.objects,
1637 base,
1638 &[Change {
1639 path: b"d/app.log".to_vec(),
1640 op: f.file("tracked"),
1641 }],
1642 )
1643 .unwrap();
1644 let (deltas, _) = f.listings(tracked);
1645 assert_eq!(show(&deltas), ["d/app.log f>f"]);
1646 assert_eq!(deltas[0].new, Some(blob("ignored")));
1647 }
1648
1649 #[test]
1650 fn a_listing_stands_only_while_the_stamp_is_older_than_the_scan() {
1651 let stamp = DirStamp {
1652 mtime: (100, 5),
1653 ctime: (100, 6),
1654 ino: 7,
1655 };
1656 let state = tempfile::tempdir().unwrap();
1657 let record = |stamp: DirStamp, time: (i64, u32)| {
1658 let dir = DirRecord {
1659 path: b"d".to_vec(),
1660 base: None,
1661 clean: false,
1662 stamp: Some(stamp),
1663 ignored: false,
1664 rules: 0,
1665 ignore_files: 0,
1666 files: Vec::new(),
1667 };
1668 cache::save(state.path(), time, &[Record::Made(dir)]).unwrap();
1669 Cache::load(state.path())
1670 };
1671 let holds = |cache: &Cache, now: DirStamp| {
1672 let dir = cache.dir(b"d").unwrap();
1673 record_holds(&dir, None, false, Some(now), cache.time())
1674 };
1675 let older = record(stamp, (100, 7));
1676 assert!(holds(&older, stamp));
1677 // Another inode, or either time changed.
1678 assert!(!holds(&older, DirStamp { ino: 8, ..stamp }));
1679 assert!(!holds(
1680 &older,
1681 DirStamp {
1682 mtime: (100, 4),
1683 ..stamp
1684 }
1685 ));
1686 assert!(!holds(
1687 &older,
1688 DirStamp {
1689 ctime: (101, 0),
1690 ..stamp
1691 }
1692 ));
1693 // Changed in the same instant as the scan that recorded it, as a
1694 // coarse clock would date it: the listing is read again.
1695 let racy = record(stamp, (100, 6));
1696 assert!(!holds(&racy, stamp));
1697 let racy = record(stamp, (100, 5));
1698 assert!(!holds(&racy, stamp));
1699 // Ignored, or with a base, where it was not.
1700 let dir = older.dir(b"d").unwrap();
1701 assert!(!record_holds(&dir, None, true, Some(stamp), older.time()));
1702 let tree = Some(ObjectId::hash(Kind::Tree, b"t"));
1703 assert!(!record_holds(&dir, tree, false, Some(stamp), older.time()));
1704 // Where the system gives no stamp, the directory is always listed.
1705 assert!(!record_holds(&dir, None, false, None, older.time()));
1706 }
1707
1708 /// A commit of `changes` on `base`, as `braid commit` makes one from a
1709 /// scan: what it changed, and the new base's tree.
1710 fn commit(f: &Fixture, base: ObjectId, changes: &[&Delta]) -> (Vec<Vec<u8>>, ObjectId) {
1711 let changes: Vec<Change> = changes
1712 .iter()
1713 .map(|delta| Change {
1714 path: delta.path.clone(),
1715 op: delta.new.clone().unwrap_or(ChangeOp::Delete),
1716 })
1717 .collect();
1718 let tree = braid_engine::apply(&f.objects, base, &changes).unwrap();
1719 (
1720 changes.into_iter().map(|change| change.path).collect(),
1721 tree,
1722 )
1723 }
1724
1725 /// Scans, commits the deltas `keep` accepts, and saves the scan's
1726 /// records brought onto the new base. Returns the new base's tree.
1727 fn scan_and_commit(f: &Fixture, base: ObjectId, keep: impl Fn(&Delta) -> bool) -> ObjectId {
1728 let old = Cache::load(f.state.path());
1729 let found = scan(&f.root, &f.objects, base, &old, FileSystem::default(), &[]).unwrap();
1730 let kept: Vec<&Delta> = found.deltas.iter().filter(|delta| keep(delta)).collect();
1731 let (paths, tree) = commit(f, base, &kept);
1732 let next = found.cache.unwrap();
1733 let records = follow(&f.objects, next.records, tree, &paths).unwrap();
1734 cache::save(f.state.path(), next.time, &records).unwrap();
1735 tree
1736 }
1737
1738 // Directories have a stamp only where the system gives one.
1739 #[cfg(unix)]
1740 #[test]
1741 fn a_scan_brought_onto_its_commit_leaves_nothing_to_do() {
1742 let f = Fixture::new();
1743 let base = f.base(&[("a/x", "1"), ("a/y", "2"), ("c/d/e", "3"), ("top", "4")]);
1744 fs::write(f.at("a/x"), "edited").unwrap();
1745 fs::create_dir_all(f.at("new/dir")).unwrap();
1746 fs::write(f.at("new/dir/f"), "f").unwrap();
1747 fs::remove_dir_all(f.at("c")).unwrap();
1748 set_mtime(&f.at("a/x"), past());
1749 set_mtime(&f.at("new/dir/f"), past());
1750 f.settle();
1751 let committed = scan_and_commit(&f, base, |_| true);
1752 let (deltas, saved, reads, listed) = f.scan_counting(committed, &[], HELD_HANDLES);
1753 assert!(deltas.is_empty(), "{:?}", show(&deltas));
1754 assert_eq!((saved, reads, listed), (false, 0, 0));
1755 }
1756
1757 #[cfg(unix)]
1758 #[test]
1759 fn a_scan_brought_onto_a_commit_of_some_paths() {
1760 let f = Fixture::new();
1761 let base = f.base(&[("a/x", "1"), ("a/y", "2"), ("c/d/e", "3"), ("top", "4")]);
1762 fs::write(f.at("a/x"), "edited").unwrap();
1763 fs::create_dir_all(f.at("new/dir")).unwrap();
1764 fs::write(f.at("new/dir/f"), "f").unwrap();
1765 fs::remove_dir_all(f.at("c")).unwrap();
1766 set_mtime(&f.at("a/x"), past());
1767 set_mtime(&f.at("new/dir/f"), past());
1768 f.settle();
1769 let committed = scan_and_commit(&f, base, |delta| delta.path == b"a/x");
1770 let (deltas, saved, reads, listed) = f.scan_counting(committed, &[], HELD_HANDLES);
1771 assert_eq!(show(&deltas), ["c/d/e f>-", "new/dir/f ->f"]);
1772 // The root's tree, to find what went missing, and the trees below
1773 // it: a is as the commit left it.
1774 assert_eq!((saved, reads, listed), (false, 3, 0));
1775 }
1776
1777 #[test]
1778 fn names_are_single_names() {
1779 for name in ["a", "a.b", "...", " "] {
1780 assert!(one_name(name.as_bytes()), "{name}");
1781 }
1782 for name in ["", ".", "..", "a/b", "/", "a\0"] {
1783 assert!(!one_name(name.as_bytes()), "{name:?}");
1784 }
1785 }
1786
1787 #[test]
1788 fn quick_test_for_reserved_names() {
1789 for name in [
1790 ".git",
1791 ".braid",
1792 ".GIT",
1793 "Git~1",
1794 "braid~2",
1795 ".git.",
1796 ".git::$INDEX_ALLOCATION",
1797 ] {
1798 assert!(may_be_reserved(name.as_bytes()), "{name}");
1799 assert!(skipped(name.as_bytes()), "{name}");
1800 }
1801 for name in ["f00.txt", "src", "main.rs", ".github", "README.md"] {
1802 assert!(!skipped(name.as_bytes()), "{name}");
1803 }
1804 assert!(skipped(".g\u{200c}it".as_bytes()));
1805 assert!(skipped(b".braid-tmp-0123"));
1806 }
1807}