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)]
pub struct WorktreeOptions {
pub dry_run: bool,
pub stale_after: Option<Duration>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum State {
Main,
Locked,
Current,
Missing,
NotMerged,
OutsideRoot,
LocalChanges {
changed: usize,
},
Merged {
discarded: usize,
},
Stale {
discarded: usize,
},
Unchecked(String),
}
#[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,
}
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) {
(State::Merged { .. } | State::Stale { .. }, Some(Outcome::Removed | Outcome::WouldRemove)) => {
totals.removed += 1;
}
(State::Merged { .. } | State::Stale { .. }, Some(Outcome::Failed(_))) => totals.failed += 1,
(State::LocalChanges { .. }, _) => totals.local_changes += 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 repositories: Vec<PathBuf> = work_trees
.iter()
.filter_map(|work_tree| {
let common = git(work_tree, &["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
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();
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);
}
let Some((default_ref, default_sha)) = default_branch(&repository.repository) else {
repository.error = Some("no default branch found (origin/HEAD, main, master)".to_owned());
return repository;
};
repository.default_branch = Some(default_ref);
let removal_lock = std::sync::Mutex::new(());
repository.worktrees = entries
.par_iter()
.skip(1)
.filter(|entry| !entry.bare)
.map(|entry| {
judge(
entry,
&repository.repository,
&default_sha,
roots,
current,
options,
&removal_lock,
)
})
.collect();
repository.worktrees.sort_by(|left, right| left.path.cmp(&right.path));
repository
}
fn judge(
entry: &Entry,
main: &Path,
default_sha: &str,
roots: &[PathBuf],
current: Option<&Path>,
options: WorktreeOptions,
removal_lock: &std::sync::Mutex<()>,
) -> Worktree {
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 entry.locked {
worktree.state = State::Locked;
return worktree;
}
if !entry.path.is_dir() {
worktree.state = State::Missing;
return worktree;
}
if !roots
.iter()
.any(|root| canonical != *root && canonical.starts_with(root))
{
worktree.state = State::OutsideRoot;
return worktree;
}
if current.is_some_and(|cwd| cwd.starts_with(&canonical)) {
worktree.state = State::Current;
return worktree;
}
let merged = match is_ancestor(main, &entry.head, default_sha) {
Ok(merged) => merged,
Err(message) => {
worktree.state = State::Unchecked(message);
return worktree;
}
};
if !merged && !options.stale_after.is_some_and(|age| is_stale(entry, main, age)) {
return worktree;
}
let Some(status) = git_bytes(
&entry.path,
&[
"status",
"--porcelain=v1",
"-z",
"--untracked-files=normal",
"--ignored=matching",
],
) else {
worktree.state = State::Unchecked("`git status` failed".to_owned());
return worktree;
};
let (discarded, changed) = classify_status(&status);
if changed > 0 {
worktree.state = State::LocalChanges { changed };
return worktree;
}
worktree.state = if merged {
State::Merged { discarded }
} else {
State::Stale { discarded }
};
worktree.outcome = Some(if options.dry_run {
Outcome::WouldRemove
} else {
let _serialised = removal_lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
remove(main, &entry.path, discarded > 0)
});
worktree
}
fn classify_status(status: &[u8]) -> (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) {
discarded += 1;
} else {
changed += 1;
}
}
(discarded, changed)
}
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) -> bool {
let reachable = git(main, &["for-each-ref", "--count=1", "--contains", &entry.head, "refs/"])
.is_some_and(|refs| !refs.trim().is_empty());
if !reachable {
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")
.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)
}