1use std::collections::{BTreeSet, HashMap};
4use std::path::{Path, PathBuf};
5use std::sync::{Mutex, OnceLock, RwLock};
6
7fn storage_roots() -> &'static RwLock<BTreeSet<PathBuf>> {
8 static ROOTS: OnceLock<RwLock<BTreeSet<PathBuf>>> = OnceLock::new();
9 ROOTS.get_or_init(RwLock::default)
10}
11
12pub fn register_storage_root(path: &Path) {
15 let absolute = if path.is_absolute() {
16 path.to_path_buf()
17 } else if let Ok(cwd) = std::env::current_dir() {
18 cwd.join(path)
19 } else {
20 return;
21 };
22 if storage_roots()
23 .read()
24 .unwrap_or_else(|poisoned| poisoned.into_inner())
25 .contains(&absolute)
26 {
27 return;
31 }
32 #[cfg(any(test, feature = "test-support"))]
33 REGISTER_CANONICALIZATIONS.with(|count| count.set(count.get() + 1));
34 let canonical =
35 crate::production_storage::canonicalized_with(&absolute, &|p| p.canonicalize().ok());
36 let mut roots = storage_roots().write().unwrap_or_else(|p| p.into_inner());
37 roots.insert(absolute);
38 roots.insert(canonical);
39}
40
41pub struct NestedWorktreeBoundary {
60 root: PathBuf,
61 common_dir: OnceLock<Option<PathBuf>>,
62 verdicts: Mutex<HashMap<PathBuf, bool>>,
63}
64
65impl NestedWorktreeBoundary {
66 pub fn for_root(root: &Path) -> Self {
69 Self {
70 root: root.to_path_buf(),
71 common_dir: OnceLock::new(),
72 verdicts: Mutex::new(HashMap::new()),
73 }
74 }
75
76 fn common_dir(&self) -> Option<&Path> {
77 self.common_dir
78 .get_or_init(|| project_git_common_dir(&self.root))
79 .as_deref()
80 }
81
82 pub fn is_nested_worktree_root(&self, dir: &Path) -> bool {
87 if dir == self.root {
88 return false;
89 }
90 if let Some(verdict) = self
91 .verdicts
92 .lock()
93 .unwrap_or_else(std::sync::PoisonError::into_inner)
94 .get(dir)
95 {
96 return *verdict;
97 }
98 let verdict = std::fs::symlink_metadata(dir.join(".git"))
101 .is_ok_and(|metadata| metadata.is_file())
102 && self
103 .common_dir()
104 .is_some_and(|common| worktree_gitdir_points_at(dir, common));
105 self.verdicts
106 .lock()
107 .unwrap_or_else(std::sync::PoisonError::into_inner)
108 .insert(dir.to_path_buf(), verdict);
109 verdict
110 }
111
112 pub fn is_under_nested_worktree(&self, path: &Path) -> bool {
116 let mut current = Some(path);
117 while let Some(dir) = current {
118 if dir == self.root || !dir.starts_with(&self.root) {
119 return false;
120 }
121 if self.is_nested_worktree_root(dir) {
122 return true;
123 }
124 current = dir.parent();
125 }
126 false
127 }
128}
129
130fn project_git_common_dir(root: &Path) -> Option<PathBuf> {
136 let mut current = if root.is_absolute() {
137 root.to_path_buf()
138 } else {
139 std::env::current_dir().ok()?.join(root)
140 };
141 loop {
142 let dot_git = current.join(".git");
143 match std::fs::symlink_metadata(&dot_git) {
144 Ok(metadata) if metadata.is_dir() => return canonicalized(&dot_git),
145 Ok(metadata) if metadata.is_file() => {
146 let target = read_gitdir_target(&dot_git)?;
147 let target = if target.is_absolute() {
148 target
149 } else {
150 current.join(target)
151 };
152 if let Some(common) = read_commondir_target(&target) {
157 let common = if common.is_absolute() {
158 common
159 } else {
160 target.join(common)
161 };
162 return canonicalized(&common);
163 }
164 return canonicalized(&target);
165 }
166 Ok(_) => return None,
167 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
168 let Some(parent) = current.parent().map(Path::to_path_buf) else {
169 return None;
170 };
171 current = parent;
172 }
173 Err(_) => return None,
174 }
175 }
176}
177
178fn worktree_gitdir_points_at(dir: &Path, common_dir: &Path) -> bool {
183 let target = match read_gitdir_target(&dir.join(".git")) {
184 Some(target) => target,
185 None => return false,
186 };
187 let target = if target.is_absolute() {
188 target
189 } else {
190 dir.join(target)
191 };
192 worktree_common_candidate(&target).is_some_and(|candidate| candidate == *common_dir)
193}
194
195fn worktree_common_candidate(gitdir_target: &Path) -> Option<PathBuf> {
200 let worktrees = gitdir_target.parent()?;
201 if worktrees.file_name()? != std::ffi::OsStr::new("worktrees") {
202 return None;
203 }
204 canonicalized(worktrees.parent()?)
205}
206
207fn canonicalized(path: &Path) -> Option<PathBuf> {
208 std::fs::canonicalize(path).ok()
209}
210
211fn read_gitdir_target(dot_git: &Path) -> Option<PathBuf> {
214 parse_gitdir_bytes(&capped_read(dot_git, 4096)?)
215}
216
217fn read_commondir_target(gitdir: &Path) -> Option<PathBuf> {
220 let bytes = capped_read(&gitdir.join("commondir"), 4096)?;
221 let line = bytes.split(|byte| *byte == b'\n').next()?;
222 let trimmed = trim_ascii_whitespace(line);
223 if trimmed.is_empty() {
224 return None;
225 }
226 bytes_to_path(trimmed)
227}
228
229fn parse_gitdir_bytes(bytes: &[u8]) -> Option<PathBuf> {
230 let line = bytes.split(|byte| *byte == b'\n').next()?;
231 let line = line.strip_suffix(b"\r").unwrap_or(line);
232 let line = trim_ascii_whitespace(line);
233 let rest = trim_ascii_whitespace(line.strip_prefix(b"gitdir:")?);
234 if rest.is_empty() {
235 return None;
236 }
237 bytes_to_path(rest)
238}
239
240fn trim_ascii_whitespace(mut bytes: &[u8]) -> &[u8] {
241 while let Some((first, rest)) = bytes.split_first() {
242 if first.is_ascii_whitespace() {
243 bytes = rest;
244 } else {
245 break;
246 }
247 }
248 while let Some((last, rest)) = bytes.split_last() {
249 if last.is_ascii_whitespace() {
250 bytes = rest;
251 } else {
252 break;
253 }
254 }
255 bytes
256}
257
258#[cfg(unix)]
259fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
260 use std::os::unix::ffi::OsStringExt;
261 Some(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
262}
263
264#[cfg(not(unix))]
265fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
266 std::str::from_utf8(bytes).ok().map(PathBuf::from)
267}
268
269fn capped_read(path: &Path, cap: u64) -> Option<Vec<u8>> {
270 use std::io::Read;
271 let file = crate::bounded_io::open_content_file(path).ok()?;
272 let mut bytes = Vec::new();
273 file.take(cap).read_to_end(&mut bytes).ok()?;
274 Some(bytes)
275}
276#[cfg(any(test, feature = "test-support"))]
280thread_local! {
281 static REGISTER_CANONICALIZATIONS: std::cell::Cell<u64> =
282 const { std::cell::Cell::new(0) };
283}
284
285#[cfg(any(test, feature = "test-support"))]
286pub fn register_canonicalizations_for_test() -> u64 {
287 REGISTER_CANONICALIZATIONS.with(|count| count.get())
288}
289
290#[cfg(any(test, feature = "test-support"))]
291pub fn reset_register_canonicalizations_for_test() {
292 REGISTER_CANONICALIZATIONS.with(|count| count.set(0));
293}
294
295pub fn is_excluded(path: &Path) -> bool {
306 admit(path, None).is_err()
307}
308
309pub fn is_excluded_with_file_type(path: &Path, file_type: Option<&std::fs::FileType>) -> bool {
310 admit(path, file_type).is_err()
311}
312
313pub fn is_excluded_event(path: &Path) -> bool {
317 is_storage_path(path)
318 || crate::os_metadata::is_os_metadata_path(path)
319 || crate::live_db_files::is_registered_file_path(path)
320 || has_sqlite_suffix(path) && path.metadata().is_ok_and(|metadata| !metadata.is_dir())
321}
322
323pub fn is_excluded_file_by_path(path: &Path) -> bool {
330 crate::watcher_markers::is_marker_path(path)
331 || is_storage_path(path)
332 || crate::os_metadata::is_os_metadata_path(path)
333 || has_sqlite_suffix(path)
334 || crate::live_db_files::is_registered_file_path(path)
335}
336
337fn is_storage_path(path: &Path) -> bool {
338 storage_roots()
339 .read()
340 .unwrap_or_else(|p| p.into_inner())
341 .iter()
342 .any(|root| path.starts_with(root))
343}
344
345pub fn storage_root_for_path(
347 path: &Path,
348 policy: &dyn crate::read_policy::StoragePathPolicy,
349) -> Option<PathBuf> {
350 let path = policy.identity(path);
351 storage_roots()
352 .read()
353 .unwrap_or_else(|p| p.into_inner())
354 .iter()
355 .find(|root| policy.contains(&path, root))
356 .cloned()
357}
358
359fn is_excluded_file(path: &Path) -> bool {
360 crate::os_metadata::is_os_metadata_path(path)
361 || has_sqlite_suffix(path) && !path.is_dir()
362 || crate::live_db_files::is_registered_file_path(path)
363}
364
365fn has_sqlite_suffix(path: &Path) -> bool {
366 path.file_name().is_some_and(|name| {
367 let name = name.as_encoded_bytes();
368 [
369 b"-wal".as_slice(),
370 b"-shm",
371 b"-journal",
372 b".db",
373 b".sqlite",
374 b".sqlite3",
375 ]
376 .iter()
377 .any(|suffix| {
378 name.len() >= suffix.len()
379 && name[name.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
380 })
381 })
382}
383
384fn is_excluded_file_with_metadata(
385 path: &Path,
386 file_type: Option<&std::fs::FileType>,
387 metadata: Option<&std::fs::Metadata>,
388) -> bool {
389 crate::os_metadata::is_os_metadata_path(path)
390 || has_sqlite_suffix(path)
391 && !file_type.is_some_and(std::fs::FileType::is_dir)
392 && !metadata.is_some_and(std::fs::Metadata::is_dir)
393 || crate::live_db_files::is_registered_file_path(path)
394}
395
396pub fn is_sqlite_or_metadata(path: &Path) -> bool {
399 is_excluded_file(path) || crate::live_db_files::is_live_sqlite_file(path)
400}
401
402pub fn reader_bounded(
405 path: &Path,
406 deadline: Option<std::time::Instant>,
407 authorized_task_artifact: bool,
408) -> std::io::Result<crate::bounded_io::Reader> {
409 admit_bounded(path, authorized_task_artifact)?;
410 crate::bounded_io::reader(path, deadline)
411}
412
413fn admit_bounded(path: &Path, authorized_task_artifact: bool) -> std::io::Result<()> {
414 if authorized_task_artifact {
415 if is_sqlite_or_metadata(path) || std::fs::symlink_metadata(path)?.file_type().is_symlink()
416 {
417 return Err(std::io::Error::new(
418 std::io::ErrorKind::PermissionDenied,
419 "SQLite files and aliases are not readable task content",
420 ));
421 }
422 } else {
423 admit(path, None)?;
424 }
425 #[cfg(any(test, feature = "test-support"))]
426 record_open(path);
427 Ok(())
428}
429
430pub fn read(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
433 let path = path.as_ref();
434 admit(path, None)?;
435 #[cfg(any(test, feature = "test-support"))]
436 record_open(path);
437 use std::io::Read;
438 crate::io_accounting::WORK
439 .content_reads
440 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
441 let mut bytes = Vec::new();
442 crate::task_temp_reads::open(path)?.read_to_end(&mut bytes)?;
443 crate::io_accounting::WORK
444 .content_read_bytes
445 .fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
446 Ok(bytes)
447}
448
449pub fn read_to_string(path: impl AsRef<Path>) -> std::io::Result<String> {
450 String::from_utf8(read(path)?)
451 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
452}
453
454pub fn open(path: impl AsRef<Path>) -> std::io::Result<std::fs::File> {
455 let path = path.as_ref();
456 admit(path, None)?;
457 #[cfg(any(test, feature = "test-support"))]
458 record_open(path);
459 crate::io_accounting::WORK
460 .content_reads
461 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
462 crate::task_temp_reads::open(path)
463}
464
465fn admit(path: &Path, file_type: Option<&std::fs::FileType>) -> std::io::Result<()> {
466 if crate::watcher_markers::is_marker_path(path)
470 || is_storage_path(path)
471 || match file_type {
472 Some(_) => is_excluded_file_with_metadata(path, file_type, None),
473 None => {
474 crate::os_metadata::is_os_metadata_path(path)
475 || crate::live_db_files::is_registered_file_path(path)
476 }
477 }
478 {
479 return Err(excluded_error());
480 }
481 if file_type.is_some_and(|kind| !kind.is_file() && !kind.is_symlink()) {
482 return Ok(());
483 }
484 let metadata = crate::live_db_files::candidate_metadata(path).ok();
485 if file_type.is_none()
486 && has_sqlite_suffix(path)
487 && !metadata.as_ref().is_some_and(std::fs::Metadata::is_dir)
488 {
489 return Err(excluded_error());
490 }
491 if metadata.as_ref().is_some_and(std::fs::Metadata::is_dir) {
492 return Ok(());
493 }
494 let excluded_alias = metadata
495 .as_ref()
496 .is_some_and(|metadata| metadata.file_type().is_symlink())
497 && path.canonicalize().is_ok_and(|target| is_excluded(&target));
498 if excluded_alias
499 || crate::live_db_files::is_live_sqlite_file_with_metadata(path, metadata.as_ref())
500 {
501 Err(excluded_error())
502 } else {
503 Ok(())
504 }
505}
506
507fn excluded_error() -> std::io::Error {
508 std::io::Error::new(
509 std::io::ErrorKind::PermissionDenied,
510 "internal storage and SQLite files are not project source",
511 )
512}
513
514#[cfg(any(test, feature = "test-support"))]
515pub use open_probe::{record_open, Probe};
516
517#[cfg(any(test, feature = "test-support"))]
518pub mod open_probe {
519 use super::*;
520 use std::collections::BTreeMap;
521 use std::sync::{Arc, Mutex};
522
523 type Opens = Arc<Mutex<Vec<PathBuf>>>;
524 fn probes() -> &'static Mutex<BTreeMap<PathBuf, Opens>> {
525 static PROBES: OnceLock<Mutex<BTreeMap<PathBuf, Opens>>> = OnceLock::new();
526 PROBES.get_or_init(Mutex::default)
527 }
528
529 pub struct Probe {
530 root: PathBuf,
531 opens: Opens,
532 }
533
534 impl Probe {
535 pub fn new(root: &Path) -> Self {
536 let opens = Arc::new(Mutex::new(Vec::new()));
537 probes()
538 .lock()
539 .unwrap()
540 .insert(root.to_path_buf(), opens.clone());
541 Self {
542 root: root.to_path_buf(),
543 opens,
544 }
545 }
546
547 pub fn paths(&self) -> Vec<PathBuf> {
548 self.opens.lock().unwrap().clone()
549 }
550 }
551
552 impl Drop for Probe {
553 fn drop(&mut self) {
554 probes().lock().unwrap().remove(&self.root);
555 }
556 }
557
558 pub fn record_open(path: &Path) {
559 for (root, opens) in probes().lock().unwrap().iter() {
560 if path.starts_with(root) {
561 opens.lock().unwrap().push(path.to_path_buf());
562 }
563 }
564 }
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570
571 #[test]
572 fn storage_root_lookup_uses_supplied_identity_and_containment() {
573 struct Policy {
574 original: PathBuf,
575 identity: PathBuf,
576 storage: PathBuf,
577 allow: bool,
578 compared: std::cell::Cell<bool>,
579 }
580 impl crate::read_policy::StoragePathPolicy for Policy {
581 fn identity(&self, path: &Path) -> PathBuf {
582 assert_eq!(path, self.original);
583 self.identity.clone()
584 }
585
586 fn contains(&self, path: &Path, prefix: &Path) -> bool {
587 assert_eq!(path, self.identity);
588 if prefix == self.storage {
589 self.compared.set(true);
590 self.allow
591 } else {
592 false
593 }
594 }
595 }
596
597 let dir = tempfile::tempdir().unwrap();
598 let root = dir.path().canonicalize().unwrap();
599 let storage = root.join("storage");
600 register_storage_root(&storage);
601 let mut policy = Policy {
602 original: root.join("alias"),
603 identity: root.join("opaque-identity"),
604 storage: storage.clone(),
605 allow: true,
606 compared: std::cell::Cell::new(false),
607 };
608 assert_eq!(
609 storage_root_for_path(&policy.original, &policy),
610 Some(storage)
611 );
612 assert!(policy.compared.get());
613 policy.allow = false;
614 policy.compared.set(false);
615 assert_eq!(storage_root_for_path(&policy.original, &policy), None);
616 assert!(policy.compared.get());
617 }
618
619 #[test]
620 fn gitdir_lines_parse_absolute_relative_and_malformed() {
621 assert_eq!(
624 parse_gitdir_bytes(b"gitdir: /repo/.git/worktrees/wt\n"),
625 Some(PathBuf::from("/repo/.git/worktrees/wt"))
626 );
627 assert_eq!(
628 parse_gitdir_bytes(b" gitdir: ../.git/worktrees/wt \r\n"),
629 Some(PathBuf::from("../.git/worktrees/wt"))
630 );
631 for malformed in [
632 b"gitdir:".as_slice(),
633 b"gitdir: \n",
634 b"not a gitdir\n",
635 b"",
636 b"gitdir : /repo/.git/worktrees/wt\n",
637 ] {
638 assert_eq!(parse_gitdir_bytes(malformed), None, "{malformed:?}");
639 }
640 }
641
642 #[test]
643 fn windows_gitdir_lines_name_a_worktrees_admin_dir() {
644 for line in [
647 "gitdir: C:/repo/.git/worktrees/wt\n",
648 "gitdir: C:/repo/.git/worktrees/wt",
649 ] {
650 let target =
651 parse_gitdir_bytes(line.as_bytes()).expect("Windows gitdir line must parse");
652 assert_eq!(
653 target.parent().and_then(|parent| parent.file_name()),
654 Some(std::ffi::OsStr::new("worktrees"))
655 );
656 assert_eq!(
657 target.parent().and_then(|parent| parent.parent()),
658 Some(std::path::Path::new("C:/repo/.git"))
659 );
660 }
661 let target = parse_gitdir_bytes(b"gitdir: ../.git/modules/sub\n").unwrap();
663 assert_ne!(
664 target.parent().and_then(|parent| parent.file_name()),
665 Some(std::ffi::OsStr::new("worktrees"))
666 );
667 }
668
669 #[test]
670 fn commondir_points_at_the_shared_git_dir() {
671 let dir = tempfile::tempdir().unwrap();
672 let root = dir.path().canonicalize().unwrap();
673 let common = root.join(".git");
674 let admin = common.join("worktrees").join("wt");
675 std::fs::create_dir_all(&admin).unwrap();
676 std::fs::write(admin.join("commondir"), "../../\n").unwrap();
677 assert_eq!(read_commondir_target(&admin), Some(PathBuf::from("../../")));
678 assert_eq!(read_commondir_target(&common), None);
679 }
680
681 #[test]
682 fn hand_rolled_worktree_layout_resolves_without_git() {
683 let dir = tempfile::tempdir().unwrap();
686 let root = dir.path().canonicalize().unwrap();
687 let main = root.join("main");
688 let linked = main.join("linked");
689 let admin = main.join(".git").join("worktrees").join("linked");
690 std::fs::create_dir_all(&admin).unwrap();
691 std::fs::create_dir_all(&linked).unwrap();
692 std::fs::write(
693 linked.join(".git"),
694 format!("gitdir: {}\n", admin.display()),
695 )
696 .unwrap();
697 std::fs::write(
698 admin.join("gitdir"),
699 format!("{}\n", linked.join(".git").display()),
700 )
701 .unwrap();
702 std::fs::write(admin.join("commondir"), "../..\n").unwrap();
703 let boundary = NestedWorktreeBoundary::for_root(&main);
704 assert!(boundary.is_nested_worktree_root(&linked));
705 assert!(!boundary.is_nested_worktree_root(&main));
706 assert!(!boundary.is_nested_worktree_root(&root));
707 assert!(boundary.is_under_nested_worktree(&linked.join("file.rs")));
708 assert!(!boundary.is_under_nested_worktree(&main.join("file.rs")));
709 }
710}