use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, RwLock};
fn storage_roots() -> &'static RwLock<BTreeSet<PathBuf>> {
static ROOTS: OnceLock<RwLock<BTreeSet<PathBuf>>> = OnceLock::new();
ROOTS.get_or_init(RwLock::default)
}
pub fn register_storage_root(path: &Path) {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else if let Ok(cwd) = std::env::current_dir() {
cwd.join(path)
} else {
return;
};
if storage_roots()
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.contains(&absolute)
{
return;
}
#[cfg(any(test, feature = "test-support"))]
REGISTER_CANONICALIZATIONS.with(|count| count.set(count.get() + 1));
let canonical =
crate::production_storage::canonicalized_with(&absolute, &|p| p.canonicalize().ok());
let mut roots = storage_roots().write().unwrap_or_else(|p| p.into_inner());
roots.insert(absolute);
roots.insert(canonical);
}
pub struct NestedWorktreeBoundary {
root: PathBuf,
common_dir: OnceLock<Option<PathBuf>>,
verdicts: Mutex<HashMap<PathBuf, bool>>,
}
impl NestedWorktreeBoundary {
pub fn for_root(root: &Path) -> Self {
Self {
root: root.to_path_buf(),
common_dir: OnceLock::new(),
verdicts: Mutex::new(HashMap::new()),
}
}
fn common_dir(&self) -> Option<&Path> {
self.common_dir
.get_or_init(|| project_git_common_dir(&self.root))
.as_deref()
}
pub fn is_nested_worktree_root(&self, dir: &Path) -> bool {
if dir == self.root {
return false;
}
if let Some(verdict) = self
.verdicts
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(dir)
{
return *verdict;
}
let verdict = std::fs::symlink_metadata(dir.join(".git"))
.is_ok_and(|metadata| metadata.is_file())
&& self
.common_dir()
.is_some_and(|common| worktree_gitdir_points_at(dir, common));
self.verdicts
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(dir.to_path_buf(), verdict);
verdict
}
pub fn is_under_nested_worktree(&self, path: &Path) -> bool {
let mut current = Some(path);
while let Some(dir) = current {
if dir == self.root || !dir.starts_with(&self.root) {
return false;
}
if self.is_nested_worktree_root(dir) {
return true;
}
current = dir.parent();
}
false
}
}
fn project_git_common_dir(root: &Path) -> Option<PathBuf> {
let mut current = if root.is_absolute() {
root.to_path_buf()
} else {
std::env::current_dir().ok()?.join(root)
};
loop {
let dot_git = current.join(".git");
match std::fs::symlink_metadata(&dot_git) {
Ok(metadata) if metadata.is_dir() => return canonicalized(&dot_git),
Ok(metadata) if metadata.is_file() => {
let target = read_gitdir_target(&dot_git)?;
let target = if target.is_absolute() {
target
} else {
current.join(target)
};
if let Some(common) = read_commondir_target(&target) {
let common = if common.is_absolute() {
common
} else {
target.join(common)
};
return canonicalized(&common);
}
return canonicalized(&target);
}
Ok(_) => return None,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let Some(parent) = current.parent().map(Path::to_path_buf) else {
return None;
};
current = parent;
}
Err(_) => return None,
}
}
}
fn worktree_gitdir_points_at(dir: &Path, common_dir: &Path) -> bool {
let target = match read_gitdir_target(&dir.join(".git")) {
Some(target) => target,
None => return false,
};
let target = if target.is_absolute() {
target
} else {
dir.join(target)
};
worktree_common_candidate(&target).is_some_and(|candidate| candidate == *common_dir)
}
fn worktree_common_candidate(gitdir_target: &Path) -> Option<PathBuf> {
let worktrees = gitdir_target.parent()?;
if worktrees.file_name()? != std::ffi::OsStr::new("worktrees") {
return None;
}
canonicalized(worktrees.parent()?)
}
fn canonicalized(path: &Path) -> Option<PathBuf> {
std::fs::canonicalize(path).ok()
}
fn read_gitdir_target(dot_git: &Path) -> Option<PathBuf> {
parse_gitdir_bytes(&capped_read(dot_git, 4096)?)
}
fn read_commondir_target(gitdir: &Path) -> Option<PathBuf> {
let bytes = capped_read(&gitdir.join("commondir"), 4096)?;
let line = bytes.split(|byte| *byte == b'\n').next()?;
let trimmed = trim_ascii_whitespace(line);
if trimmed.is_empty() {
return None;
}
bytes_to_path(trimmed)
}
fn parse_gitdir_bytes(bytes: &[u8]) -> Option<PathBuf> {
let line = bytes.split(|byte| *byte == b'\n').next()?;
let line = line.strip_suffix(b"\r").unwrap_or(line);
let line = trim_ascii_whitespace(line);
let rest = trim_ascii_whitespace(line.strip_prefix(b"gitdir:")?);
if rest.is_empty() {
return None;
}
bytes_to_path(rest)
}
fn trim_ascii_whitespace(mut bytes: &[u8]) -> &[u8] {
while let Some((first, rest)) = bytes.split_first() {
if first.is_ascii_whitespace() {
bytes = rest;
} else {
break;
}
}
while let Some((last, rest)) = bytes.split_last() {
if last.is_ascii_whitespace() {
bytes = rest;
} else {
break;
}
}
bytes
}
#[cfg(unix)]
fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
Some(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
}
#[cfg(not(unix))]
fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
std::str::from_utf8(bytes).ok().map(PathBuf::from)
}
fn capped_read(path: &Path, cap: u64) -> Option<Vec<u8>> {
use std::io::Read;
let file = crate::bounded_io::open_content_file(path).ok()?;
let mut bytes = Vec::new();
file.take(cap).read_to_end(&mut bytes).ok()?;
Some(bytes)
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static REGISTER_CANONICALIZATIONS: std::cell::Cell<u64> =
const { std::cell::Cell::new(0) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn register_canonicalizations_for_test() -> u64 {
REGISTER_CANONICALIZATIONS.with(|count| count.get())
}
#[cfg(any(test, feature = "test-support"))]
pub fn reset_register_canonicalizations_for_test() {
REGISTER_CANONICALIZATIONS.with(|count| count.set(0));
}
pub fn is_excluded(path: &Path) -> bool {
admit(path, None).is_err()
}
pub fn is_excluded_with_file_type(path: &Path, file_type: Option<&std::fs::FileType>) -> bool {
admit(path, file_type).is_err()
}
pub fn is_excluded_event(path: &Path) -> bool {
is_storage_path(path)
|| crate::os_metadata::is_os_metadata_path(path)
|| crate::live_db_files::is_registered_file_path(path)
|| has_sqlite_suffix(path) && path.metadata().is_ok_and(|metadata| !metadata.is_dir())
}
pub fn is_excluded_file_by_path(path: &Path) -> bool {
crate::watcher_markers::is_marker_path(path)
|| is_storage_path(path)
|| crate::os_metadata::is_os_metadata_path(path)
|| has_sqlite_suffix(path)
|| crate::live_db_files::is_registered_file_path(path)
}
fn is_storage_path(path: &Path) -> bool {
storage_roots()
.read()
.unwrap_or_else(|p| p.into_inner())
.iter()
.any(|root| path.starts_with(root))
}
pub fn storage_root_for_path(
path: &Path,
policy: &dyn crate::read_policy::StoragePathPolicy,
) -> Option<PathBuf> {
let path = policy.identity(path);
storage_roots()
.read()
.unwrap_or_else(|p| p.into_inner())
.iter()
.find(|root| policy.contains(&path, root))
.cloned()
}
fn is_excluded_file(path: &Path) -> bool {
crate::os_metadata::is_os_metadata_path(path)
|| has_sqlite_suffix(path) && !path.is_dir()
|| crate::live_db_files::is_registered_file_path(path)
}
fn has_sqlite_suffix(path: &Path) -> bool {
path.file_name().is_some_and(|name| {
let name = name.as_encoded_bytes();
[
b"-wal".as_slice(),
b"-shm",
b"-journal",
b".db",
b".sqlite",
b".sqlite3",
]
.iter()
.any(|suffix| {
name.len() >= suffix.len()
&& name[name.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
})
})
}
fn is_excluded_file_with_metadata(
path: &Path,
file_type: Option<&std::fs::FileType>,
metadata: Option<&std::fs::Metadata>,
) -> bool {
crate::os_metadata::is_os_metadata_path(path)
|| has_sqlite_suffix(path)
&& !file_type.is_some_and(std::fs::FileType::is_dir)
&& !metadata.is_some_and(std::fs::Metadata::is_dir)
|| crate::live_db_files::is_registered_file_path(path)
}
pub fn is_sqlite_or_metadata(path: &Path) -> bool {
is_excluded_file(path) || crate::live_db_files::is_live_sqlite_file(path)
}
pub fn reader_bounded(
path: &Path,
deadline: Option<std::time::Instant>,
authorized_task_artifact: bool,
) -> std::io::Result<crate::bounded_io::Reader> {
admit_bounded(path, authorized_task_artifact)?;
crate::bounded_io::reader(path, deadline)
}
fn admit_bounded(path: &Path, authorized_task_artifact: bool) -> std::io::Result<()> {
if authorized_task_artifact {
if is_sqlite_or_metadata(path) || std::fs::symlink_metadata(path)?.file_type().is_symlink()
{
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"SQLite files and aliases are not readable task content",
));
}
} else {
admit(path, None)?;
}
#[cfg(any(test, feature = "test-support"))]
record_open(path);
Ok(())
}
pub fn read(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
let path = path.as_ref();
admit(path, None)?;
#[cfg(any(test, feature = "test-support"))]
record_open(path);
use std::io::Read;
crate::io_accounting::WORK
.content_reads
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut bytes = Vec::new();
crate::task_temp_reads::open(path)?.read_to_end(&mut bytes)?;
crate::io_accounting::WORK
.content_read_bytes
.fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
Ok(bytes)
}
pub fn read_to_string(path: impl AsRef<Path>) -> std::io::Result<String> {
String::from_utf8(read(path)?)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}
pub fn open(path: impl AsRef<Path>) -> std::io::Result<std::fs::File> {
let path = path.as_ref();
admit(path, None)?;
#[cfg(any(test, feature = "test-support"))]
record_open(path);
crate::io_accounting::WORK
.content_reads
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
crate::task_temp_reads::open(path)
}
fn admit(path: &Path, file_type: Option<&std::fs::FileType>) -> std::io::Result<()> {
if crate::watcher_markers::is_marker_path(path)
|| is_storage_path(path)
|| match file_type {
Some(_) => is_excluded_file_with_metadata(path, file_type, None),
None => {
crate::os_metadata::is_os_metadata_path(path)
|| crate::live_db_files::is_registered_file_path(path)
}
}
{
return Err(excluded_error());
}
if file_type.is_some_and(|kind| !kind.is_file() && !kind.is_symlink()) {
return Ok(());
}
let metadata = crate::live_db_files::candidate_metadata(path).ok();
if file_type.is_none()
&& has_sqlite_suffix(path)
&& !metadata.as_ref().is_some_and(std::fs::Metadata::is_dir)
{
return Err(excluded_error());
}
if metadata.as_ref().is_some_and(std::fs::Metadata::is_dir) {
return Ok(());
}
let excluded_alias = metadata
.as_ref()
.is_some_and(|metadata| metadata.file_type().is_symlink())
&& path.canonicalize().is_ok_and(|target| is_excluded(&target));
if excluded_alias
|| crate::live_db_files::is_live_sqlite_file_with_metadata(path, metadata.as_ref())
{
Err(excluded_error())
} else {
Ok(())
}
}
fn excluded_error() -> std::io::Error {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"internal storage and SQLite files are not project source",
)
}
#[cfg(any(test, feature = "test-support"))]
pub use open_probe::{record_open, Probe};
#[cfg(any(test, feature = "test-support"))]
pub mod open_probe {
use super::*;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
type Opens = Arc<Mutex<Vec<PathBuf>>>;
fn probes() -> &'static Mutex<BTreeMap<PathBuf, Opens>> {
static PROBES: OnceLock<Mutex<BTreeMap<PathBuf, Opens>>> = OnceLock::new();
PROBES.get_or_init(Mutex::default)
}
pub struct Probe {
root: PathBuf,
opens: Opens,
}
impl Probe {
pub fn new(root: &Path) -> Self {
let opens = Arc::new(Mutex::new(Vec::new()));
probes()
.lock()
.unwrap()
.insert(root.to_path_buf(), opens.clone());
Self {
root: root.to_path_buf(),
opens,
}
}
pub fn paths(&self) -> Vec<PathBuf> {
self.opens.lock().unwrap().clone()
}
}
impl Drop for Probe {
fn drop(&mut self) {
probes().lock().unwrap().remove(&self.root);
}
}
pub fn record_open(path: &Path) {
for (root, opens) in probes().lock().unwrap().iter() {
if path.starts_with(root) {
opens.lock().unwrap().push(path.to_path_buf());
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn storage_root_lookup_uses_supplied_identity_and_containment() {
struct Policy {
original: PathBuf,
identity: PathBuf,
storage: PathBuf,
allow: bool,
compared: std::cell::Cell<bool>,
}
impl crate::read_policy::StoragePathPolicy for Policy {
fn identity(&self, path: &Path) -> PathBuf {
assert_eq!(path, self.original);
self.identity.clone()
}
fn contains(&self, path: &Path, prefix: &Path) -> bool {
assert_eq!(path, self.identity);
if prefix == self.storage {
self.compared.set(true);
self.allow
} else {
false
}
}
}
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let storage = root.join("storage");
register_storage_root(&storage);
let mut policy = Policy {
original: root.join("alias"),
identity: root.join("opaque-identity"),
storage: storage.clone(),
allow: true,
compared: std::cell::Cell::new(false),
};
assert_eq!(
storage_root_for_path(&policy.original, &policy),
Some(storage)
);
assert!(policy.compared.get());
policy.allow = false;
policy.compared.set(false);
assert_eq!(storage_root_for_path(&policy.original, &policy), None);
assert!(policy.compared.get());
}
#[test]
fn gitdir_lines_parse_absolute_relative_and_malformed() {
assert_eq!(
parse_gitdir_bytes(b"gitdir: /repo/.git/worktrees/wt\n"),
Some(PathBuf::from("/repo/.git/worktrees/wt"))
);
assert_eq!(
parse_gitdir_bytes(b" gitdir: ../.git/worktrees/wt \r\n"),
Some(PathBuf::from("../.git/worktrees/wt"))
);
for malformed in [
b"gitdir:".as_slice(),
b"gitdir: \n",
b"not a gitdir\n",
b"",
b"gitdir : /repo/.git/worktrees/wt\n",
] {
assert_eq!(parse_gitdir_bytes(malformed), None, "{malformed:?}");
}
}
#[test]
fn windows_gitdir_lines_name_a_worktrees_admin_dir() {
for line in [
"gitdir: C:/repo/.git/worktrees/wt\n",
"gitdir: C:/repo/.git/worktrees/wt",
] {
let target =
parse_gitdir_bytes(line.as_bytes()).expect("Windows gitdir line must parse");
assert_eq!(
target.parent().and_then(|parent| parent.file_name()),
Some(std::ffi::OsStr::new("worktrees"))
);
assert_eq!(
target.parent().and_then(|parent| parent.parent()),
Some(std::path::Path::new("C:/repo/.git"))
);
}
let target = parse_gitdir_bytes(b"gitdir: ../.git/modules/sub\n").unwrap();
assert_ne!(
target.parent().and_then(|parent| parent.file_name()),
Some(std::ffi::OsStr::new("worktrees"))
);
}
#[test]
fn commondir_points_at_the_shared_git_dir() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let common = root.join(".git");
let admin = common.join("worktrees").join("wt");
std::fs::create_dir_all(&admin).unwrap();
std::fs::write(admin.join("commondir"), "../../\n").unwrap();
assert_eq!(read_commondir_target(&admin), Some(PathBuf::from("../../")));
assert_eq!(read_commondir_target(&common), None);
}
#[test]
fn hand_rolled_worktree_layout_resolves_without_git() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let main = root.join("main");
let linked = main.join("linked");
let admin = main.join(".git").join("worktrees").join("linked");
std::fs::create_dir_all(&admin).unwrap();
std::fs::create_dir_all(&linked).unwrap();
std::fs::write(
linked.join(".git"),
format!("gitdir: {}\n", admin.display()),
)
.unwrap();
std::fs::write(
admin.join("gitdir"),
format!("{}\n", linked.join(".git").display()),
)
.unwrap();
std::fs::write(admin.join("commondir"), "../..\n").unwrap();
let boundary = NestedWorktreeBoundary::for_root(&main);
assert!(boundary.is_nested_worktree_root(&linked));
assert!(!boundary.is_nested_worktree_root(&main));
assert!(!boundary.is_nested_worktree_root(&root));
assert!(boundary.is_under_nested_worktree(&linked.join("file.rs")));
assert!(!boundary.is_under_nested_worktree(&main.join("file.rs")));
}
}