use std::path::{Path, PathBuf};
pub use cortexkit_paths::{IdentityError, ProjectRootId};
pub fn project_scope_key(project_root: &Path) -> String {
let canonical = ProjectRootId::from_path(project_root)
.map(ProjectRootId::into_path_buf)
.unwrap_or_else(|_| lexical_normalize(project_root));
hash16(&canonical)
}
pub fn directory_scope_is_narrow(directory: &Path, home: &Path, volume: &Path) -> bool {
project_root_path_is_narrow(directory, home, volume)
&& directory.parent().and_then(Path::parent).is_some()
&& directory.parent() != Some(volume)
&& !directory_is_system_tree(directory)
}
#[cfg(unix)]
fn directory_is_system_tree(directory: &Path) -> bool {
if ["/var/folders", "/private/var/folders"]
.iter()
.any(|root| directory.starts_with(root))
{
return false;
}
[
"/usr",
"/etc",
"/bin",
"/sbin",
"/lib",
"/lib32",
"/lib64",
"/libx32",
"/libexec",
"/opt",
"/var",
"/System",
"/Library",
"/private/etc",
"/private/var",
]
.iter()
.any(|root| directory.starts_with(root))
}
#[cfg(windows)]
fn directory_is_system_tree(directory: &Path) -> bool {
directory
.components()
.find_map(|component| match component {
std::path::Component::Normal(name) => Some(name.to_string_lossy().to_ascii_lowercase()),
_ => None,
})
.is_some_and(|name| {
matches!(
name.as_str(),
"windows" | "program files" | "program files (x86)"
)
})
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn project_root_is_narrow(directory: &Path, home: &Path, volume: &Path) -> Option<bool> {
if !project_root_path_is_narrow(directory, home, volume)
|| project_root_is_shared_temp(directory)
{
return Some(false);
}
protected_directory_alias(directory, home, volume).map(|protected| !protected)
}
}
fn project_root_is_shared_temp(directory: &Path) -> bool {
let directory = crate::policy_path::policy_path(directory);
let platform_temp = std::env::temp_dir();
let roots = std::iter::once(platform_temp.as_path());
#[cfg(unix)]
let roots = roots.chain([
Path::new("/tmp"),
Path::new("/var/tmp"),
Path::new("/private/tmp"),
Path::new("/private/var/tmp"),
]);
let shared = roots
.filter_map(|root| ProjectRootId::from_path(root).ok())
.any(|root| crate::policy_path::policy_path(&root.into_path_buf()) == directory);
shared
}
fn project_root_path_is_narrow(directory: &Path, home: &Path, volume: &Path) -> bool {
directory.is_absolute()
&& directory.parent().is_some()
&& !home.starts_with(directory)
&& directory != volume
}
pub(crate) fn project_root_volume(canonical_root: &Path, home: Option<&Path>) -> Option<PathBuf> {
let (volume, _) = crate::volume::volume_anchor(canonical_root)?;
#[cfg(target_os = "linux")]
return project_root_volume_with(canonical_root, volume, home, read_mountinfo, |path| {
crate::volume::volume_anchor(path).map(|(volume, _)| volume)
});
#[cfg(not(target_os = "linux"))]
{
let _ = (canonical_root, home);
Some(volume)
}
}
#[cfg(target_os = "linux")]
fn project_root_volume_with(
root: &Path,
volume: PathBuf,
home: Option<&Path>,
read: impl FnOnce() -> std::io::Result<Vec<u8>>,
volume_of: impl FnOnce(&Path) -> Option<PathBuf>,
) -> Option<PathBuf> {
if root != volume {
return Some(volume);
}
let Some(parent) = volume.parent() else {
return Some(volume);
};
let mountinfo = match read() {
Ok(text) => text,
Err(error) => {
static LOGGED: std::sync::Once = std::sync::Once::new();
LOGGED.call_once(|| {
crate::slog_warn!(
"cannot read {MOUNTINFO_PATH} ({error}); mount points are judged as volume roots"
);
});
return Some(volume);
}
};
match mount_root_in(&mountinfo, &volume) {
MountRoot::Subdirectory(source_root) if !source_root_is_home_like(&source_root, home) => {
volume_of(parent)
}
_ => Some(volume),
}
}
#[cfg(target_os = "linux")]
const MOUNTINFO_PATH: &str = "/proc/self/mountinfo";
#[cfg(target_os = "linux")]
const MOUNTINFO_MAX_BYTES: u64 = 16 * 1024 * 1024;
#[cfg(target_os = "linux")]
const MOUNTINFO_BUDGET: std::time::Duration = std::time::Duration::from_millis(500);
#[cfg(target_os = "linux")]
fn read_mountinfo() -> std::io::Result<Vec<u8>> {
use std::io::Read;
crate::bounded_io::with_budget(None, || {
crate::bounded_io::run(
Path::new(MOUNTINFO_PATH),
Some(std::time::Instant::now() + MOUNTINFO_BUDGET),
|path| {
let mut bytes = Vec::new();
std::fs::File::open(&path)?
.take(MOUNTINFO_MAX_BYTES + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MOUNTINFO_MAX_BYTES {
return Err(std::io::Error::other("mount table exceeds the size limit"));
}
Ok(bytes)
},
)
})
}
#[cfg(target_os = "linux")]
#[derive(Debug, PartialEq, Eq)]
enum MountRoot {
WholeVolume,
Subdirectory(PathBuf),
Unknown,
}
#[cfg(target_os = "linux")]
fn mount_root_in(mountinfo: &[u8], mount_point: &Path) -> MountRoot {
let Some(fields) = mountinfo
.split(|byte| *byte == b'\n')
.map(|line| line.split(|byte| *byte == b' ').collect::<Vec<_>>())
.filter(|fields| {
fields
.get(4)
.is_some_and(|point| unescape_mount_field(point) == mount_point)
})
.last()
else {
return MountRoot::Unknown;
};
let Some(separator) = fields
.iter()
.skip(6)
.position(|field| *field == b"-".as_slice())
else {
return MountRoot::Unknown;
};
let tail = &fields[6 + separator + 1..];
let (Some(fs_type), Some(super_options)) = (tail.first(), tail.get(2)) else {
return MountRoot::Unknown;
};
let root = unescape_mount_field(fields[3]);
if !root.is_absolute() {
return MountRoot::Unknown;
}
if root == Path::new("/") {
return MountRoot::WholeVolume;
}
let subvolume = super_options
.split(|byte| *byte == b',')
.find_map(|option| option.strip_prefix(b"subvol=".as_slice()))
.map(unescape_mount_field);
match subvolume {
Some(subvolume) if root == subvolume => MountRoot::WholeVolume,
Some(subvolume) if root.starts_with(&subvolume) => MountRoot::Subdirectory(root),
Some(_) => MountRoot::Unknown,
None if matches!(*fs_type, b"btrfs" | b"bcachefs") => MountRoot::Unknown,
None => MountRoot::Subdirectory(root),
}
}
#[cfg(target_os = "linux")]
fn unescape_mount_field(bytes: &[u8]) -> PathBuf {
use std::os::unix::ffi::OsStrExt;
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let octal = bytes.get(index + 1..index + 4).filter(|digits| {
bytes[index] == b'\\' && digits.iter().all(|d| (b'0'..=b'7').contains(d))
});
match octal {
Some(digits) => {
let value = digits
.iter()
.fold(0u32, |value, digit| value * 8 + u32::from(digit - b'0'));
decoded.push(value as u8);
index += 4;
}
None => {
decoded.push(bytes[index]);
index += 1;
}
}
}
PathBuf::from(std::ffi::OsStr::from_bytes(&decoded))
}
#[cfg(target_os = "linux")]
fn source_root_is_home_like(source_root: &Path, home: Option<&Path>) -> bool {
if home.is_some_and(|home| home.starts_with(source_root)) {
return true;
}
let names: Vec<&str> = source_root
.components()
.filter_map(|component| match component {
std::path::Component::Normal(name) => Some(name.to_str().unwrap_or("")),
_ => None,
})
.collect();
matches!(
names.as_slice(),
[] | ["root"]
| ["home"]
| ["home", _]
| ["Users"]
| ["Users", _]
| ["var", "home"]
| ["var", "home", _]
)
}
#[cfg(unix)]
pub fn directory_is_protected_alias(directory: &Path, home: &Path, volume: &Path) -> Option<bool> {
if protected_directory_alias(directory, home, volume)? {
return Some(true);
}
Some(directory_identity(directory.parent()?)? == directory_identity(volume)?)
}
#[cfg(unix)]
fn directory_identity(path: &Path) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.dev(), metadata.ino()))
}
#[cfg(unix)]
fn protected_directory_alias(directory: &Path, home: &Path, volume: &Path) -> Option<bool> {
let candidate = directory_identity(directory)?;
for ancestor in home.ancestors().chain(std::iter::once(volume)) {
if directory_identity(ancestor)? == candidate {
return Some(true);
}
}
Some(false)
}
#[cfg(not(unix))]
fn protected_directory_alias(_directory: &Path, _home: &Path, _volume: &Path) -> Option<bool> {
Some(false)
}
#[cfg(not(unix))]
pub fn directory_is_protected_alias(
_directory: &Path,
_home: &Path,
_volume: &Path,
) -> Option<bool> {
Some(false)
}
fn hash16(path: &Path) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(path.to_string_lossy().as_bytes());
let digest = format!("{:x}", hasher.finalize());
digest[..16].to_string()
}
pub fn lexical_normalize(path: &Path) -> PathBuf {
use std::path::Component;
let mut result = PathBuf::new();
for component in path.components() {
match component {
Component::ParentDir => match result.components().next_back() {
Some(Component::Normal(_)) => {
result.pop();
}
Some(Component::RootDir) => {}
Some(Component::Prefix(_)) if path.has_root() => {}
_ => result.push(component),
},
Component::CurDir => {}
other => result.push(other),
}
}
result
}
pub fn normalize_path(path: &Path) -> PathBuf {
#[cfg(windows)]
let path = &crate::windows_path::normalize_windows_path(path);
crate::path_identity::lexical_normalize(path)
}
pub fn canonicalize_normalized(path: &Path) -> PathBuf {
#[cfg(any(test, feature = "test-support"))]
CANONICALIZE_CALLS.with(|calls| {
if let Some(calls) = calls.borrow_mut().as_mut() {
calls.push(path.to_path_buf());
}
});
match std::fs::canonicalize(path) {
Ok(canonical) => normalize_path(&canonical),
Err(_) => normalize_path(path),
}
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static CANONICALIZE_CALLS: std::cell::RefCell<Option<Vec<PathBuf>>> = const { std::cell::RefCell::new(None) };
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn platform_temp_root_is_broad_but_tempdir_projects_are_narrow() {
let root = super::ProjectRootId::from_path(&std::env::temp_dir())
.unwrap()
.into_path_buf();
assert!(super::project_root_is_shared_temp(&root));
let project = tempfile::tempdir().unwrap();
let project = project.path().canonicalize().unwrap();
assert!(!super::project_root_is_shared_temp(&project));
assert_eq!(
super::project_root_is_narrow(&root, &project, root.ancestors().last().unwrap()),
Some(false)
);
}
#[cfg(unix)]
#[test]
fn named_shared_temp_roots_use_canonical_identities() {
for name in ["/tmp", "/var/tmp"] {
let root = super::ProjectRootId::from_path(std::path::Path::new(name))
.unwrap()
.into_path_buf();
assert!(super::project_root_is_shared_temp(&root), "{name}");
assert!(!super::project_root_is_shared_temp(
&root.join("my-scratch-project")
));
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_private_temp_forms_and_platform_temp_are_broad() {
for name in [
std::path::PathBuf::from("/private/tmp"),
std::path::PathBuf::from("/private/var/tmp"),
std::env::temp_dir(),
] {
let root = super::ProjectRootId::from_path(&name)
.unwrap()
.into_path_buf();
assert!(
super::project_root_is_shared_temp(&root),
"{}",
name.display()
);
assert_eq!(
super::project_root_is_narrow(&root, &root.join("home"), std::path::Path::new("/")),
Some(false)
);
assert!(!super::project_root_is_shared_temp(
&root.join("my-scratch-project")
));
}
}
#[cfg(windows)]
#[test]
fn windows_temp_root_uses_the_canonical_platform_identity() {
let temp = std::env::temp_dir();
let root = super::ProjectRootId::from_path(&temp)
.unwrap()
.into_path_buf();
assert!(super::project_root_is_shared_temp(&root));
assert!(!super::project_root_is_shared_temp(
&root.join("my-scratch-project")
));
}
#[test]
fn project_root_volume_children_are_not_permission_scopes() {
let volume = tempfile::tempdir().unwrap();
let volume = volume.path().canonicalize().unwrap();
let home = volume.join("users/person");
std::fs::create_dir_all(&home).unwrap();
for name in ["app", "workspace", "src", "code"] {
let project = volume.join(name);
std::fs::create_dir(&project).unwrap();
assert_eq!(
super::project_root_is_narrow(&project, &home, &volume),
Some(true),
"a project directly below a volume must stay enabled: {name}"
);
assert!(
!super::directory_scope_is_narrow(&project, &home, &volume),
"permission-card scopes must remain stricter than project roots"
);
#[cfg(unix)]
assert_eq!(
super::directory_is_protected_alias(&project, &home, &volume),
Some(true)
);
}
}
#[cfg(unix)]
#[test]
fn project_root_paths_allow_container_roots_but_not_protected_roots() {
let home = std::path::Path::new("/home/person");
let volume = std::path::Path::new("/");
for project in ["/app", "/workspace", "/src", "/code"] {
assert!(super::project_root_path_is_narrow(
std::path::Path::new(project),
home,
volume
));
}
for protected in ["/", "/home", "/home/person"] {
assert!(!super::project_root_path_is_narrow(
std::path::Path::new(protected),
home,
volume
));
}
let mounted_volume = std::path::Path::new("/Volumes/Work");
assert!(!super::project_root_path_is_narrow(
mounted_volume,
home,
mounted_volume
));
assert!(super::project_root_path_is_narrow(
std::path::Path::new("/Volumes/Work/app"),
home,
mounted_volume,
));
}
#[cfg(windows)]
#[test]
fn project_root_paths_allow_drive_children_but_not_protected_roots() {
let home = std::path::Path::new(r"C:\Users\person");
let volume = std::path::Path::new(r"C:\");
for project in [r"C:\app", r"C:\workspace", r"C:\src", r"C:\code"] {
assert!(super::project_root_path_is_narrow(
std::path::Path::new(project),
home,
volume
));
}
for protected in [volume, home, home.parent().unwrap()] {
assert!(!super::project_root_path_is_narrow(protected, home, volume));
}
}
#[test]
fn project_root_protected_directories_remain_disabled() {
let volume = tempfile::tempdir().unwrap();
let volume = volume.path().canonicalize().unwrap();
let home = volume.join("users/person");
std::fs::create_dir_all(&home).unwrap();
for root in [
&volume,
&home,
home.parent().unwrap(),
volume.ancestors().last().unwrap(),
] {
assert_eq!(
super::project_root_is_narrow(root, &home, &volume),
Some(false)
);
}
}
#[cfg(unix)]
#[test]
fn project_root_unknown_identity_is_not_admitted() {
let volume = tempfile::tempdir().unwrap();
let volume = volume.path().canonicalize().unwrap();
let home = volume.join("users/person");
std::fs::create_dir_all(&home).unwrap();
let missing = volume.join("missing/project");
assert_eq!(
super::project_root_is_narrow(&missing, &home, &volume),
None
);
}
#[cfg(unix)]
#[test]
fn project_root_protected_aliases_remain_disabled() {
let volume = tempfile::tempdir().unwrap();
let volume = volume.path().canonicalize().unwrap();
let home = volume.join("users/person");
std::fs::create_dir_all(&home).unwrap();
for (name, target) in [
("app", home.as_path()),
("workspace", home.parent().unwrap()),
("code", volume.as_path()),
] {
let alias = volume.join(name);
std::os::unix::fs::symlink(target, &alias).unwrap();
assert!(super::project_root_path_is_narrow(&alias, &home, &volume));
assert_eq!(
super::project_root_is_narrow(&alias, &home, &volume),
Some(false)
);
}
}
#[cfg(target_os = "linux")]
mod mount_table {
use super::super::mount_root_in;
use super::super::project_root_is_shared_temp;
use super::super::project_root_path_is_narrow;
use super::super::project_root_volume_with;
use super::super::MountRoot;
use std::path::Path;
use std::path::PathBuf;
const OVERLAY_ROOT: &str = "1748 1 0:173 / / rw,relatime master:1 - overlay overlay rw,lowerdir=/l,upperdir=/u,workdir=/w\n";
fn narrow_with(root: &str, read: impl FnOnce() -> std::io::Result<Vec<u8>>) -> bool {
let root = Path::new(root);
let home = Path::new("/root");
let volume =
project_root_volume_with(root, root.to_path_buf(), Some(home), read, |_| {
Some(PathBuf::from("/"))
});
volume.is_some_and(|volume| {
project_root_path_is_narrow(root, home, &volume)
&& !project_root_is_shared_temp(root)
})
}
#[test]
fn shared_temp_roots_are_broad_on_bind_and_tmpfs_mounts() {
for root in ["/tmp", "/var/tmp"] {
assert!(!narrow(
root,
&format!("1801 1748 8:1 /tmp {root} rw - ext4 /dev/sda1 rw")
));
assert!(!narrow(
root,
&format!("1801 1748 0:45 / {root} rw - tmpfs tmpfs rw")
));
assert!(narrow(&format!("{root}/my-scratch-project"), &format!("1801 1748 8:1 /tmp/project {root}/my-scratch-project rw - ext4 /dev/sda1 rw")));
}
}
fn narrow(root: &str, mount: &str) -> bool {
narrow_with(root, || Ok(format!("{OVERLAY_ROOT}{mount}\n").into_bytes()))
}
#[test]
fn bind_of_a_subdirectory_is_narrow() {
assert!(narrow(
"/proj",
"1801 1748 8:1 /tmp/repro/proj-x /proj ro,relatime - ext4 /dev/sda1 rw"
));
assert!(narrow(
"/data",
"1801 1748 8:1 /tmp/repro /data ro,relatime shared:5 master:1 - ext4 /dev/sda1 rw"
));
assert!(narrow(
"/workspace",
"1801 1748 8:1 /var/lib/docker/volumes/x/_data /workspace rw - ext4 /dev/sda1 rw"
));
assert!(narrow(
"/work space",
"1801 1748 8:1 /srv/my\\040proj /work\\040space rw - xfs /dev/sda1 rw"
));
}
#[test]
fn whole_filesystem_mount_is_broad() {
let mount = "1801 1748 8:17 / /data rw,relatime shared:5 - ext4 /dev/sdb1 rw";
assert!(!narrow("/data", mount));
assert_eq!(
mount_root_in(mount.as_bytes(), Path::new("/data")),
MountRoot::WholeVolume
);
}
#[test]
fn mount_on_top_of_a_bind_decides() {
assert!(!narrow(
"/data",
"1801 1748 8:1 /tmp/repro /data rw - ext4 /dev/sda1 rw\n\
1802 1801 8:17 / /data rw - ext4 /dev/sdb1 rw"
));
}
#[test]
fn btrfs_subvolume_root_is_broad() {
assert!(!narrow(
"/data",
"1801 1748 0:45 /@data /data rw,relatime shared:5 - btrfs /dev/sdb2 rw,space_cache=v2,subvolid=257,subvol=/@data"
));
assert!(!narrow(
"/data",
"1801 1748 0:45 /@data /data rw - btrfs /dev/sdb2 rw,space_cache=v2"
));
assert!(!narrow(
"/data",
"1801 1748 0:45 /@other /data rw - btrfs /dev/sdb2 rw,subvolid=257,subvol=/@data"
));
assert!(narrow(
"/data",
"1801 1748 0:45 /@data/proj /data rw - btrfs /dev/sdb2 rw,subvolid=257,subvol=/@data"
));
}
#[test]
fn bind_of_a_home_folder_is_broad() {
for source in ["/home/u", "/home", "/Users/u", "/root", "/var/home/u"] {
assert!(
!narrow(
"/workspace",
&format!("1801 1748 8:1 {source} /workspace rw - ext4 /dev/sda1 rw")
),
"{source}"
);
}
let home = Path::new("/srv/people/u");
for source in ["/srv/people/u", "/srv/people", "/srv"] {
let root = Path::new("/workspace");
let volume = project_root_volume_with(
root,
root.to_path_buf(),
Some(home),
|| {
Ok(format!(
"{OVERLAY_ROOT}1801 1748 8:1 {source} /workspace rw - ext4 /dev/sda1 rw\n"
)
.into_bytes())
},
|_| Some(PathBuf::from("/")),
);
assert_eq!(volume.as_deref(), Some(root), "{source}");
}
}
#[test]
fn filesystem_root_is_broad() {
assert!(!narrow_with("/", || Ok(
b"1748 317 9:5 /runner/sandboxes/x/root / ro - xfs /dev/md5 rw\n".to_vec()
)));
}
#[test]
fn non_utf8_mount_names_do_not_hide_a_bind() {
let table = [
OVERLAY_ROOT.as_bytes(),
b"1802 1748 8:1 /srv/caf\xe9 /mnt/caf\xe9 rw - ext4 /dev/sda1 rw\n",
b"1801 1748 8:1 /tmp/repro/proj-x /workspace rw - ext4 /dev/sda1 rw\n",
]
.concat();
assert!(narrow_with("/workspace", || Ok(table)));
}
#[test]
fn non_utf8_mount_point_matches_its_entry() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let root = Path::new(OsStr::from_bytes(b"/caf\xe9"));
let table = [
OVERLAY_ROOT.as_bytes(),
b"1801 1748 8:1 /srv/proj\xff /caf\xe9 rw - ext4 /dev/sda1 rw\n",
]
.concat();
assert_eq!(
mount_root_in(&table, root),
MountRoot::Subdirectory(PathBuf::from(OsStr::from_bytes(b"/srv/proj\xff")))
);
let volume = project_root_volume_with(
root,
root.to_path_buf(),
Some(Path::new("/root")),
|| Ok(table.clone()),
|_| Some(PathBuf::from("/")),
);
assert_eq!(volume, Some(PathBuf::from("/")));
}
#[test]
fn unreadable_mount_table_keeps_the_device_answer() {
assert!(!narrow_with("/proj", || Err(std::io::Error::other(
"permission denied"
))));
assert!(!narrow(
"/proj",
"1801 1748 8:1 /tmp/repro/proj-x /elsewhere rw - ext4 /dev/sda1 rw"
));
}
#[test]
fn root_below_its_mount_point_keeps_its_volume() {
let volume = project_root_volume_with(
Path::new("/data/proj"),
PathBuf::from("/data"),
None,
|| panic!("the mount table is only read for a mount point root"),
|_| panic!("no re-anchoring below a mount point"),
);
assert_eq!(volume, Some(PathBuf::from("/data")));
}
}
#[test]
fn lexical_normalization_preserves_parents_and_root_boundaries() {
for (input, expected) in [
("../../x", "../../x"),
("../a/../../x", "../../x"),
("a/../b", "b"),
("a/../../x", "../x"),
] {
assert_eq!(lexical_normalize(Path::new(input)), Path::new(expected));
}
#[cfg(unix)]
assert_eq!(lexical_normalize(Path::new("/../../x")), Path::new("/x"));
}
#[cfg(windows)]
#[test]
fn lexical_normalization_preserves_drive_relative_parents() {
assert_eq!(
lexical_normalize(Path::new(r"C:..\..\x")),
Path::new(r"C:..\..\x")
);
assert_eq!(
lexical_normalize(Path::new(r"C:\..\..\x")),
Path::new(r"C:\x")
);
}
fn temp_root(label: &str) -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::Builder::new()
.prefix(&format!("aft-path-identity-{label}-"))
.tempdir()
.expect("create temp root");
let path = dir.path().to_path_buf();
(dir, path)
}
#[test]
fn scope_key_is_stable_and_16_hex() {
let (_root_dir, root) = temp_root("stable");
let a = project_scope_key(&root);
let b = project_scope_key(&root);
assert_eq!(a, b);
assert_eq!(a.len(), 16);
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn scope_key_distinguishes_distinct_roots() {
let (_a_dir, a) = temp_root("root-a");
let (_b_dir, b) = temp_root("root-b");
assert_ne!(project_scope_key(&a), project_scope_key(&b));
}
#[test]
fn scope_key_canonicalizes_equivalent_spellings() {
let (_root_dir, root) = temp_root("spelling");
let nested = root.join("nested");
fs::create_dir_all(&nested).expect("create nested");
assert_eq!(
project_scope_key(&root),
project_scope_key(&nested.join("..")),
);
assert_eq!(project_scope_key(&root), project_scope_key(&root.join(".")));
}
#[test]
fn scope_key_total_on_non_existent_root() {
let missing = std::env::temp_dir().join("aft-path-identity-definitely-missing-xyz/sub/..");
let key = project_scope_key(&missing);
assert_eq!(key.len(), 16);
}
}
#[cfg(test)]
mod comparison_tests {
#[test]
fn comparison_adapter_preserves_relative_parent_components() {
for (input, expected) in [("../../x", "../../x"), ("a/../../x", "../x")] {
assert_eq!(
super::normalize_path(std::path::Path::new(input)),
std::path::PathBuf::from(expected),
"{input}"
);
}
}
}