use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime};
use fallow_engine::changed_files::clear_ambient_git_env;
use rustc_hash::FxHashSet;
use xxhash_rust::xxh3::xxh3_64;
use crate::report::plural;
pub struct BaseWorktree {
path: PathBuf,
persistent: bool,
}
impl BaseWorktree {
pub fn create(repo_root: &Path, base_ref: &str, base_sha: Option<&str>) -> Option<Self> {
sweep_orphan_audit_worktrees(repo_root);
if let Some(base_sha) = base_sha
&& let Some(worktree) = Self::reuse_or_create(repo_root, base_sha)
{
return Some(worktree);
}
let path = non_reusable_worktree_path()?;
let mut guard = WorktreeCleanupGuard::new(repo_root, &path);
if let Err(error) = fallow_engine::repo_refs::create_detached_base_worktree(
repo_root,
guard.path(),
base_ref,
) {
tracing::debug!(
base_ref,
error = %error,
"could not materialize non-reusable audit base worktree",
);
return None;
}
unregister_worktree(guard.path());
guard.defuse();
drop(guard);
let worktree = Self {
path,
persistent: false,
};
materialize_base_dependency_context(repo_root, worktree.path());
Some(worktree)
}
pub fn reuse_or_create(repo_root: &Path, base_sha: &str) -> Option<Self> {
let path = reusable_audit_worktree_path(repo_root, base_sha);
let _lock = ReusableWorktreeLock::try_acquire(&path)?;
if reusable_audit_worktree_is_ready(&path, base_sha)
|| try_migrate_legacy_reusable_cache(repo_root, &path, base_sha)
{
let worktree = Self {
path,
persistent: true,
};
materialize_base_dependency_context(repo_root, worktree.path());
touch_last_used(worktree.path());
return Some(worktree);
}
if audit_worktree_is_registered(repo_root, &path) {
remove_audit_worktree(repo_root, &path);
}
let _ = std::fs::remove_dir_all(&path);
let mut guard = WorktreeCleanupGuard::new(repo_root, &path);
if let Err(error) = fallow_engine::repo_refs::create_detached_base_worktree(
repo_root,
guard.path(),
base_sha,
) {
tracing::debug!(
base_sha,
error = %error,
"could not materialize reusable audit base worktree",
);
return None;
}
unregister_worktree(guard.path());
guard.defuse();
drop(guard);
write_reusable_sha(&path, base_sha);
let worktree = Self {
path,
persistent: true,
};
materialize_base_dependency_context(repo_root, worktree.path());
touch_last_used(worktree.path());
Some(worktree)
}
pub fn path(&self) -> &Path {
&self.path
}
}
fn non_reusable_worktree_path() -> Option<PathBuf> {
static SEQ: AtomicU64 = AtomicU64::new(0);
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let nanos = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.ok()?
.as_nanos();
Some(std::env::temp_dir().join(format!(
"fallow-audit-base-{}-{nanos}-{seq}",
std::process::id()
)))
}
pub struct WorktreeCleanupGuard<'a> {
repo_root: PathBuf,
path: &'a Path,
armed: bool,
}
impl<'a> WorktreeCleanupGuard<'a> {
pub fn new(repo_root: &Path, path: &'a Path) -> Self {
Self {
repo_root: repo_root.to_path_buf(),
path,
armed: true,
}
}
pub fn path(&self) -> &Path {
self.path
}
pub fn defuse(&mut self) {
self.armed = false;
}
}
impl Drop for WorktreeCleanupGuard<'_> {
fn drop(&mut self) {
if self.armed {
remove_audit_worktree(&self.repo_root, self.path);
let _ = std::fs::remove_dir_all(self.path);
}
}
}
pub struct ReusableWorktreeLock {
_file: std::fs::File,
}
impl ReusableWorktreeLock {
pub fn try_acquire(reusable_path: &Path) -> Option<Self> {
let lock_path = reusable_worktree_lock_path(reusable_path);
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&lock_path)
.ok()?;
match file.try_lock() {
Ok(()) => Some(Self { _file: file }),
Err(std::fs::TryLockError::WouldBlock) => {
tracing::debug!(
path = %lock_path.display(),
"reusable audit worktree lock contended; falling back to non-reusable worktree",
);
None
}
Err(std::fs::TryLockError::Error(err)) => {
tracing::debug!(
path = %lock_path.display(),
error = %err,
"could not acquire reusable audit worktree lock; falling back to non-reusable worktree",
);
None
}
}
}
}
pub fn reusable_worktree_lock_path(reusable_path: &Path) -> PathBuf {
sidecar_path(reusable_path, REUSABLE_LOCK_SUFFIX)
}
fn sidecar_path(reusable_path: &Path, suffix: &str) -> PathBuf {
let mut name = reusable_path
.file_name()
.map(std::ffi::OsString::from)
.unwrap_or_default();
name.push(suffix);
reusable_path
.parent()
.map_or_else(|| PathBuf::from(&name), |parent| parent.join(&name))
}
pub fn reusable_worktree_sha_path(reusable_path: &Path) -> PathBuf {
sidecar_path(reusable_path, REUSABLE_SHA_SUFFIX)
}
fn write_reusable_sha(reusable_path: &Path, base_sha: &str) {
let sha_path = reusable_worktree_sha_path(reusable_path);
if let Err(err) = std::fs::write(&sha_path, format!("{base_sha}\n")) {
tracing::debug!(
path = %sha_path.display(),
error = %err,
"failed to write reusable audit worktree .sha sidecar; next run will rebuild",
);
}
}
const DEFAULT_AUDIT_CACHE_MAX_AGE_DAYS: u32 = 30;
const AUDIT_CACHE_MAX_AGE_ENV: &str = "FALLOW_AUDIT_CACHE_MAX_AGE_DAYS";
const REUSABLE_LAST_USED_SUFFIX: &str = ".last-used";
const REUSABLE_SHA_SUFFIX: &str = ".sha";
const REUSABLE_LOCK_SUFFIX: &str = ".lock";
const UNREGISTERED_GITDIR_STUB: &str = "gitdir: fallow-audit-unregistered\n";
pub fn reusable_worktree_last_used_path(reusable_path: &Path) -> PathBuf {
sidecar_path(reusable_path, REUSABLE_LAST_USED_SUFFIX)
}
pub fn touch_last_used(reusable_path: &Path) {
let last_used = reusable_worktree_last_used_path(reusable_path);
let result = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&last_used)
.and_then(|file| file.set_modified(SystemTime::now()));
if let Err(err) = result {
tracing::warn!(
path = %last_used.display(),
error = %err,
"failed to touch reusable audit worktree sidecar; staleness signal may not update",
);
}
}
pub fn resolve_cache_max_age_with_options(
root: &Path,
config_path: Option<&PathBuf>,
allow_remote_extends: bool,
) -> Option<Duration> {
if let Ok(raw) = std::env::var(AUDIT_CACHE_MAX_AGE_ENV) {
if let Ok(days) = raw.trim().parse::<u32>() {
return days_to_duration(days);
}
tracing::debug!(
value = %raw,
"FALLOW_AUDIT_CACHE_MAX_AGE_DAYS is not a valid u32; falling back to config/default",
);
}
if let Some(days) = load_audit_config(root, config_path, allow_remote_extends)
.and_then(|c| c.cache_max_age_days)
{
return days_to_duration(days);
}
days_to_duration(DEFAULT_AUDIT_CACHE_MAX_AGE_DAYS)
}
pub fn days_to_duration(days: u32) -> Option<Duration> {
if days == 0 {
return None;
}
Some(Duration::from_secs(u64::from(days) * 86_400))
}
fn load_audit_config(
root: &Path,
config_path: Option<&PathBuf>,
allow_remote_extends: bool,
) -> Option<fallow_config::AuditConfig> {
let options = fallow_config::ConfigLoadOptions {
allow_remote_extends,
};
if let Some(path) = config_path {
return fallow_config::FallowConfig::load_with_options(path, options)
.ok()
.map(|config| config.audit);
}
fallow_config::FallowConfig::find_and_load_with_options(root, options)
.ok()
.flatten()
.map(|(config, _path)| config.audit)
}
pub fn sweep_old_reusable_caches(repo_root: &Path, max_age: Option<Duration>, quiet: bool) {
if deregister_legacy_reusable_caches(repo_root) {
let mut command = Command::new("git");
command
.args(["worktree", "prune", "--expire=now"])
.current_dir(repo_root);
clear_ambient_git_env(&mut command);
let _ = command.output();
}
let prefix = reusable_cache_repo_prefix(repo_root);
let now = SystemTime::now();
let mut removed: u32 = 0;
for path in scan_reusable_cache_paths(&prefix) {
if reclaim_reusable_cache_entry(&path, max_age, now) {
removed += 1;
}
}
if removed == 0 {
return;
}
tracing::info!(
count = removed,
"reclaimed stale audit base-snapshot caches",
);
if !quiet {
let s = plural(removed as usize);
let _ = writeln!(
std::io::stderr(),
"fallow: reclaimed {removed} stale base-snapshot cache{s}",
);
}
}
fn deregister_legacy_reusable_caches(repo_root: &Path) -> bool {
let Some(worktrees) = list_audit_worktrees(repo_root) else {
return false;
};
let mut deregistered = false;
for path in worktrees {
if !is_reusable_audit_worktree_path(&path) {
continue;
}
let Some(_lock) = ReusableWorktreeLock::try_acquire(&path) else {
continue;
};
if !audit_worktree_is_registered(repo_root, &path) {
continue;
}
seed_legacy_reusable_sha(&path);
unregister_worktree(&path);
deregistered = true;
}
deregistered
}
fn seed_legacy_reusable_sha(path: &Path) {
if reusable_worktree_sha_path(path).exists()
|| !fallow_engine::repo_refs::detached_base_worktree_is_raw_materialized(path)
{
return;
}
if let Some(head) = git_rev_parse(path, "HEAD") {
write_reusable_sha(path, &head);
}
}
fn scan_reusable_cache_paths(prefix: &str) -> Vec<PathBuf> {
let temp = std::env::temp_dir();
let Ok(entries) = std::fs::read_dir(&temp) else {
return Vec::new();
};
let mut seen: FxHashSet<PathBuf> = FxHashSet::default();
let mut paths = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
if !name.starts_with(prefix) {
continue;
}
let path = temp.join(strip_cache_sidecar_suffix(name));
if seen.insert(path.clone()) {
paths.push(path);
}
}
paths
}
fn strip_cache_sidecar_suffix(name: &str) -> &str {
for suffix in [
REUSABLE_LAST_USED_SUFFIX,
REUSABLE_SHA_SUFFIX,
REUSABLE_LOCK_SUFFIX,
] {
if let Some(stripped) = name.strip_suffix(suffix) {
return stripped;
}
}
name
}
fn reclaim_reusable_cache_entry(path: &Path, max_age: Option<Duration>, now: SystemTime) -> bool {
if !path.exists() {
return reclaim_orphan_cache_entry(path);
}
let Some(max_age) = max_age else {
return false;
};
reclaim_aged_cache_entry(path, max_age, now)
}
fn reclaim_orphan_cache_entry(path: &Path) -> bool {
let Some(_lock) = ReusableWorktreeLock::try_acquire(path) else {
return false;
};
if path.exists() {
return false;
}
let last_used = reusable_worktree_last_used_path(path);
let sha = reusable_worktree_sha_path(path);
if !last_used.exists() && !sha.exists() {
return false;
}
let _ = std::fs::remove_file(&last_used);
let _ = std::fs::remove_file(&sha);
true
}
fn reclaim_aged_cache_entry(path: &Path, max_age: Duration, now: SystemTime) -> bool {
let sidecar = reusable_worktree_last_used_path(path);
let sidecar_mtime = std::fs::metadata(&sidecar)
.ok()
.and_then(|m| m.modified().ok());
let Some(mtime) = sidecar_mtime else {
touch_last_used(path);
return false;
};
let Ok(age) = now.duration_since(mtime) else {
return false;
};
if age < max_age {
return false;
}
let Some(_lock) = ReusableWorktreeLock::try_acquire(path) else {
return false;
};
let dir_removed = match std::fs::remove_dir_all(path) {
Ok(()) => true,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
Err(err) => {
tracing::warn!(
path = %path.display(),
error = %err,
"failed to remove stale reusable audit worktree directory; entry may leak",
);
false
}
};
let _ = std::fs::remove_file(&sidecar);
let _ = std::fs::remove_file(reusable_worktree_sha_path(path));
dir_removed
}
fn reusable_cache_repo_prefix(repo_root: &Path) -> String {
let repo_root = git_toplevel(repo_root).unwrap_or_else(|| repo_root.to_path_buf());
let repo_root = dunce::canonicalize(&repo_root).unwrap_or(repo_root);
let repo_hash = xxh3_64(repo_root.to_string_lossy().as_bytes());
format!("fallow-audit-base-cache-{repo_hash:016x}-")
}
pub fn reusable_audit_worktree_path(repo_root: &Path, base_sha: &str) -> PathBuf {
let sha_prefix = base_sha.get(..16).unwrap_or(base_sha);
std::env::temp_dir().join(format!(
"{}{sha_prefix}",
reusable_cache_repo_prefix(repo_root)
))
}
fn reusable_audit_worktree_is_ready(path: &Path, base_sha: &str) -> bool {
if !path.exists() {
return false;
}
let recorded = std::fs::read_to_string(reusable_worktree_sha_path(path))
.ok()
.map(|contents| contents.trim().to_owned());
if recorded.as_deref() != Some(base_sha) {
return false;
}
repair_unregistered_git_stub(path);
true
}
fn try_migrate_legacy_reusable_cache(repo_root: &Path, path: &Path, base_sha: &str) -> bool {
if !path.exists() || !audit_worktree_is_registered(repo_root, path) {
return false;
}
let head_matches = git_rev_parse(path, "HEAD").is_some_and(|head| head == base_sha);
if !head_matches || !fallow_engine::repo_refs::detached_base_worktree_is_raw_materialized(path)
{
return false;
}
write_reusable_sha(path, base_sha);
unregister_worktree(path);
true
}
pub fn unregister_worktree(path: &Path) {
let gitfile = path.join(".git");
if let Ok(contents) = std::fs::read_to_string(&gitfile)
&& let Some(admin_dir) = parse_worktree_gitdir(&contents)
&& is_fallow_admin_dir(&admin_dir)
{
let _ = std::fs::remove_dir_all(&admin_dir);
}
let _ = std::fs::write(&gitfile, UNREGISTERED_GITDIR_STUB);
}
fn repair_unregistered_git_stub(path: &Path) {
let gitfile = path.join(".git");
match std::fs::read_to_string(&gitfile) {
Ok(contents) => {
if parse_worktree_gitdir(&contents).is_some_and(|admin| is_fallow_admin_dir(&admin)) {
unregister_worktree(path);
}
}
Err(_) => {
let _ = std::fs::write(&gitfile, UNREGISTERED_GITDIR_STUB);
}
}
}
fn parse_worktree_gitdir(contents: &str) -> Option<PathBuf> {
contents
.lines()
.find_map(|line| line.trim().strip_prefix("gitdir:"))
.map(|rest| PathBuf::from(rest.trim()))
}
fn is_fallow_admin_dir(admin_dir: &Path) -> bool {
admin_dir
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("fallow-audit-base-"))
}
pub fn git_rev_parse(root: &Path, rev: &str) -> Option<String> {
let mut command = Command::new("git");
command.args(["rev-parse", rev]).current_dir(root);
clear_ambient_git_env(&mut command);
let output = command.output().ok()?;
if !output.status.success() {
return None;
}
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
pub fn git_toplevel(root: &Path) -> Option<PathBuf> {
let mut command = Command::new("git");
command
.args(["rev-parse", "--show-toplevel"])
.current_dir(root);
clear_ambient_git_env(&mut command);
let output = command.output().ok()?;
if !output.status.success() {
return None;
}
let path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
Some(dunce::canonicalize(&path).unwrap_or(path))
}
fn audit_worktree_is_registered(repo_root: &Path, path: &Path) -> bool {
let Some(worktrees) = list_audit_worktrees(repo_root) else {
return false;
};
worktrees.iter().any(|worktree| paths_equal(worktree, path))
}
pub fn paths_equal(left: &Path, right: &Path) -> bool {
if left == right {
return true;
}
match (dunce::canonicalize(left), dunce::canonicalize(right)) {
(Ok(left), Ok(right)) => left == right,
_ => false,
}
}
const MATERIALIZED_CONTEXT_DIRS: &[&str] = &["node_modules", ".nuxt", ".astro"];
pub fn materialize_base_dependency_context(repo_root: &Path, worktree_path: &Path) {
for &name in MATERIALIZED_CONTEXT_DIRS {
let source = repo_root.join(name);
if !source.is_dir() {
continue;
}
let destination = worktree_path.join(name);
if destination.is_dir() {
continue;
}
if let Ok(metadata) = std::fs::symlink_metadata(&destination) {
if !metadata.file_type().is_symlink() {
continue;
}
let _ = std::fs::remove_file(&destination);
}
let _ = symlink_dependency_dir(&source, &destination);
}
}
#[cfg(unix)]
fn symlink_dependency_dir(source: &Path, destination: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(source, destination)
}
#[cfg(windows)]
fn symlink_dependency_dir(source: &Path, destination: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_dir(source, destination)
}
pub fn remove_audit_worktree(repo_root: &Path, path: &Path) {
let mut command = Command::new("git");
command
.args([
"worktree",
"remove",
"--force",
path.to_string_lossy().as_ref(),
])
.current_dir(repo_root);
clear_ambient_git_env(&mut command);
match crate::signal::scoped_child::output(&mut command) {
Ok(output) => {
if !output.status.success() && path.exists() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!(
path = %path.display(),
stderr = %stderr.trim(),
"git worktree remove failed; the directory remains and may leak",
);
}
}
Err(err) => {
tracing::warn!(
path = %path.display(),
error = %err,
"git worktree remove subprocess failed to spawn",
);
}
}
}
pub fn sweep_orphan_audit_worktrees(repo_root: &Path) {
sweep_orphan_audit_worktrees_in(repo_root, &std::env::temp_dir());
}
pub fn sweep_orphan_audit_worktrees_in(repo_root: &Path, temp_root: &Path) {
if deregister_legacy_orphan_worktrees(repo_root) {
let mut command = Command::new("git");
command
.args(["worktree", "prune", "--expire=now"])
.current_dir(repo_root);
clear_ambient_git_env(&mut command);
let _ = command.output();
}
for path in scan_non_reusable_orphan_paths(temp_root) {
let _ = std::fs::remove_dir_all(&path);
}
}
fn deregister_legacy_orphan_worktrees(repo_root: &Path) -> bool {
let Some(worktrees) = list_audit_worktrees(repo_root) else {
return false;
};
let mut removed_any = false;
for path in worktrees {
if !is_fallow_audit_worktree_path(&path)
|| is_reusable_audit_worktree_path(&path)
|| audit_worktree_process_is_alive(&path)
{
continue;
}
remove_audit_worktree(repo_root, &path);
let _ = std::fs::remove_dir_all(&path);
removed_any = true;
}
removed_any
}
fn scan_non_reusable_orphan_paths(temp: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(temp) else {
return Vec::new();
};
let mut paths = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
let Some(pid) = audit_worktree_pid(name) else {
continue;
};
if process_is_alive(pid) || !entry.path().is_dir() {
continue;
}
paths.push(temp.join(name));
}
paths
}
pub fn list_audit_worktrees(repo_root: &Path) -> Option<Vec<PathBuf>> {
let mut command = Command::new("git");
command
.args(["worktree", "list", "--porcelain"])
.current_dir(repo_root);
clear_ambient_git_env(&mut command);
let output = command.output().ok()?;
if !output.status.success() {
return None;
}
Some(parse_worktree_list(&String::from_utf8_lossy(
&output.stdout,
)))
}
pub fn parse_worktree_list(output: &str) -> Vec<PathBuf> {
output
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.map(PathBuf::from)
.filter(|path| is_fallow_audit_worktree_path(path))
.collect()
}
pub fn is_fallow_audit_worktree_path(path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
return false;
};
name.starts_with("fallow-audit-base-") && path_is_inside_temp_dir(path)
}
pub fn is_reusable_audit_worktree_path(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("fallow-audit-base-cache-"))
}
fn path_is_inside_temp_dir(path: &Path) -> bool {
let temp = std::env::temp_dir();
let simple_path = dunce::simplified(path);
let simple_temp = dunce::simplified(&temp);
if simple_path.starts_with(simple_temp) {
return true;
}
let Ok(canonical_temp) = std::fs::canonicalize(&temp) else {
return false;
};
let simple_canonical_temp = dunce::simplified(&canonical_temp);
simple_path.starts_with(simple_canonical_temp)
|| std::fs::canonicalize(path).is_ok_and(|canonical_path| {
dunce::simplified(&canonical_path).starts_with(simple_canonical_temp)
})
}
fn audit_worktree_process_is_alive(path: &Path) -> bool {
let Some(pid) = path
.file_name()
.and_then(|name| name.to_str())
.and_then(audit_worktree_pid)
else {
return false;
};
process_is_alive(pid)
}
pub fn audit_worktree_pid(name: &str) -> Option<u32> {
name.strip_prefix("fallow-audit-base-")?
.split('-')
.next()?
.parse()
.ok()
}
#[cfg(unix)]
pub fn process_is_alive(pid: u32) -> bool {
Command::new("kill")
.args(["-0", &pid.to_string()])
.output()
.is_ok_and(|output| output.status.success())
}
#[cfg(windows)]
pub fn process_is_alive(pid: u32) -> bool {
windows_process::is_alive(pid)
}
#[cfg(not(any(unix, windows)))]
pub fn process_is_alive(_pid: u32) -> bool {
true
}
#[cfg(windows)]
#[allow(
unsafe_code,
reason = "Win32 process-query API (OpenProcess / WaitForSingleObject / CloseHandle / GetLastError) requires unsafe FFI"
)]
mod windows_process {
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, GetLastError, HANDLE,
WAIT_OBJECT_0,
};
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, WaitForSingleObject,
};
struct ProcessHandle(HANDLE);
impl Drop for ProcessHandle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
pub fn is_alive(pid: u32) -> bool {
let raw = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if raw.is_null() {
let err = unsafe { GetLastError() };
#[expect(
clippy::match_same_arms,
reason = "named arm documents the cross-session case"
)]
return match err {
ERROR_INVALID_PARAMETER => false,
ERROR_ACCESS_DENIED => true,
_ => true,
};
}
let handle = ProcessHandle(raw);
let wait_result = unsafe { WaitForSingleObject(handle.0, 0) };
wait_result != WAIT_OBJECT_0
}
}
impl Drop for BaseWorktree {
fn drop(&mut self) {
if self.persistent {
return;
}
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_reusable_worktree_paths_are_unique_under_concurrency() {
const N: usize = 64;
let barrier = std::sync::Barrier::new(N);
let paths = std::sync::Mutex::new(Vec::with_capacity(N));
std::thread::scope(|s| {
for _ in 0..N {
let barrier = &barrier;
let paths = &paths;
s.spawn(move || {
barrier.wait();
let path = non_reusable_worktree_path().expect("path should build");
paths.lock().unwrap().push(path);
});
}
});
let mut paths = paths.into_inner().unwrap();
assert_eq!(paths.len(), N);
paths.sort();
paths.dedup();
assert_eq!(paths.len(), N, "non-reusable worktree paths collided");
}
#[test]
fn non_reusable_worktree_path_pid_is_parseable() {
let path = non_reusable_worktree_path().expect("path should build");
let name = path.file_name().unwrap().to_str().unwrap();
assert!(is_fallow_audit_worktree_path(&path));
assert!(!is_reusable_audit_worktree_path(&path));
assert_eq!(audit_worktree_pid(name), Some(std::process::id()));
}
}