use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use rustc_hash::FxHashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectEntry {
Missing,
Outside,
Inside,
}
#[must_use]
pub fn project_scope_base(root: &Path) -> PathBuf {
let Ok(root) = dunce::canonicalize(root) else {
return root.to_path_buf();
};
let cache = SCOPE_BASES.get_or_init(Mutex::default);
let generation = match cache.lock() {
Ok(bases) => {
if let Some(base) = bases.bases.get(&root) {
return base.clone();
}
bases.generation
}
Err(_) => return uncached_scope_base(&root),
};
let base = uncached_scope_base(&root);
if let Ok(mut bases) = cache.lock()
&& bases.generation == generation
{
bases.bases.insert(root, base.clone());
}
base
}
#[derive(Default)]
struct ScopeBases {
bases: FxHashMap<PathBuf, PathBuf>,
generation: u64,
}
static SCOPE_BASES: OnceLock<Mutex<ScopeBases>> = OnceLock::new();
pub fn clear_project_scope_bases() {
if let Some(Ok(mut bases)) = SCOPE_BASES.get().map(Mutex::lock) {
bases.bases.clear();
bases.generation = bases.generation.wrapping_add(1);
}
}
fn uncached_scope_base(root: &Path) -> PathBuf {
if let Some(top) = project_checkout_top(root) {
return top.to_path_buf();
}
workspace_root_above(root).unwrap_or_else(|| root.to_path_buf())
}
pub fn project_checkout_top(root: &Path) -> Option<&Path> {
let top = root
.ancestors()
.take_while(|dir| test_ceiling::allows(dir))
.find(|dir| dir.join(".git").symlink_metadata().is_ok())?;
(top == root || !is_home_or_above(top)).then_some(top)
}
fn workspace_root_above(root: &Path) -> Option<PathBuf> {
root.ancestors()
.skip(1)
.take_while(|dir| !is_home_or_above(dir) && test_ceiling::allows(dir))
.find(|dir| workspace_root_lists(dir, root))
.map(Path::to_path_buf)
}
fn workspace_root_lists(workspace_root: &Path, member: &Path) -> bool {
use fallow_types::read_guard::{DEFAULT_MAX_READ_BYTES, read_to_string_inside};
let mut patterns = read_to_string_inside(
workspace_root,
Path::new("pnpm-workspace.yaml"),
DEFAULT_MAX_READ_BYTES,
)
.map(|content| crate::pnpm_workspace_packages(&content))
.unwrap_or_default();
let manifest = workspace_root.join("package.json");
if manifest.symlink_metadata().is_ok()
&& let Ok(pkg) = crate::PackageJson::load_inside(workspace_root, &manifest)
{
patterns.extend(pkg.workspace_patterns());
}
!patterns.is_empty()
&& crate::ManifestPatternMatcher::from_patterns(patterns.iter().map(String::as_str))
.declares(workspace_root, member)
}
pub fn is_home_or_above(dir: &Path) -> bool {
let homes = ["HOME", "USERPROFILE"]
.iter()
.filter_map(std::env::var_os)
.filter(|home| !home.is_empty())
.filter_map(|home| dunce::canonicalize(home).ok());
is_home_or_above_in(dir, homes)
}
fn is_home_or_above_in(dir: &Path, mut homes: impl Iterator<Item = PathBuf>) -> bool {
dir.parent().is_none() || homes.any(|home| home.starts_with(dir))
}
mod test_ceiling {
use std::path::Path;
#[cfg(test)]
thread_local! {
static CEILING: std::cell::RefCell<Option<std::path::PathBuf>> =
const { std::cell::RefCell::new(None) };
}
#[cfg(test)]
pub fn set(dir: &Path) {
CEILING.with(|ceiling| *ceiling.borrow_mut() = Some(dir.to_path_buf()));
}
#[cfg(test)]
pub(super) fn allows(dir: &Path) -> bool {
CEILING.with(|ceiling| {
ceiling
.borrow()
.as_ref()
.is_none_or(|top| dir.starts_with(top))
})
}
#[cfg(not(test))]
pub(super) const fn allows(_dir: &Path) -> bool {
true
}
}
#[cfg(test)]
pub use test_ceiling::set as set_test_ceiling;
pub fn project_entry(canonical_root: &Path, path: &Path) -> ProjectEntry {
project_entry_within(canonical_root, canonical_root, path)
}
pub fn project_entry_within(
canonical_base: &Path,
canonical_root: &Path,
path: &Path,
) -> ProjectEntry {
let joined = canonical_root.join(path);
let Ok(relative) = joined.strip_prefix(canonical_base) else {
return ProjectEntry::Outside;
};
let mut current = canonical_base.to_path_buf();
let mut components = relative.components();
while let Some(component) = components.next() {
match component {
Component::CurDir => {}
Component::ParentDir => {
current.pop();
if !current.starts_with(canonical_base) {
return ProjectEntry::Outside;
}
}
Component::Normal(name) => {
let next = current.join(name);
match next.symlink_metadata() {
Ok(meta) if meta.file_type().is_symlink() => match dunce::canonicalize(&next) {
Ok(target) if target.starts_with(canonical_base) => current = target,
_ => return ProjectEntry::Outside,
},
Ok(_) => current = next,
Err(_) => return missing_rest(canonical_base, next, components),
}
}
Component::RootDir | Component::Prefix(_) => return ProjectEntry::Outside,
}
}
ProjectEntry::Inside
}
pub fn project_path_entry(
canonical_base: &Path,
base_as_given: &Path,
canonical_root: &Path,
path: &Path,
) -> ProjectEntry {
if !path.is_absolute() {
return project_entry_within(canonical_base, canonical_root, path);
}
if !absolute_path_text_inside(path, canonical_base, base_as_given) {
return ProjectEntry::Outside;
}
let Some((existing, resolved)) = path.ancestors().find_map(|dir| {
dunce::canonicalize(dir)
.ok()
.map(|resolved| (dir, resolved))
}) else {
return ProjectEntry::Outside;
};
let Ok(rest) = path.strip_prefix(existing) else {
return ProjectEntry::Outside;
};
project_entry_within(canonical_base, canonical_base, &resolved.join(rest))
}
#[must_use]
pub fn absolute_path_text_inside(path: &Path, canonical_base: &Path, base_as_given: &Path) -> bool {
if is_share_or_device_text(path) {
return false;
}
let normalized = fallow_types::path_guard::lexically_normalized(path);
let given = std::path::absolute(base_as_given)
.map(|base| fallow_types::path_guard::lexically_normalized(&base));
normalized.starts_with(canonical_base) || given.is_ok_and(|given| normalized.starts_with(given))
}
fn is_share_or_device_text(path: &Path) -> bool {
let bytes = path.as_os_str().as_encoded_bytes();
let separator = |byte: u8| byte == b'/' || byte == b'\\';
if bytes.len() >= 2 && separator(bytes[0]) && separator(bytes[1]) {
return true;
}
matches!(
path.components().next(),
Some(Component::Prefix(prefix)) if !matches!(prefix.kind(), std::path::Prefix::Disk(_))
)
}
#[must_use]
pub fn base_as_given(
root_as_given: &Path,
canonical_root: &Path,
canonical_base: &Path,
) -> PathBuf {
let Ok(below) = canonical_root.strip_prefix(canonical_base) else {
return canonical_base.to_path_buf();
};
let mut given = std::path::absolute(root_as_given).map_or_else(
|_| root_as_given.to_path_buf(),
|root| fallow_types::path_guard::lexically_normalized(&root),
);
for _ in below.components() {
given.pop();
}
given
}
fn missing_rest(
canonical_base: &Path,
missing: PathBuf,
mut rest: std::path::Components<'_>,
) -> ProjectEntry {
let mut current = missing;
while let Some(component) = rest.next() {
match component {
Component::CurDir => {}
Component::ParentDir => {
current.pop();
if !current.starts_with(canonical_base) {
return ProjectEntry::Outside;
}
if current.symlink_metadata().is_ok() {
return project_entry_within(
canonical_base,
canonical_base,
¤t.join(rest.as_path()),
);
}
}
Component::Normal(name) => current.push(name),
Component::RootDir | Component::Prefix(_) => return ProjectEntry::Outside,
}
}
if current.symlink_metadata().is_ok() {
return project_entry_within(canonical_base, canonical_base, ¤t);
}
ProjectEntry::Missing
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn missing_outside_and_inside_paths() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::write(root.join("a.json"), "{}").unwrap();
assert_eq!(
project_entry(&root, Path::new("a.json")),
ProjectEntry::Inside
);
assert_eq!(
project_entry(&root, Path::new("b.json")),
ProjectEntry::Missing
);
assert_eq!(
project_entry(&root, Path::new("../b.json")),
ProjectEntry::Outside
);
assert_eq!(
project_entry(&root, Path::new("/nonexistent/b.json")),
ProjectEntry::Outside
);
assert_eq!(
project_entry(&root, Path::new("sub/../a.json")),
ProjectEntry::Inside
);
}
#[cfg(unix)]
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn a_missing_file_behind_an_outside_directory_link_is_outside() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(&root).unwrap();
std::os::unix::fs::symlink(dir.path(), root.join("up")).unwrap();
assert_eq!(
project_entry(&root, Path::new("up/missing.json")),
ProjectEntry::Outside
);
}
#[cfg(unix)]
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn a_dot_dot_after_a_link_goes_to_the_parent_of_the_link_target() {
let dir = tempfile::tempdir().unwrap();
let outer = dunce::canonicalize(dir.path()).unwrap();
let root = outer.join("project");
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::create_dir_all(outer.join("elsewhere/deep")).unwrap();
std::fs::write(outer.join("elsewhere/a.json"), "{}").unwrap();
std::fs::write(root.join("a.json"), "{}").unwrap();
std::os::unix::fs::symlink(outer.join("elsewhere/deep"), root.join("away")).unwrap();
std::os::unix::fs::symlink(&root, root.join("sub/home")).unwrap();
for path in [
"away/../a.json",
"away/../missing.json",
"sub/home/../../a.json",
"sub/home/../missing/../../a.json",
] {
assert_eq!(
project_entry(&root, Path::new(path)),
ProjectEntry::Outside,
"{path}"
);
}
assert_eq!(
project_entry(&root, Path::new("sub/home/a.json")),
ProjectEntry::Inside
);
assert_eq!(
project_entry(&root, Path::new("sub/home/../project/a.json")),
ProjectEntry::Outside
);
assert_eq!(
project_entry(&root, Path::new("missing/../a.json")),
ProjectEntry::Inside
);
assert_eq!(
project_entry_within(&outer, &root, Path::new("../elsewhere/a.json")),
ProjectEntry::Inside
);
assert_eq!(
project_entry_within(&root, &root, Path::new("../elsewhere/a.json")),
ProjectEntry::Outside
);
}
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn the_scope_base_is_the_git_top_level_or_the_root() {
let dir = tempfile::tempdir().unwrap();
let top = dunce::canonicalize(dir.path()).unwrap();
set_test_ceiling(&top);
let package = top.join("packages/a");
std::fs::create_dir_all(&package).unwrap();
assert_eq!(project_scope_base(&package), package);
std::fs::create_dir(top.join(".git")).unwrap();
clear_project_scope_bases();
assert_eq!(project_scope_base(&package), top);
assert_eq!(project_scope_base(&top), top);
}
fn workspace_without_git(manifest: (&str, &str)) -> (tempfile::TempDir, PathBuf, PathBuf) {
let dir = tempfile::tempdir().unwrap();
let outer = dunce::canonicalize(dir.path()).unwrap();
set_test_ceiling(&outer);
let top = outer.join("ws");
let member = top.join("packages/a");
std::fs::create_dir_all(&member).unwrap();
std::fs::write(top.join(manifest.0), manifest.1).unwrap();
(dir, top, member)
}
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn without_git_the_scope_base_is_the_workspace_root_that_lists_the_root() {
for manifest in [
("pnpm-workspace.yaml", "packages:\n - 'packages/*'\n"),
("package.json", r#"{"workspaces": ["packages/*"]}"#),
(
"package.json",
r#"{"workspaces": {"packages": ["./packages/*"]}}"#,
),
] {
let (_dir, top, member) = workspace_without_git(manifest);
assert_eq!(project_scope_base(&member), top, "{manifest:?}");
assert_eq!(project_scope_base(&top), top, "{manifest:?}");
}
}
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn without_git_a_workspace_root_that_does_not_list_the_root_is_not_the_base() {
for manifest in [
("pnpm-workspace.yaml", "packages:\n - 'apps/*'\n"),
(
"package.json",
r#"{"workspaces": ["packages/*", "!packages/a"]}"#,
),
("package.json", r#"{"name": "no-workspaces"}"#),
] {
let (_dir, _top, member) = workspace_without_git(manifest);
assert_eq!(project_scope_base(&member), member, "{manifest:?}");
}
}
#[test]
fn the_file_system_root_is_never_a_checkout_top_level() {
assert!(is_home_or_above(Path::new("/")));
}
#[test]
fn without_home_variables_only_the_file_system_root_counts_as_home() {
assert!(is_home_or_above_in(Path::new("/"), std::iter::empty()));
assert!(!is_home_or_above_in(Path::new("/srv"), std::iter::empty()));
assert!(!is_home_or_above_in(
Path::new("/srv/project"),
std::iter::empty()
));
let homes = || std::iter::once(PathBuf::from("/srv/user"));
assert!(is_home_or_above_in(Path::new("/srv"), homes()));
assert!(is_home_or_above_in(Path::new("/srv/user"), homes()));
assert!(!is_home_or_above_in(Path::new("/srv/user/code"), homes()));
}
#[test]
fn share_and_device_paths_are_refused_by_text() {
let base = &abs("/base");
for path in [
"//host/share/x",
r"\\host\share\x",
r"\\?\C:\base\x",
r"\\?\UNC\host\share\x",
r"\\.\pipe\x",
"//./pipe/x",
] {
assert!(
!absolute_path_text_inside(Path::new(path), base, base),
"{path}"
);
}
assert!(absolute_path_text_inside(&abs("/base/a/../b"), base, base));
assert!(!absolute_path_text_inside(
&abs("/base/../other"),
base,
base
));
assert!(absolute_path_text_inside(
&abs("/given/a"),
base,
&abs("/given")
));
}
#[cfg(windows)]
#[test]
fn windows_share_and_device_prefixes_are_refused() {
let base = Path::new(r"C:\base");
for path in [
r"\\host\share\x",
r"\\?\UNC\host\share\x",
r"\\?\C:\base\x",
r"\\.\COM1",
] {
assert!(
!absolute_path_text_inside(Path::new(path), base, base),
"{path}"
);
assert_eq!(
project_path_entry(base, base, base, Path::new(path)),
ProjectEntry::Outside,
"{path}"
);
}
assert!(absolute_path_text_inside(
Path::new(r"C:\base\x"),
base,
base
));
}
#[test]
fn the_base_keeps_the_spelling_of_the_given_root() {
assert_eq!(
base_as_given(
&abs("/link/repo/packages/a"),
&abs("/real/repo/packages/a"),
&abs("/real/repo"),
),
abs("/link/repo")
);
assert_eq!(
base_as_given(&abs("/x"), &abs("/real/x"), &abs("/other")),
abs("/other")
);
}
fn abs(path: &str) -> PathBuf {
if cfg!(windows) {
PathBuf::from(format!("C:{}", path.replace('/', "\\")))
} else {
PathBuf::from(path)
}
}
#[cfg(unix)]
#[test]
fn a_share_path_key_is_outside_without_a_file_system_call() {
let base = Path::new("/nonexistent-base");
assert_eq!(
project_path_entry(base, base, base, Path::new("//host/share/CODEOWNERS")),
ProjectEntry::Outside
);
}
#[cfg(unix)]
#[test]
#[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
fn a_link_after_a_dot_dot_out_of_a_missing_dir_is_walked_on_disk() {
let dir = tempfile::tempdir().unwrap();
let outer = dunce::canonicalize(dir.path()).unwrap();
let root = outer.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(outer.join("elsewhere")).unwrap();
std::os::unix::fs::symlink(outer.join("elsewhere"), root.join("away")).unwrap();
for path in ["missing/../away/new.json", "a/b/../../away/new.json"] {
assert_eq!(
project_entry(&root, Path::new(path)),
ProjectEntry::Outside,
"{path}"
);
}
assert_eq!(
project_entry(&root, Path::new("missing/../new.json")),
ProjectEntry::Missing
);
}
}