mod dangling;
mod github;
mod report;
#[cfg(test)]
mod tests;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use rayon::prelude::*;
pub use report::{document, render_human, render_json};
pub const SCHEMA_VERSION: u32 = 1;
const BUILD_OUTPUT_DIRS: &[&str] = &["dist", "build", "target", "out", "node_modules", "__pycache__"];
const UNAMBIGUOUS_BUILD_OUTPUT_DIRS: &[&str] = &["dist", "target", "node_modules", "__pycache__"];
const DEFAULT_BRANCH_FALLBACKS: &[&str] = &[
"refs/remotes/origin/main",
"refs/remotes/origin/master",
"refs/heads/main",
"refs/heads/master",
];
#[derive(Debug, Clone, Copy, Default)]
pub struct WorktreeOptions {
pub dry_run: bool,
pub stale_after: Option<Duration>,
pub github_merged: bool,
pub aggressive: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum State {
Main,
Locked,
Current,
Missing,
NotMerged,
OutsideRoot,
LocalChanges {
changed: usize,
},
Discarded,
Merged {
discarded: usize,
},
Stale {
discarded: usize,
},
Unchecked(String),
HeadDiffers {
pull: u64,
},
Dangling {
gitdir: PathBuf,
bytes: u64,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Removed,
WouldRemove,
Failed(String),
}
#[derive(Debug, Clone)]
pub struct Worktree {
pub path: PathBuf,
pub branch: Option<String>,
pub state: State,
pub outcome: Option<Outcome>,
}
#[derive(Debug, Clone)]
pub struct RepositoryWorktrees {
pub repository: PathBuf,
pub default_branch: Option<String>,
pub worktrees: Vec<Worktree>,
pub error: Option<String>,
}
#[derive(Debug)]
pub struct WorktreePruneResult {
pub repositories: Vec<RepositoryWorktrees>,
pub dry_run: bool,
pub elapsed: Duration,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Totals {
pub removed: usize,
pub local_changes: usize,
pub kept: usize,
pub failed: usize,
pub dangling: usize,
}
impl WorktreePruneResult {
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals::default();
for worktree in self.repositories.iter().flat_map(|repository| &repository.worktrees) {
match (&worktree.state, &worktree.outcome) {
(_, Some(Outcome::Removed | Outcome::WouldRemove)) => {
totals.removed += 1;
}
(_, Some(Outcome::Failed(_))) => totals.failed += 1,
(State::LocalChanges { .. }, _) => totals.local_changes += 1,
(State::Dangling { .. }, _) => totals.dangling += 1,
_ => totals.kept += 1,
}
}
totals
}
#[must_use]
pub fn exit_code(&self) -> i32 {
if self.totals().failed > 0 {
crate::report::exit::REMOVAL_FAILED
} else {
crate::report::exit::SUCCESS
}
}
}
#[must_use]
pub fn prune(work_trees: &[PathBuf], roots: &[PathBuf], options: WorktreeOptions) -> WorktreePruneResult {
let started = Instant::now();
let current = std::env::current_dir().ok().and_then(|cwd| cwd.canonicalize().ok());
let roots: Vec<PathBuf> = roots.iter().filter_map(|root| root.canonicalize().ok()).collect();
let mut seen = std::collections::BTreeSet::new();
let mut orphans = Vec::new();
let repositories: Vec<PathBuf> = work_trees
.iter()
.filter_map(|work_tree| {
let Some(common) = git(work_tree, &["rev-parse", "--path-format=absolute", "--git-common-dir"]) else {
orphans.extend(dangling::orphan(work_tree).map(|orphan| (work_tree.clone(), orphan)));
return None;
};
seen.insert(PathBuf::from(common.trim())).then(|| work_tree.clone())
})
.collect();
let mut found: Vec<RepositoryWorktrees> = repositories
.par_iter()
.map(|work_tree| examine(work_tree, &roots, current.as_deref(), options))
.collect();
for (work_tree, orphan) in orphans {
dangling::attach(&mut found, &work_tree, &orphan, &roots, current.as_deref(), options);
}
found.retain(|repository| !repository.worktrees.is_empty() || repository.error.is_some());
found.sort_by(|left, right| left.repository.cmp(&right.repository));
WorktreePruneResult {
repositories: found,
dry_run: options.dry_run,
elapsed: started.elapsed(),
}
}
fn examine(
work_tree: &Path,
roots: &[PathBuf],
current: Option<&Path>,
options: WorktreeOptions,
) -> RepositoryWorktrees {
let mut repository = RepositoryWorktrees {
repository: work_tree.to_path_buf(),
default_branch: None,
worktrees: Vec::new(),
error: None,
};
let Some(listing) = git(work_tree, &["worktree", "list", "--porcelain"]) else {
repository.error = Some("`git worktree list` failed".to_owned());
return repository;
};
let entries = parse_listing(&listing);
if let Some(main) = entries.first() {
repository.repository.clone_from(&main.path);
}
if !entries.iter().skip(1).any(|entry| !entry.bare) {
return repository;
}
let default = default_branch(&repository.repository);
if default.is_none() && !options.github_merged && options.stale_after.is_none() {
repository.error = Some("no default branch found (origin/HEAD, main, master)".to_owned());
return repository;
}
repository.default_branch = default.as_ref().map(|(name, _)| name.clone());
let github_repository = options
.github_merged
.then(|| github::repository(&repository.repository));
let hosted_merge = |head: &str, branch: Option<&str>| match &github_repository {
Some(Ok(name)) => github::merged(&repository.repository, name, head, branch),
Some(Err(error)) => Err(error.clone()),
None => Ok(github::Hosted::NotMerged),
};
let removal_lock = std::sync::Mutex::new(());
repository.worktrees = entries
.par_iter()
.skip(1)
.filter(|entry| !entry.bare)
.map(|entry| {
judge(
entry,
&JudgeContext {
main: &repository.repository,
merge_proof: MergeProof {
default_sha: default.as_ref().map(|(_, sha)| sha.as_str()),
hosted_merge: &hosted_merge,
},
roots,
current,
options,
removal_lock: &removal_lock,
},
)
})
.collect();
repository.worktrees.sort_by(|left, right| left.path.cmp(&right.path));
repository
}
type HostedLookup<'a> = dyn Fn(&str, Option<&str>) -> Result<github::Hosted, String> + Sync + 'a;
#[derive(Clone, Copy)]
struct MergeProof<'a> {
default_sha: Option<&'a str>,
hosted_merge: &'a HostedLookup<'a>,
}
#[derive(Clone, Copy)]
struct JudgeContext<'a> {
main: &'a Path,
merge_proof: MergeProof<'a>,
roots: &'a [PathBuf],
current: Option<&'a Path>,
options: WorktreeOptions,
removal_lock: &'a std::sync::Mutex<()>,
}
fn preliminary_state(entry: &Entry, canonical: &Path, context: &JudgeContext<'_>) -> Option<State> {
if entry.locked {
return Some(State::Locked);
}
if !entry.path.is_dir() {
return Some(State::Missing);
}
if !context
.roots
.iter()
.any(|root| canonical != *root && canonical.starts_with(root))
{
return Some(State::OutsideRoot);
}
if context.current.is_some_and(|cwd| cwd.starts_with(canonical)) {
return Some(State::Current);
}
None
}
fn hosted_proof(entry: &Entry, context: &JudgeContext<'_>) -> Result<(github::Hosted, bool), String> {
let ancestor = context
.merge_proof
.default_sha
.map_or(Ok(false), |sha| is_ancestor(context.main, &entry.head, sha));
let locally_merged = ancestor.as_ref().is_ok_and(|merged| *merged);
let proof = match ancestor {
Ok(true) => Ok(github::Hosted::Merged),
Ok(false) => (context.merge_proof.hosted_merge)(&entry.head, entry.branch.as_deref()),
Err(message) => Err(message),
};
proof.map(|hosted| (hosted, locally_merged))
}
fn removable_state(options: WorktreeOptions, merged: bool, discarded: usize) -> State {
if options.aggressive {
State::Discarded
} else if merged {
State::Merged { discarded }
} else {
State::Stale { discarded }
}
}
fn judge(entry: &Entry, context: &JudgeContext<'_>) -> Worktree {
let JudgeContext {
main,
roots,
options,
removal_lock,
..
} = *context;
let canonical = entry.path.canonicalize().unwrap_or_else(|_| entry.path.clone());
let mut worktree = Worktree {
path: canonical.clone(),
branch: entry.branch.clone(),
state: State::NotMerged,
outcome: None,
};
if let Some(state) = preliminary_state(entry, &canonical, context) {
worktree.state = state;
return worktree;
}
let guard = match removal_guard(roots, &entry.path) {
Ok(guard) => guard,
Err(message) => {
worktree.state = State::Unchecked(message);
return worktree;
}
};
let (hosted, locally_merged) = match hosted_proof(entry, context) {
Ok(proof) => proof,
Err(message) => {
worktree.state = State::Unchecked(message);
return worktree;
}
};
let merged = hosted == github::Hosted::Merged;
if !merged
&& !options
.stale_after
.is_some_and(|age| is_stale(entry, main, age, options.aggressive))
{
if let github::Hosted::HeadDiffers { pull } = hosted {
worktree.state = State::HeadDiffers { pull };
}
return worktree;
}
let Some((discarded, changed)) = local_status(&entry.path, options.aggressive) else {
worktree.state = State::Unchecked("`git status` failed".to_owned());
return worktree;
};
if changed > 0 && !options.aggressive {
worktree.state = State::LocalChanges { changed };
return worktree;
}
if !checkout_unchanged(entry, &canonical) {
worktree.state = State::Unchecked("worktree HEAD or path changed while checking it".to_owned());
return worktree;
}
worktree.state = removable_state(options, merged, discarded);
worktree.outcome = Some(if options.dry_run {
Outcome::WouldRemove
} else {
remove_checked(
entry,
main,
&canonical,
RemovalPolicy {
force: options.aggressive || discarded > 0,
aggressive: options.aggressive,
guard: &guard,
},
(merged && !locally_merged) || (options.aggressive && !merged && entry.branch.is_none()),
removal_lock,
)
});
worktree
}
fn local_status(path: &Path, aggressive: bool) -> Option<(usize, usize)> {
if aggressive { Some((0, 0)) } else { working_tree(path) }
}
fn removal_guard(roots: &[PathBuf], path: &Path) -> Result<crate::delete::Guard, String> {
let guard = crate::delete::Guard::new(roots, true).map_err(|error| format!("checking worktree path: {error}"))?;
guard
.check(path)
.map_err(|refusal| format!("worktree path refused: {refusal}"))?;
Ok(guard)
}
#[derive(Clone, Copy)]
struct RemovalPolicy<'a> {
force: bool,
aggressive: bool,
guard: &'a crate::delete::Guard,
}
fn remove_checked(
entry: &Entry,
main: &Path,
canonical: &Path,
policy: RemovalPolicy<'_>,
retain_head: bool,
removal_lock: &std::sync::Mutex<()>,
) -> Outcome {
let _serialised = removal_lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let clean_now = policy.aggressive || working_tree(&entry.path).is_some_and(|(_, changed)| changed == 0);
if !clean_now || !checkout_unchanged(entry, canonical) {
return Outcome::Failed("worktree HEAD or local changes changed before removal".to_owned());
}
if let Err(refusal) = policy.guard.check(&entry.path) {
return Outcome::Failed(format!("worktree path refused before removal: {refusal}"));
}
if retain_head {
let namespace = if policy.aggressive {
"aggressive-worktrees"
} else {
"merged-worktrees"
};
let reference = format!("refs/voom/{namespace}/{}", entry.head);
if git(main, &["update-ref", &reference, &entry.head]).is_none() {
return Outcome::Failed("could not retain worktree HEAD".to_owned());
}
}
if !checkout_unchanged(entry, canonical) {
return Outcome::Failed("worktree HEAD or path changed before removal".to_owned());
}
remove(main, &entry.path, policy.force)
}
fn checkout_unchanged(entry: &Entry, canonical: &Path) -> bool {
std::fs::symlink_metadata(&entry.path).is_ok_and(|metadata| metadata.file_type().is_dir())
&& entry.path.canonicalize().is_ok_and(|path| path == canonical)
&& git(&entry.path, &["rev-parse", "HEAD"]).is_some_and(|head| head.trim() == entry.head)
}
fn working_tree(path: &Path) -> Option<(usize, usize)> {
let tracked = git_bytes(path, &["status", "--porcelain=v1", "-z", "--untracked-files=no"])?;
let (discarded, changed) = classify_status_in(&tracked, Some(path));
if changed > 0 {
return Some((discarded, changed));
}
let full = git_bytes(
path,
&[
"status",
"--porcelain=v1",
"-z",
"--untracked-files=normal",
"--ignored=matching",
],
)?;
Some(classify_status_in(&full, Some(path)))
}
#[cfg(test)]
fn classify_status(status: &[u8]) -> (usize, usize) {
classify_status_in(status, None)
}
fn classify_status_in(status: &[u8], work_tree: Option<&Path>) -> (usize, usize) {
let mut discarded = 0;
let mut changed = 0;
let mut fields = status.split(|byte| *byte == 0).filter(|field| !field.is_empty());
while let Some(field) = fields.next() {
if field.len() < 4 {
changed += 1;
continue;
}
let (index, tree) = (field[0], field[1]);
let path = String::from_utf8_lossy(&field[3..]);
if matches!(index, b'R' | b'C') || matches!(tree, b'R' | b'C') {
fields.next();
}
if index == b' ' && tree == b'D' && is_deleted_build_output(&path) {
discarded += 1;
} else if index == b'!'
&& tree == b'!'
&& (is_build_output(&path) || work_tree.is_some_and(|root| is_ignored_dependency(root, &path)))
{
discarded += 1;
} else {
changed += 1;
}
}
(discarded, changed)
}
fn is_ignored_dependency(root: &Path, path: &str) -> bool {
let relative = Path::new(path.trim_end_matches('/'));
if !relative
.components()
.all(|part| matches!(part, std::path::Component::Normal(_)))
{
return false;
}
if !std::fs::symlink_metadata(root.join(relative)).is_ok_and(|metadata| metadata.file_type().is_dir()) {
return false;
}
let markers: &[&str] = match relative.file_name().and_then(|name| name.to_str()) {
Some("deps") => &["mix.exs"],
Some(".venv") => &["pyproject.toml", "setup.py", "setup.cfg"],
_ => return false,
};
let Some(parent) = relative.parent() else { return false };
markers.iter().any(|marker| {
std::fs::symlink_metadata(root.join(parent).join(marker)).is_ok_and(|metadata| metadata.file_type().is_file())
})
}
fn is_build_output(path: &str) -> bool {
path.split('/').any(|part| BUILD_OUTPUT_DIRS.contains(&part))
}
fn is_deleted_build_output(path: &str) -> bool {
let mut parts = path.split('/');
let top_level = parts.next();
if top_level.is_some_and(|first| BUILD_OUTPUT_DIRS.contains(&first)) {
return true;
}
let mut directories: Vec<&str> = parts.collect();
directories.pop();
directories
.iter()
.any(|part| UNAMBIGUOUS_BUILD_OUTPUT_DIRS.contains(part))
}
fn remove(main: &Path, path: &Path, force: bool) -> Outcome {
let mut command = base_command(main);
command.args(["worktree", "remove"]);
if force {
command.arg("--force");
}
command.arg(&*crate::git::for_git(path));
match command.output() {
Ok(output) if output.status.success() => Outcome::Removed,
Ok(output) => Outcome::Failed(
String::from_utf8_lossy(&output.stderr)
.lines()
.next()
.unwrap_or("")
.to_owned(),
),
Err(error) => Outcome::Failed(error.to_string()),
}
}
fn is_ancestor(main: &Path, head: &str, default_sha: &str) -> Result<bool, String> {
let output = base_command(main)
.args(["merge-base", "--is-ancestor", head, default_sha])
.output()
.map_err(|error| error.to_string())?;
match output.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
_ => Err("`git merge-base` failed".to_owned()),
}
}
fn is_stale(entry: &Entry, main: &Path, age: Duration, aggressive: bool) -> bool {
if !aggressive
&& git(main, &["for-each-ref", "--count=1", "--contains", &entry.head, "refs/"])
.is_none_or(|refs| refs.trim().is_empty())
{
return false;
}
let committed = git(&entry.path, &["log", "-1", "--format=%ct", "HEAD"])
.and_then(|seconds| seconds.trim().parse::<u64>().ok())
.map(|seconds| std::time::UNIX_EPOCH + Duration::from_secs(seconds));
let reflog = git(&entry.path, &["rev-parse", "--path-format=absolute", "--git-dir"])
.and_then(|dir| std::fs::metadata(Path::new(dir.trim()).join("logs/HEAD")).ok())
.and_then(|metadata| metadata.modified().ok());
let Some(latest) = [committed, reflog].into_iter().flatten().max() else {
return false;
};
committed.is_some() && latest.elapsed().is_ok_and(|idle| idle >= age)
}
fn default_branch(main: &Path) -> Option<(String, String)> {
let symbolic = git(main, &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
let candidates = symbolic
.iter()
.map(|target| target.trim().to_owned())
.chain(DEFAULT_BRANCH_FALLBACKS.iter().map(|name| (*name).to_owned()));
for candidate in candidates {
if let Some(sha) = git(
main,
&["rev-parse", "--verify", "--quiet", &format!("{candidate}^{{commit}}")],
) {
let short = candidate
.trim_start_matches("refs/remotes/")
.trim_start_matches("refs/heads/");
return Some((short.to_owned(), sha.trim().to_owned()));
}
}
None
}
#[derive(Debug, Default)]
struct Entry {
path: PathBuf,
head: String,
branch: Option<String>,
locked: bool,
bare: bool,
}
fn parse_listing(listing: &str) -> Vec<Entry> {
let mut entries = Vec::new();
for block in listing.split("\n\n") {
let mut entry = Entry::default();
for line in block.lines() {
if let Some(path) = line.strip_prefix("worktree ") {
entry.path = PathBuf::from(path);
} else if let Some(head) = line.strip_prefix("HEAD ") {
head.clone_into(&mut entry.head);
} else if let Some(branch) = line.strip_prefix("branch ") {
entry.branch = Some(branch.trim_start_matches("refs/heads/").to_owned());
} else if line == "bare" {
entry.bare = true;
} else if line == "locked" || line.starts_with("locked ") {
entry.locked = true;
}
}
if !entry.path.as_os_str().is_empty() {
entries.push(entry);
}
}
entries
}
fn base_command(dir: &Path) -> Command {
let mut command = Command::new("git");
command
.current_dir(dir)
.args(["-c", "core.hooksPath=", "-c", "core.fsmonitor=false"])
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_OPTIONAL_LOCKS", "0")
.stdin(Stdio::null());
command
}
fn git(dir: &Path, args: &[&str]) -> Option<String> {
git_bytes(dir, args).and_then(|bytes| String::from_utf8(bytes).ok())
}
fn git_bytes(dir: &Path, args: &[&str]) -> Option<Vec<u8>> {
let output = base_command(dir).args(args).output().ok()?;
output.status.success().then_some(output.stdout)
}