use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RemovalReason {
Merged,
MergedInto(String),
MergedThrough(String),
SessionMerged(String),
Verdict(String),
NoChanges,
ResearchReport,
ResearchReportInWorktree,
ResearchEndedWithoutReport(String),
ResearchStoppedWithoutSummary(u64),
OlderThan(u64),
}
impl std::fmt::Display for RemovalReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Merged => write!(f, "merged"),
Self::MergedInto(base) => write!(f, "merged into {base}"),
Self::MergedThrough(child) => write!(f, "merged through {child}"),
Self::SessionMerged(branch) => write!(f, "{branch} merged"),
Self::Verdict(v) => {
if v.is_empty() {
write!(f, "verdict")
} else {
write!(f, "verdict {v}")
}
}
Self::NoChanges => write!(f, "no changes"),
Self::ResearchReport => write!(f, "research report"),
Self::ResearchReportInWorktree => {
write!(f, "research report (copied out on removal)")
}
Self::ResearchEndedWithoutReport(outcome) => {
write!(f, "research run ended without a report ({outcome})")
}
Self::ResearchStoppedWithoutSummary(d) => {
write!(
f,
"research run stopped without a summary, started more than {d} days ago"
)
}
Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum KeptReason {
UncommittedChanges,
Running,
NoVerdict,
NotMergedYet,
NoReport,
UnreadableSummary,
InUse,
CannotCheckInUse(String),
UsedRecently(u64),
HoldsRuns(String),
Custom(String),
}
impl std::fmt::Display for KeptReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UncommittedChanges => write!(f, "uncommitted changes"),
Self::Running => write!(f, "running"),
Self::NoVerdict => write!(f, "no verdict"),
Self::NotMergedYet => write!(f, "not merged yet"),
Self::NoReport => write!(f, "no report"),
Self::UnreadableSummary => write!(f, "unreadable summary"),
Self::InUse => write!(f, "in use by a running process"),
Self::CannotCheckInUse(err) => {
write!(f, "cannot tell whether it is in use: {err}")
}
Self::UsedRecently(d) => write!(f, "used in the last {d} days"),
Self::HoldsRuns(path) => write!(f, "holds runs: review them from {path}"),
Self::Custom(s) => write!(f, "{s}"),
}
}
}
pub fn dir_size(path: &Path) -> u64 {
let mut total = 0;
let Ok(meta) = std::fs::symlink_metadata(path) else {
return 0;
};
if meta.file_type().is_symlink() {
return 0;
}
if meta.is_file() {
return meta.len();
}
if meta.is_dir() {
let Ok(entries) = std::fs::read_dir(path) else {
return 0;
};
for entry in entries.flatten() {
let Ok(ft) = entry.file_type() else {
continue;
};
if ft.is_symlink() {
continue;
} else if ft.is_dir() {
total += dir_size(&entry.path());
} else if ft.is_file() {
if let Ok(m) = entry.metadata() {
total += m.len();
}
}
}
}
total
}
pub fn format_size(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let b = bytes as f64;
let (val, unit) = if b >= GB {
(b / GB, "GB")
} else if b >= MB {
(b / MB, "MB")
} else if b >= KB {
(b / KB, "KB")
} else {
return format!("{bytes} B");
};
let s = if val >= 100.0 {
format!("{val:.0}")
} else {
let formatted = format!("{val:.1}");
formatted
.strip_suffix(".0")
.unwrap_or(&formatted)
.to_string()
};
format!("{s} {unit}")
}
pub fn is_pid_alive(pid: i64) -> bool {
if pid <= 0 {
return false;
}
let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
if ret == 0 {
true
} else {
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
}
pub fn find_repo_root() -> Result<PathBuf, String> {
let out = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output()
.map_err(|e| format!("git not found: {e}"))?;
if !out.status.success() {
return Err("not a git repository".to_string());
}
let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
let dirs = std::process::Command::new("git")
.args([
"rev-parse",
"--path-format=absolute",
"--git-dir",
"--git-common-dir",
])
.current_dir(&root)
.output()
.map_err(|e| format!("git not found: {e}"))?;
if !dirs.status.success() {
return Err(format!(
"cannot read the git dirs of {}: {}",
root.display(),
String::from_utf8_lossy(&dirs.stderr).trim()
));
}
let dirs = String::from_utf8_lossy(&dirs.stdout);
let mut lines = dirs.lines();
let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
return Err(format!("cannot read the git dirs of {}", root.display()));
};
if git_dir != common_dir {
crate::config::main_checkout(&root).ok_or_else(|| {
format!(
"cannot find main checkout for linked worktree {}",
root.display()
)
})
} else {
Ok(root)
}
}
pub fn is_research(root: &Path, id: &str) -> bool {
let start_path = root.join(".wt").join(format!("{id}.start.json"));
if let Ok(s) = std::fs::read_to_string(&start_path) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
return val
.get("research")
.and_then(|r| r.as_bool())
.unwrap_or(false);
}
}
false
}
pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
let out = std::process::Command::new("git")
.args([
"-C",
wt_path.to_str().unwrap_or(""),
"status",
"--porcelain",
])
.output();
match out {
Ok(o) if o.status.success() => {
!o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
}
_ => true,
}
}
fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
let out = std::process::Command::new("git")
.args(["rev-parse", &format!("{ref_name}^{{tree}}")])
.current_dir(root)
.output()
.ok()?;
if out.status.success() {
Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
None
}
}
fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
let cherry_out = std::process::Command::new("git")
.args(["cherry", target, commit_sha])
.current_dir(root)
.output();
if let Ok(o) = cherry_out {
if o.status.success() {
let s = String::from_utf8_lossy(&o.stdout);
let lines: Vec<&str> = s
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
return true;
}
}
}
false
}
fn is_merge_tree_merged_into_target(
root: &Path,
commit_sha: &str,
target: &str,
target_tree: Option<&str>,
) -> bool {
let target_tree_sha = match target_tree {
Some(t) => Some(t.to_string()),
None => git_tree_sha(root, target),
};
if let Some(target_tree_sha) = target_tree_sha {
let merge_tree_out = std::process::Command::new("git")
.args(["merge-tree", "--write-tree", target, commit_sha])
.current_dir(root)
.output();
if let Ok(mt_o) = merge_tree_out {
if mt_o.status.success() {
let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
if let Some(first_line) = mt_stdout.lines().next() {
if first_line.trim() == target_tree_sha {
return true;
}
}
}
}
}
false
}
fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
let s = val.get("started_at")?;
if let Some(n) = s.as_u64() {
Some(n)
} else if let Some(n) = s.as_i64() {
if n >= 0 {
Some(n as u64)
} else {
None
}
} else if let Some(f) = s.as_f64() {
if f >= 0.0 {
Some(f as u64)
} else {
None
}
} else if let Some(st) = s.as_str() {
st.parse::<u64>().ok()
} else {
None
}
}
fn check_history_merged(
root: &Path,
tip_sha: &str,
target: &str,
started_at: Option<&serde_json::Value>,
) -> bool {
let mb_out = std::process::Command::new("git")
.args(["merge-base", target, tip_sha])
.current_dir(root)
.output();
let Ok(mb_o) = mb_out else {
return false;
};
if !mb_o.status.success() {
return false;
}
let merge_base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
if merge_base.is_empty() {
return false;
}
let diff_out = std::process::Command::new("git")
.args(["diff", "--name-only", &merge_base, tip_sha])
.current_dir(root)
.output();
let Ok(diff_o) = diff_out else {
return false;
};
if !diff_o.status.success() {
return false;
}
let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
if files.is_empty() {
return false;
}
let since_arg = started_at
.and_then(|v| {
if let Some(n) = v.as_i64() {
if n >= 100_000_000 {
Some(format!("--since={n}"))
} else {
Some("--since=1970-01-01T00:00:00Z".to_string())
}
} else if let Some(n) = v.as_u64() {
if n >= 100_000_000 {
Some(format!("--since={n}"))
} else {
Some("--since=1970-01-01T00:00:00Z".to_string())
}
} else {
v.as_str().map(|s| format!("--since={s}"))
}
})
.unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
let mut cmd = std::process::Command::new("git");
cmd.args([
"rev-list",
"--first-parent",
&since_arg,
"-n",
"20",
target,
"--",
]);
for f in &files {
cmd.arg(f);
}
cmd.current_dir(root);
let Ok(rev_o) = cmd.output() else {
return false;
};
if !rev_o.status.success() {
return false;
}
let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
for c in commits {
let mt_out = std::process::Command::new("git")
.args(["merge-tree", "--write-tree", &c, tip_sha])
.current_dir(root)
.output();
let Ok(mt_o) = mt_out else {
continue;
};
if !mt_o.status.success() {
continue;
}
let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
let Some(first_line) = mt_stdout.lines().next() else {
continue;
};
let mt_tree = first_line.trim();
if let Some(c_tree) = git_tree_sha(root, &c) {
if mt_tree == c_tree {
return true;
}
}
}
false
}
pub struct CleanContext<'a> {
pub root: &'a Path,
pub start_files: HashMap<String, serde_json::Value>,
pub all_run_ids: Vec<String>,
pub wip_branch_tips: HashMap<String, String>,
pub default_branch: String,
pub origin_default: Option<String>,
pub default_tree: Option<String>,
pub origin_default_tree: Option<String>,
pub wip_contains_cache: HashMap<String, Vec<String>>,
pub merged_cache: HashMap<String, Option<RemovalReason>>,
pub branch_contains_calls: usize,
pub cherry_pick_set: Option<HashSet<String>>,
pub rev_list_cache: HashMap<String, Vec<String>>,
pub ancestor_cache: HashMap<(String, String), bool>,
}
impl<'a> CleanContext<'a> {
pub fn new(root: &'a Path) -> Self {
let mut start_files = HashMap::new();
let mut all_run_ids = Vec::new();
let wt_dir = root.join(".wt");
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(id) = name.strip_suffix(".start.json") {
all_run_ids.push(id.to_string());
if let Ok(content) = std::fs::read_to_string(entry.path()) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
start_files.insert(id.to_string(), val);
}
}
}
}
}
all_run_ids.sort();
let mut wip_branch_tips = HashMap::new();
let ref_out = std::process::Command::new("git")
.args([
"for-each-ref",
"--format=%(refname:short) %(objectname)",
"refs/heads/wip/",
])
.current_dir(root)
.output();
if let Ok(o) = ref_out {
if o.status.success() {
for line in String::from_utf8_lossy(&o.stdout).lines() {
let mut parts = line.split_whitespace();
if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
wip_branch_tips.insert(refname.to_string(), sha.to_string());
}
}
}
}
let default_branch = find_default_branch(root);
let name = default_branch
.strip_prefix("origin/")
.unwrap_or(&default_branch);
let remote = format!("origin/{name}");
let origin_default = if remote != default_branch
&& git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
{
Some(remote)
} else {
None
};
let default_tree = git_tree_sha(root, &default_branch);
let origin_default_tree = origin_default
.as_deref()
.and_then(|r| git_tree_sha(root, r));
Self {
root,
start_files,
all_run_ids,
wip_branch_tips,
default_branch,
origin_default,
default_tree,
origin_default_tree,
wip_contains_cache: HashMap::new(),
merged_cache: HashMap::new(),
branch_contains_calls: 0,
cherry_pick_set: None,
rev_list_cache: HashMap::new(),
ancestor_cache: HashMap::new(),
}
}
fn compute_cherry_pick_set(&self) -> HashSet<String> {
let unremoved_ids = find_blyte_worktrees(self.root);
let candidate_ids: &[String] = if unremoved_ids.is_empty() {
&self.all_run_ids
} else {
&unremoved_ids
};
let mut min_started_at: Option<u64> = None;
let mut all_valid = true;
for id in candidate_ids {
let start_val = self.start_files.get(id);
let parsed = start_val.and_then(parse_started_at);
match parsed {
Some(ts) => {
min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
}
None => {
all_valid = false;
}
}
}
let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
if min_ts >= 86_400 + 100_000_000 {
format!("--since={}", min_ts - 86_400)
} else {
"--since=1970-01-01T00:00:00Z".to_string()
}
} else {
"--since=1970-01-01T00:00:00Z".to_string()
};
let mut targets = Vec::new();
let mut seen = HashSet::new();
if git_ok(
self.root,
&["rev-parse", "--verify", "--quiet", &self.default_branch],
) && seen.insert(self.default_branch.clone())
{
targets.push(self.default_branch.clone());
}
if let Some(ref origin_def) = self.origin_default {
if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
&& seen.insert(origin_def.clone())
{
targets.push(origin_def.clone());
}
}
for id in &self.all_run_ids {
if let Some(base_str) = self
.start_files
.get(id)
.and_then(|s| s.get("base"))
.and_then(|b| b.as_str())
{
if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
for bt in base_targets {
if seen.insert(bt.clone()) {
targets.push(bt);
}
}
}
}
}
if targets.is_empty() {
return HashSet::new();
}
let mut cmd = std::process::Command::new("git");
cmd.args(["log", "--format=%B", &since_arg]);
for t in &targets {
cmd.arg(t);
}
cmd.current_dir(self.root);
let mut set = HashSet::new();
if let Ok(o) = cmd.output() {
if o.status.success() {
let text = String::from_utf8_lossy(&o.stdout);
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
if let Some(sha) = rest.strip_suffix(')') {
let sha = sha.trim();
if is_commit_id(sha) {
set.insert(sha.to_lowercase());
}
}
}
}
}
}
set
}
pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
if self.cherry_pick_set.is_none() {
let set = self.compute_cherry_pick_set();
self.cherry_pick_set = Some(set);
}
self.cherry_pick_set.as_ref().unwrap()
}
fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
let key = (commit_sha.to_string(), target.to_string());
if let Some(&cached) = self.ancestor_cache.get(&key) {
return cached;
}
let is_anc = std::process::Command::new("git")
.args(["merge-base", "--is-ancestor", commit_sha, target])
.current_dir(self.root)
.output()
.map(|c| c.status.success())
.unwrap_or(false);
self.ancestor_cache.insert(key, is_anc);
is_anc
}
fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
let def = self.default_branch.clone();
if self.is_ancestor_of_target(commit_sha, &def) {
return true;
}
if let Some(origin_def) = self.origin_default.clone() {
if self.is_ancestor_of_target(commit_sha, &origin_def) {
return true;
}
}
false
}
fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
if let Some(cached) = self.rev_list_cache.get(tip_sha) {
return cached.clone();
}
let out = std::process::Command::new("git")
.args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
.current_dir(self.root)
.output();
let commits: Vec<String> = match out {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
.lines()
.map(|l| l.trim().to_lowercase())
.filter(|l| !l.is_empty())
.collect(),
_ => Vec::new(),
};
self.rev_list_cache
.insert(tip_sha.to_string(), commits.clone());
commits
}
fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
let commits = self.get_run_commits_against_default(tip_sha);
if commits.is_empty() {
return false;
}
let cherry_set = self.get_cherry_pick_set();
commits.iter().all(|c| cherry_set.contains(c))
}
pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
if let Some(sha) = self.wip_branch_tips.get(branch_name) {
return Some(sha.clone());
}
get_branch_tip(self.root, branch_name)
}
pub fn is_research_run(&self, id: &str) -> bool {
self.start_files
.get(id)
.and_then(|v| v.get("research"))
.and_then(|r| r.as_bool())
.unwrap_or_else(|| is_research(self.root, id))
}
pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
return cached.clone();
}
self.branch_contains_calls += 1;
let out = std::process::Command::new("git")
.args([
"branch",
"--list",
"--format=%(refname:short)",
"wip/*",
"--contains",
tip_sha,
])
.current_dir(self.root)
.output();
let mut branches = Vec::new();
if let Ok(o) = out {
if o.status.success() {
for line in String::from_utf8_lossy(&o.stdout).lines() {
let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
if !trimmed.is_empty() {
branches.push(trimmed.to_string());
}
}
}
}
self.wip_contains_cache
.insert(tip_sha.to_string(), branches.clone());
branches
}
pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
let mut children = Vec::new();
let mut seen = HashSet::new();
for (candidate_id, start_val) in &self.start_files {
if candidate_id == id {
continue;
}
if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
let base_str = base_str.trim().trim_end_matches('/');
let target1 = format!("wip/{id}");
let target2 = format!("refs/heads/wip/{id}");
if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
{
children.push(candidate_id.clone());
}
}
}
if !tip_sha.is_empty() {
let tip_sha_owned = tip_sha.to_string();
let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
for b in containing_branches {
let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
if candidate_id == id {
continue;
}
if !self.start_files.contains_key(candidate_id) {
continue;
}
let has_base = self
.start_files
.get(candidate_id)
.and_then(|val| val.get("base"))
.is_some_and(|b| !b.is_null());
if !has_base && seen.insert(candidate_id.to_string()) {
children.push(candidate_id.to_string());
}
}
}
}
children.sort();
children
}
pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
if self.is_research_run(child) {
return false;
}
let branch_name = format!("wip/{child}");
let tip = self.get_branch_tip(&branch_name);
if tip.is_none() {
let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
let v = std::fs::read_to_string(&verdict_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("verdict")
.and_then(|s| s.as_str())
.map(|s| s.to_string())
})
.unwrap_or_default();
(v == "accepted" || v == "fixed", v == "redone")
} else {
(false, false)
};
if is_redone {
return false;
}
let summary_path = self.root.join(".wt").join(format!("{child}.json"));
let is_verified = std::fs::read_to_string(&summary_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("outcome")
.and_then(|s| s.as_str())
.map(|s| s == "verified")
})
.unwrap_or(false);
let wt_gone = !self.root.join(".wt").join(child).is_dir();
return has_accepted_verdict || (is_verified && wt_gone);
}
self.check_run_merged_internal(child, visited).is_some()
}
pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
let mut visited = HashSet::new();
self.check_run_merged_internal(id, &mut visited)
}
fn check_run_merged_internal(
&mut self,
id: &str,
visited: &mut HashSet<String>,
) -> Option<RemovalReason> {
if visited.contains(id) {
return None;
}
if let Some(cached) = self.merged_cache.get(id) {
return cached.clone();
}
visited.insert(id.to_string());
let branch_name = format!("wip/{id}");
let tip_sha = self.get_branch_tip(&branch_name);
let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
visited.remove(id);
self.merged_cache.insert(id.to_string(), result.clone());
result
}
fn decide_run_merged(
&mut self,
id: &str,
tip_sha: Option<&str>,
visited: &mut HashSet<String>,
) -> Option<RemovalReason> {
let base_opt = self.start_files.get(id).and_then(|s| {
s.get("base")
.and_then(|b| b.as_str())
.map(|b| b.to_string())
});
let base_targets = base_opt
.as_deref()
.and_then(|b| resolve_base_targets(self.root, b));
let started_at = self
.start_files
.get(id)
.and_then(|s| s.get("started_at"))
.cloned();
if let Some(tip_sha) = tip_sha {
if self.is_ancestor_of_default(tip_sha) {
return Some(RemovalReason::Merged);
}
if self.is_in_cherry_pick_record(tip_sha) {
return Some(RemovalReason::Merged);
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if self.is_ancestor_of_target(tip_sha, target) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
if is_cherry_merged_into_target(self.root, tip_sha, target) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
}
}
}
let children = self.get_children_of(id, tip_sha.unwrap_or(""));
for child in children {
if visited.contains(&child) {
continue;
}
if self.is_child_run_merged(&child, visited) {
return Some(RemovalReason::MergedThrough(child));
}
}
if let Some(tip_sha) = tip_sha {
if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
return Some(RemovalReason::Merged);
}
if let Some(ref origin_def) = self.origin_default {
if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
return Some(RemovalReason::Merged);
}
}
if is_merge_tree_merged_into_target(
self.root,
tip_sha,
&self.default_branch,
self.default_tree.as_deref(),
) {
return Some(RemovalReason::Merged);
}
if let Some(ref origin_def) = self.origin_default {
if is_merge_tree_merged_into_target(
self.root,
tip_sha,
origin_def,
self.origin_default_tree.as_deref(),
) {
return Some(RemovalReason::Merged);
}
}
if check_history_merged(
self.root,
tip_sha,
&self.default_branch,
started_at.as_ref(),
) {
return Some(RemovalReason::Merged);
}
if let Some(ref origin_def) = self.origin_default {
if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
return Some(RemovalReason::Merged);
}
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
}
}
if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
return Some(reason);
}
}
None
}
fn squash_merged_reason(
&self,
tip_sha: &str,
base_targets: &Option<(String, Vec<String>)>,
) -> Option<RemovalReason> {
if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
return Some(RemovalReason::Merged);
}
if let Some(ref origin_def) = self.origin_default {
if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
return Some(RemovalReason::Merged);
}
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if is_squash_merged_into_target(self.root, tip_sha, target) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
}
}
None
}
pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
let branch_name = format!("wip/{id}");
let tip_sha = self.get_branch_tip(&branch_name);
let mut visited = HashSet::new();
visited.insert(id.to_string());
let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
children
.into_iter()
.find(|child| self.is_child_run_merged(child, &mut visited))
}
pub fn check_removable(
&mut self,
id: &str,
older_than_days: u64,
) -> Result<RemovalReason, KeptReason> {
let wt_dir = self.root.join(".wt");
let summary_path = wt_dir.join(format!("{id}.json"));
let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
let report_path = wt_dir.join(format!("{id}.report.md"));
let start_json = self.start_files.get(id);
let summary_exists = summary_path.is_file();
if let Some(start) = start_json {
if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
if is_pid_alive(pid) {
if !summary_exists {
return Err(KeptReason::Running);
}
let Some(started_at) = parse_started_at(start) else {
return Err(KeptReason::Running);
};
let summary_mtime = std::fs::metadata(&summary_path)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
if summary_mtime.is_none_or(|mtime| mtime < started_at) {
return Err(KeptReason::Running);
}
}
}
}
let is_res = self.is_research_run(id);
let verdict_str = if verdict_path.is_file() {
std::fs::read_to_string(&verdict_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("verdict")
.and_then(|s| s.as_str())
.map(|s| s.to_string())
})
.unwrap_or_default()
} else {
String::new()
};
if verdict_str == "redone" {
return Ok(RemovalReason::Verdict("redone".to_string()));
}
if summary_exists {
if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
return Ok(RemovalReason::NoChanges);
}
}
}
}
if is_res && report_path.is_file() {
return Ok(RemovalReason::ResearchReport);
}
if is_res {
let wt_report_path = wt_dir.join(id).join("report.md");
if wt_report_path.is_file() && !report_path.is_file() {
return Ok(RemovalReason::ResearchReportInWorktree);
}
if summary_exists {
let outcome = std::fs::read_to_string(&summary_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("outcome")
.and_then(|o| o.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
});
return match outcome {
Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
None => Err(KeptReason::UnreadableSummary),
};
}
let start_path = wt_dir.join(format!("{id}.start.json"));
if let Ok(meta) = std::fs::metadata(&start_path) {
if let Ok(mtime) = meta.modified() {
let age = std::time::SystemTime::now()
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
{
return Ok(RemovalReason::ResearchStoppedWithoutSummary(
older_than_days,
));
}
}
}
}
if !is_res {
if let Some(reason) = self.check_run_merged(id) {
return Ok(reason);
}
}
if summary_exists {
if let Ok(meta) = std::fs::metadata(&summary_path) {
if let Ok(mtime) = meta.modified() {
let age = std::time::SystemTime::now()
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
{
return Ok(RemovalReason::OlderThan(older_than_days));
}
}
}
}
if !verdict_str.is_empty() {
return Err(KeptReason::NotMergedYet);
}
if is_res {
Err(KeptReason::NoReport)
} else {
Err(KeptReason::NoVerdict)
}
}
}
pub fn check_removable(
root: &Path,
id: &str,
older_than_days: u64,
) -> Result<RemovalReason, KeptReason> {
let mut ctx = CleanContext::new(root);
ctx.check_removable(id, older_than_days)
}
pub fn find_default_branch(root: &Path) -> String {
let sym_out = std::process::Command::new("git")
.args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
.current_dir(root)
.output();
if let Ok(o) = sym_out {
if o.status.success() {
let target = String::from_utf8_lossy(&o.stdout);
let target = target.trim();
let branch_name = target.strip_prefix("origin/").unwrap_or(target);
let local_check = std::process::Command::new("git")
.args([
"rev-parse",
"--verify",
&format!("refs/heads/{branch_name}"),
])
.current_dir(root)
.output();
if local_check.map(|c| c.status.success()).unwrap_or(false) {
return branch_name.to_string();
}
let remote_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", target])
.current_dir(root)
.output();
if remote_check.map(|c| c.status.success()).unwrap_or(false) {
return target.to_string();
}
return branch_name.to_string();
}
}
let main_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", "refs/heads/main"])
.current_dir(root)
.output();
if main_check.map(|c| c.status.success()).unwrap_or(false) {
return "main".to_string();
}
let master_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", "refs/heads/master"])
.current_dir(root)
.output();
if master_check.map(|c| c.status.success()).unwrap_or(false) {
return "master".to_string();
}
"main".to_string()
}
fn is_commit_id(s: &str) -> bool {
(s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
}
pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
let base = base.trim();
if base.is_empty() {
return None;
}
if base == "HEAD"
|| base.starts_with("HEAD~")
|| base.starts_with("HEAD^")
|| base.starts_with("HEAD@")
|| base.starts_with("HEAD:")
{
return None;
}
if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
return None;
}
if is_commit_id(base) {
return None;
}
let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
stripped
} else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
stripped
} else {
base
};
let is_wip = clean == "wip"
|| clean.starts_with("wip/")
|| clean == "origin/wip"
|| clean.starts_with("origin/wip/");
if is_wip {
return None;
}
let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
if without_origin.is_empty()
|| without_origin == "wip"
|| without_origin.starts_with("wip/")
|| without_origin == "HEAD"
|| without_origin.starts_with("HEAD~")
|| without_origin.starts_with("HEAD^")
|| is_commit_id(without_origin)
{
return None;
}
let cand1 = format!("refs/remotes/{clean}");
let cand2 = format!("refs/heads/{without_origin}");
(without_origin.to_string(), vec![cand1, cand2])
} else {
let cand1 = format!("refs/heads/{clean}");
let cand2 = format!("refs/remotes/origin/{clean}");
(clean.to_string(), vec![cand1, cand2])
};
let mut resolved = Vec::new();
for cand in candidates {
if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
resolved.push(cand);
}
}
if resolved.is_empty() {
None
} else {
Some((display_name, resolved))
}
}
pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
let start_path = root.join(".wt").join(format!("{id}.start.json"));
std::fs::read_to_string(&start_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("base")
.and_then(|b| b.as_str())
.map(|s| s.to_string())
})
}
pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
let check = std::process::Command::new("git")
.args([
"rev-parse",
"--verify",
&format!("refs/heads/{branch_name}"),
])
.current_dir(root)
.output()
.ok()?;
if !check.status.success() {
return None;
}
let tip_out = std::process::Command::new("git")
.args(["rev-parse", &format!("refs/heads/{branch_name}")])
.current_dir(root)
.output()
.ok()?;
if tip_out.status.success() {
Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
} else {
None
}
}
pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
let mut ctx = CleanContext::new(root);
if let Some(id) = branch_name.strip_prefix("wip/") {
ctx.check_run_merged(id).is_some()
} else {
is_branch_merged_with_targets(root, branch_name, &[])
}
}
pub fn is_branch_merged_with_targets(
root: &Path,
branch_name: &str,
extra_targets: &[&str],
) -> bool {
let Some(tip_sha) = get_branch_tip(root, branch_name) else {
return false;
};
is_commit_merged_with_targets(root, &tip_sha, extra_targets)
}
pub fn is_branch_merged_with_extra_targets(
root: &Path,
branch_name: &str,
extra_targets: &[&str],
) -> bool {
is_branch_merged_with_targets(root, branch_name, extra_targets)
}
pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
is_commit_merged_with_targets(root, commit_sha, &[])
}
pub fn is_commit_merged_with_targets(
root: &Path,
commit_sha: &str,
extra_targets: &[&str],
) -> bool {
let default_branch = find_default_branch(root);
let name = default_branch
.strip_prefix("origin/")
.unwrap_or(&default_branch);
let remote = format!("origin/{name}");
let mut targets = vec![default_branch.clone()];
if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
targets.push(remote);
}
for extra in extra_targets {
if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
targets.push(extra.to_string());
}
}
targets
.iter()
.any(|target| merged_into(root, commit_sha, target))
}
fn git_ok(root: &Path, args: &[&str]) -> bool {
std::process::Command::new("git")
.args(args)
.current_dir(root)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
let ancestor_check = std::process::Command::new("git")
.args(["merge-base", "--is-ancestor", commit_sha, default_branch])
.current_dir(root)
.output();
if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
return true;
}
let cherry_out = std::process::Command::new("git")
.args(["cherry", default_branch, commit_sha])
.current_dir(root)
.output();
if let Ok(o) = cherry_out {
if o.status.success() {
let s = String::from_utf8_lossy(&o.stdout);
let lines: Vec<&str> = s
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
return true;
}
}
}
let default_tree_out = std::process::Command::new("git")
.args(["rev-parse", &format!("{default_branch}^{{tree}}")])
.current_dir(root)
.output();
if let Ok(tree_o) = default_tree_out {
if tree_o.status.success() {
let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
let merge_tree_out = std::process::Command::new("git")
.args(["merge-tree", "--write-tree", default_branch, commit_sha])
.current_dir(root)
.output();
if let Ok(mt_o) = merge_tree_out {
if mt_o.status.success() {
let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
if let Some(first_line) = mt_stdout.lines().next() {
if first_line.trim() == default_tree {
return true;
}
}
}
}
}
}
is_squash_merged_into_target(root, commit_sha, default_branch)
}
fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
let mb_out = std::process::Command::new("git")
.args(["merge-base", target, commit_sha])
.current_dir(root)
.output();
let Ok(mb_o) = mb_out else {
return false;
};
if !mb_o.status.success() {
return false;
}
let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
if base.is_empty() {
return false;
}
let subj_out = std::process::Command::new("git")
.args([
"log",
"--no-merges",
"--format=%s",
&format!("{target}..{commit_sha}"),
])
.current_dir(root)
.output();
let Ok(subj_o) = subj_out else {
return false;
};
if !subj_o.status.success() {
return false;
}
let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
let subjects: Vec<&str> = subj_stdout
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if subjects.is_empty() {
return false;
}
let hay_out = std::process::Command::new("git")
.args(["log", "--format=%B", &format!("{base}..{target}")])
.current_dir(root)
.output();
let Ok(hay_o) = hay_out else {
return false;
};
if !hay_o.status.success() {
return false;
}
let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
let mut haystack_lines = HashSet::new();
for line in hay_stdout.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
haystack_lines.insert(trimmed.to_string());
if let Some(stripped) = trimmed
.strip_prefix("* ")
.or_else(|| trimmed.strip_prefix("- "))
{
let stripped = stripped.trim();
if !stripped.is_empty() {
haystack_lines.insert(stripped.to_string());
}
}
}
subjects.iter().all(|s| haystack_lines.contains(*s))
}
pub fn list_all_run_ids(root: &Path) -> Vec<String> {
let wt_dir = root.join(".wt");
let mut ids = Vec::new();
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(id) = name.strip_suffix(".start.json") {
ids.push(id.to_string());
}
}
}
ids.sort();
ids
}
pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
let mut ctx = CleanContext::new(root);
ctx.find_merged_followup(id)
}
pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
let wt_dir = root.join(".wt");
if !wt_dir.is_dir() {
return Vec::new();
}
let mut ids = Vec::new();
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
if let Ok(ft) = entry.file_type() {
if ft.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
let start_file = wt_dir.join(format!("{name}.start.json"));
if start_file.is_file() {
ids.push(name);
}
}
}
}
}
ids.sort();
ids
}
#[derive(Debug, Default)]
pub struct CleanRepoStats {
pub removed_worktrees: usize,
pub freed_bytes: u64,
pub had_errors: bool,
}
pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
stdout
.lines()
.filter_map(|line| line.strip_prefix('n'))
.filter(|path| !path.is_empty())
.map(PathBuf::from)
.collect()
}
pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
let out = std::process::Command::new("lsof")
.args(["-a", "-d", "cwd", "-Fn"])
.output()
.map_err(|e| e.to_string())?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
if stderr.is_empty() {
return Err(format!("lsof exited with {}", out.status));
}
return Err(format!("lsof exited with {}: {stderr}", out.status));
}
let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
if paths.is_empty() {
return Err("lsof listed no working directories".to_string());
}
Ok(paths)
}
pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let wt_canon = wt_path
.canonicalize()
.unwrap_or_else(|_| wt_path.to_path_buf());
let Some(wt_parent) = wt_canon.parent() else {
return false;
};
let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
return false;
};
let wt_dir_canon = root_canon
.join(".wt")
.canonicalize()
.unwrap_or_else(|_| root_canon.join(".wt"));
if wt_parent == wt_dir_canon {
let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
return !start_file.is_file();
}
let claude_wt_dir_canon = root_canon
.join(".claude")
.join("worktrees")
.canonicalize()
.unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
return true;
}
}
false
}
pub fn has_dispatched_runs(wt_path: &Path) -> bool {
let wt_dir = wt_path.join(".wt");
let Ok(entries) = std::fs::read_dir(&wt_dir) else {
return false;
};
for entry in entries.flatten() {
let name = entry.file_name();
if name.to_string_lossy().ends_with(".start.json")
&& entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
{
return true;
}
}
false
}
pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
let wt_canon = wt_path
.canonicalize()
.unwrap_or_else(|_| wt_path.to_path_buf());
cwds.iter().any(|cwd| {
let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
cwd_canon.starts_with(&wt_canon)
})
}
pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
let o = std::process::Command::new("git")
.arg("-C")
.arg(wt_path.as_os_str())
.args(["rev-parse", "--absolute-git-dir"])
.output()
.map_err(|e| format!("cannot run git: {e}"))?;
if !o.status.success() {
return Err(format!(
"git rev-parse --absolute-git-dir failed: {}",
String::from_utf8_lossy(&o.stderr).trim()
));
}
let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
if git_dir_str.is_empty() {
return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
}
let git_dir = PathBuf::from(git_dir_str);
let now = std::time::SystemTime::now();
let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
for name in ["index", "HEAD"] {
let p = git_dir.join(name);
let mtime = std::fs::metadata(&p)
.and_then(|m| m.modified())
.map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
let age = now
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if idle_days > 0 && age <= threshold {
return Ok(false);
}
}
Ok(true)
}
pub fn check_session_worktree_removable(
root: &Path,
wt: &GitWorktreeInfo,
cwds: &Result<Vec<PathBuf>, String>,
idle_days: u64,
) -> Result<RemovalReason, KeptReason> {
let is_merged = if let Some(ref branch) = wt.branch {
is_branch_merged(root, branch)
} else if let Some(ref sha) = wt.head_sha {
is_commit_merged(root, sha)
} else {
false
};
if !is_merged {
return Err(KeptReason::NotMergedYet);
}
if has_dispatched_runs(&wt.path) {
let display_path = display_worktree_path(&wt.path, root);
return Err(KeptReason::HoldsRuns(display_path));
}
if !is_worktree_clean(&wt.path) {
return Err(KeptReason::UncommittedChanges);
}
match cwds {
Ok(list) => {
if is_worktree_in_use(&wt.path, list) {
return Err(KeptReason::InUse);
}
}
Err(err) => {
return Err(KeptReason::CannotCheckInUse(err.clone()));
}
}
match is_worktree_idle(&wt.path, idle_days) {
Ok(true) => {}
Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
Err(e) => {
return Err(KeptReason::Custom(format!(
"cannot tell when it was last used: {e}"
)))
}
}
let branch_label = wt.branch.clone().unwrap_or_else(|| {
wt.head_sha
.as_deref()
.map(|s| s[..s.len().min(7)].to_string())
.unwrap_or_else(|| "detached".to_string())
});
Ok(RemovalReason::SessionMerged(branch_label))
}
fn branch_checked_out_elsewhere(
worktrees: &[GitWorktreeInfo],
removed_wt_paths: &HashSet<PathBuf>,
current_wt_canon: &Path,
branch_name: &str,
) -> bool {
for wt in worktrees {
if !wt.path.exists() {
continue;
}
let wt_canon = wt
.path
.canonicalize()
.unwrap_or_else(|_| wt.path.to_path_buf());
if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
continue;
}
if wt.branch.as_deref() == Some(branch_name) {
return true;
}
}
false
}
pub fn clean_repo(
root: &Path,
older_than_days: u64,
dry_run: bool,
skip_id: Option<&str>,
quiet: bool,
) -> CleanRepoStats {
clean_repo_with_options(
root,
older_than_days,
dry_run,
skip_id,
quiet,
DEFAULT_SESSION_IDLE_DAYS,
None,
)
}
pub fn clean_repo_with_options(
root: &Path,
older_than_days: u64,
dry_run: bool,
skip_id: Option<&str>,
quiet: bool,
session_idle_days: u64,
process_cwds: Option<Result<Vec<PathBuf>, String>>,
) -> CleanRepoStats {
let mut removed_worktrees = 0;
let mut freed_bytes = 0;
let mut had_errors = false;
let mut ctx = CleanContext::new(root);
let ids = find_blyte_worktrees(root);
for id in ids {
if skip_id == Some(&id) {
continue;
}
let wt_path = root.join(".wt").join(&id);
match ctx.check_removable(&id, older_than_days) {
Err(kept_reason) => {
if !quiet {
println!("kept .wt/{id} ({kept_reason})");
}
}
Ok(removal_reason) => {
let is_res = ctx.is_research_run(&id);
if !is_res && has_uncommitted_changes(&wt_path) {
if !quiet {
println!("kept .wt/{id} (uncommitted changes)");
}
continue;
}
let size = dir_size(&wt_path);
let branch_name = format!("wip/{id}");
let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
let is_merged = branch_exists
&& (matches!(
removal_reason,
RemovalReason::Merged
| RemovalReason::MergedInto(_)
| RemovalReason::MergedThrough(_)
) || ctx.check_run_merged(&id).is_some());
if dry_run {
if !quiet {
println!(
"would remove .wt/{id} ({removal_reason}, {})",
format_size(size)
);
if is_merged {
println!("would delete branch {branch_name} (merged)");
}
}
freed_bytes += size;
removed_worktrees += 1;
} else {
if removal_reason == RemovalReason::ResearchReportInWorktree {
let src = wt_path.join("report.md");
let dst = root.join(".wt").join(format!("{id}.report.md"));
if let Err(err) = std::fs::copy(&src, &dst) {
eprintln!(
"error: could not copy {} to {}: {err}",
src.display(),
dst.display()
);
if !quiet {
println!("kept .wt/{id} (report copy failed)");
}
continue;
}
}
let removed_ok = if is_res {
std::fs::remove_dir_all(&wt_path).is_ok()
} else {
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
.current_dir(root)
.output();
let _ = std::process::Command::new("git")
.args(["worktree", "prune"])
.current_dir(root)
.output();
rm_out.map(|o| o.status.success()).unwrap_or(false)
};
if removed_ok {
freed_bytes += size;
removed_worktrees += 1;
if !quiet {
println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
}
if is_merged {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", &branch_name])
.current_dir(root)
.output();
if del_out.map(|o| o.status.success()).unwrap_or(false) {
ctx.wip_branch_tips.remove(&branch_name);
if !quiet {
println!("deleted branch {branch_name} (merged)");
}
}
}
} else if !quiet {
println!("kept .wt/{id} (worktree remove failed)");
}
}
}
}
}
if !is_linked_worktree(root) {
let all_worktrees = parse_worktree_list(root);
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let main_canon = all_worktrees
.first()
.map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
let mut session_indices: Vec<(String, usize)> = all_worktrees
.iter()
.enumerate()
.skip(1)
.filter_map(|(idx, wt)| {
if wt.is_bare || !wt.path.exists() {
return None;
}
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
return None;
}
if !is_session_worktree(root, &wt.path) {
return None;
}
Some((display_worktree_path(&wt.path, root), idx))
})
.collect();
session_indices.sort_by(|a, b| a.0.cmp(&b.0));
if !session_indices.is_empty() {
let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
let mut removed_wt_paths = HashSet::new();
for (display_path, idx) in session_indices {
let wt = &all_worktrees[idx];
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
match check_session_worktree_removable(root, wt, &cwds, session_idle_days) {
Err(kept_reason) => {
if !quiet {
println!("kept {display_path} ({kept_reason})");
}
}
Ok(removal_reason) => {
let size = dir_size(&wt.path);
if dry_run {
removed_wt_paths.insert(wt_canon.clone());
if !quiet {
println!(
"would remove {display_path} ({removal_reason}, {})",
format_size(size)
);
if let Some(ref branch_name) = wt.branch {
if !branch_checked_out_elsewhere(
&all_worktrees,
&removed_wt_paths,
&wt_canon,
branch_name,
) && get_branch_tip(root, branch_name).is_some()
{
println!("would delete branch {branch_name} (merged)");
}
}
}
freed_bytes += size;
removed_worktrees += 1;
} else {
let rm_out = std::process::Command::new("git")
.arg("worktree")
.arg("remove")
.arg(&wt.path)
.current_dir(root)
.output();
match rm_out {
Ok(o) if o.status.success() => {
let _ = std::process::Command::new("git")
.args(["worktree", "prune"])
.current_dir(root)
.output();
removed_wt_paths.insert(wt_canon.clone());
freed_bytes += size;
removed_worktrees += 1;
if !quiet {
println!(
"removed {display_path} ({removal_reason}, {})",
format_size(size)
);
}
if let Some(ref branch_name) = wt.branch {
if !branch_checked_out_elsewhere(
&all_worktrees,
&removed_wt_paths,
&wt_canon,
branch_name,
) && get_branch_tip(root, branch_name).is_some()
{
let del_out = std::process::Command::new("git")
.args(["branch", "-D", branch_name])
.current_dir(root)
.output();
match del_out {
Ok(o) if o.status.success() => {
ctx.wip_branch_tips.remove(branch_name);
if !quiet {
println!(
"deleted branch {branch_name} (merged)"
);
}
}
Ok(o) => {
eprintln!(
"error: could not delete branch {branch_name}: {}",
String::from_utf8_lossy(&o.stderr).trim()
);
had_errors = true;
}
Err(e) => {
eprintln!(
"error: could not delete branch {branch_name}: {e}"
);
had_errors = true;
}
}
}
}
}
Ok(o) => {
let stderr =
String::from_utf8_lossy(&o.stderr).trim().to_string();
let stdout =
String::from_utf8_lossy(&o.stdout).trim().to_string();
let msg = if !stderr.is_empty() {
stderr
} else if !stdout.is_empty() {
stdout
} else {
format!("exit status {}", o.status)
};
eprintln!("error: could not remove {display_path}: {msg}");
had_errors = true;
}
Err(e) => {
eprintln!("error: could not remove {display_path}: {e}");
had_errors = true;
}
}
}
}
}
}
}
}
if !quiet {
report_other_worktrees(root);
}
CleanRepoStats {
removed_worktrees,
freed_bytes,
had_errors,
}
}
#[derive(Debug)]
pub struct GitWorktreeInfo {
pub path: PathBuf,
pub head_sha: Option<String>,
pub branch: Option<String>,
pub is_detached: bool,
pub is_bare: bool,
}
pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
let out = std::process::Command::new("git")
.args(["worktree", "list", "--porcelain"])
.current_dir(root)
.output();
let Ok(o) = out else {
return Vec::new();
};
if !o.status.success() {
return Vec::new();
}
let text = String::from_utf8_lossy(&o.stdout);
let mut list = Vec::new();
let mut cur_path: Option<PathBuf> = None;
let mut cur_head: Option<String> = None;
let mut cur_branch: Option<String> = None;
let mut cur_detached = false;
let mut cur_bare = false;
let mut finish_entry = |path: &mut Option<PathBuf>,
head: &mut Option<String>,
branch: &mut Option<String>,
detached: &mut bool,
bare: &mut bool| {
if let Some(p) = path.take() {
list.push(GitWorktreeInfo {
path: p,
head_sha: head.take(),
branch: branch.take(),
is_detached: *detached,
is_bare: *bare,
});
*detached = false;
*bare = false;
}
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
} else if let Some(p) = line.strip_prefix("worktree ") {
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
cur_path = Some(PathBuf::from(p.trim()));
} else if let Some(h) = line.strip_prefix("HEAD ") {
cur_head = Some(h.trim().to_string());
} else if let Some(b) = line.strip_prefix("branch ") {
let b_str = b.trim();
let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
cur_branch = Some(b_name.to_string());
} else if line == "detached" {
cur_detached = true;
} else if line == "bare" {
cur_bare = true;
}
}
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
list
}
pub fn display_worktree_path(target: &Path, root: &Path) -> String {
let target_canon = target
.canonicalize()
.unwrap_or_else(|_| target.to_path_buf());
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
if !rel.as_os_str().is_empty() {
return rel.to_string_lossy().replace('\\', "/");
}
}
if target_canon != root_canon {
if let (Some(root_parent), Some(target_parent)) =
(root_canon.parent(), target_canon.parent())
{
if root_parent == target_parent {
if let Some(file_name) = target_canon.file_name() {
let rel = Path::new("..").join(file_name);
return rel.to_string_lossy().replace('\\', "/");
}
}
}
}
target_canon.to_string_lossy().replace('\\', "/")
}
pub fn is_linked_worktree(root: &Path) -> bool {
let git_dir_out = std::process::Command::new("git")
.args(["rev-parse", "--git-dir"])
.current_dir(root)
.output();
let common_dir_out = std::process::Command::new("git")
.args(["rev-parse", "--git-common-dir"])
.current_dir(root)
.output();
match (git_dir_out, common_dir_out) {
(Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
if gd_str == cd_str {
return false;
}
let gd_path = if Path::new(&gd_str).is_absolute() {
PathBuf::from(&gd_str)
} else {
root.join(&gd_str)
};
let cd_path = if Path::new(&cd_str).is_absolute() {
PathBuf::from(&cd_str)
} else {
root.join(&cd_str)
};
let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
gd_canon != cd_canon
}
_ => false,
}
}
pub fn has_wt_component(path: &Path) -> bool {
path.components().any(|c| c.as_os_str() == ".wt")
}
pub fn is_worktree_clean(wt_path: &Path) -> bool {
let out = std::process::Command::new("git")
.arg("--no-optional-locks")
.arg("-C")
.arg(wt_path.as_os_str())
.args(["status", "--porcelain", "-u"])
.output();
match out {
Ok(o) if o.status.success() => {
let stdout = String::from_utf8_lossy(&o.stdout);
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if line.len() < 3 {
return false;
}
let mut path_part = line[3..].trim();
if let Some((_, new_path)) = path_part.split_once(" -> ") {
path_part = new_path.trim();
}
let unquoted = path_part
.strip_prefix('"')
.and_then(|p| p.strip_suffix('"'))
.unwrap_or(path_part);
if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
return false;
}
}
true
}
_ => false,
}
}
pub fn report_other_worktrees(root: &Path) {
if is_linked_worktree(root) {
return;
}
let worktrees = parse_worktree_list(root);
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let main_canon = worktrees
.first()
.map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
let mut other_count = 0;
let mut other_bytes = 0;
for (idx, wt) in worktrees.into_iter().enumerate() {
if idx == 0 {
continue;
}
if wt.is_bare {
continue;
}
if !wt.path.exists() {
continue;
}
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
if wt_canon == root_canon || wt.path == root {
continue;
}
if Some(&wt_canon) == main_canon.as_ref() {
continue;
}
if has_wt_component(&wt.path)
|| has_wt_component(&wt_canon)
|| is_session_worktree(root, &wt.path)
{
continue;
}
let is_merged = if let Some(ref branch) = wt.branch {
is_branch_merged(root, branch)
} else if let Some(ref sha) = wt.head_sha {
is_commit_merged(root, sha)
} else {
false
};
if !is_merged {
continue;
}
if !is_worktree_clean(&wt.path) {
continue;
}
let size = dir_size(&wt.path);
let path_str = display_worktree_path(&wt.path, root);
let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
wt.head_sha
.as_deref()
.map(|s| &s[..s.len().min(7)])
.unwrap_or("detached")
});
println!(
"merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
format_size(size)
);
other_count += 1;
other_bytes += size;
}
if other_count > 0 {
println!(
"{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
format_size(other_bytes)
);
}
}
struct CleanLockGuard(PathBuf);
impl Drop for CleanLockGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
enum LockOutcome {
Acquired(CleanLockGuard),
AlreadyRunning,
Error(String),
}
fn acquire_clean_lock(root: &Path) -> LockOutcome {
use std::io::Write;
let wt_dir = root.join(".wt");
if let Err(e) = std::fs::create_dir_all(&wt_dir) {
return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
}
let lock_path = wt_dir.join("clean.lock");
let pid_str = format!("{}\n", std::process::id());
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(mut f) => {
if let Err(e) = f.write_all(pid_str.as_bytes()) {
let _ = std::fs::remove_file(&lock_path);
return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
}
LockOutcome::Acquired(CleanLockGuard(lock_path))
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let contents = match std::fs::read_to_string(&lock_path) {
Ok(c) => c,
Err(read_err) => {
return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
}
};
let old_pid: i64 = match contents.trim().parse() {
Ok(p) => p,
Err(parse_err) => {
return LockOutcome::Error(format!(
"{}: invalid pid: {parse_err}",
lock_path.display()
));
}
};
if is_pid_alive(old_pid) {
return LockOutcome::AlreadyRunning;
}
eprintln!(
"replacing stale {} from dead pid {old_pid}",
lock_path.display()
);
if let Err(rm_err) = std::fs::remove_file(&lock_path) {
return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
}
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(mut f) => {
if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
let _ = std::fs::remove_file(&lock_path);
return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
}
LockOutcome::Acquired(CleanLockGuard(lock_path))
}
Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
}
}
Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
}
}
pub fn run(args: &crate::cli::CleanArgs) -> i32 {
if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
return 2;
}
let repos = if args.all {
let tidy_res = if args.dry_run {
crate::registry::missing_registered()
} else {
crate::registry::prune_missing()
};
match tidy_res {
Ok(removed) if !removed.is_empty() => {
let verb = if args.dry_run {
"would forget"
} else {
"forgot"
};
let list = removed
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
println!(
"{verb} {} repositories that no longer exist: {list}",
removed.len()
);
}
Ok(_) => {}
Err(err) => {
let path = crate::registry::state_dir()
.map(|d| d.join("repos").display().to_string())
.unwrap_or_default();
eprintln!("error: could not tidy the repository registry {path}: {err}");
}
}
crate::registry::registered()
} else {
match find_repo_root() {
Ok(root) => vec![root],
Err(e) => {
eprintln!("error: {e}");
return 2;
}
}
};
let _lock_guard = if args.quiet {
let Some(root) = repos.first() else {
eprintln!("error: blyte clean --quiet found no repository to clean");
return 1;
};
match acquire_clean_lock(root) {
LockOutcome::Acquired(guard) => Some(guard),
LockOutcome::AlreadyRunning => return 0,
LockOutcome::Error(e) => {
eprintln!("error: {e}");
return 1;
}
}
} else {
None
};
let mut total_freed = 0;
let mut had_errors = false;
for repo in &repos {
let stats = clean_repo(
repo,
args.older_than,
args.dry_run,
args.skip.as_deref(),
args.quiet,
);
total_freed += stats.freed_bytes;
if stats.had_errors {
had_errors = true;
}
}
if !args.quiet {
if args.dry_run {
println!("would free {}", format_size(total_freed));
} else {
println!("freed {}", format_size(total_freed));
}
}
if had_errors {
1
} else {
0
}
}
fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", branch_name])
.current_dir(root)
.output()
.map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
if !del_out.status.success() {
return Err(format!(
"git branch -D {branch_name}: {}",
String::from_utf8_lossy(&del_out.stderr).trim()
));
}
Ok(())
}
pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
let wt_path = root.join(".wt").join(id);
let branch_name = format!("wip/{id}");
let mut ctx = CleanContext::new(root);
if wt_path.exists() {
let reason = match ctx.check_removable(id, u64::MAX) {
Ok(
r @ (RemovalReason::Merged
| RemovalReason::MergedInto(_)
| RemovalReason::MergedThrough(_)
| RemovalReason::NoChanges),
) => r,
Ok(
RemovalReason::SessionMerged(_)
| RemovalReason::Verdict(_)
| RemovalReason::OlderThan(_)
| RemovalReason::ResearchReport
| RemovalReason::ResearchReportInWorktree
| RemovalReason::ResearchEndedWithoutReport(_)
| RemovalReason::ResearchStoppedWithoutSummary(_),
)
| Err(_) => return Ok(None),
};
if has_uncommitted_changes(&wt_path) {
return Ok(None);
}
let wt_rel = format!(".wt/{id}");
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", &wt_rel])
.current_dir(root)
.output()
.map_err(|e| format!("git worktree remove {wt_rel}: {e}"))?;
if !rm_out.status.success() {
return Err(format!(
"git worktree remove {wt_rel}: {}",
String::from_utf8_lossy(&rm_out.stderr).trim()
));
}
if ctx.get_branch_tip(&branch_name).is_some() {
delete_wip_branch_strict(root, &branch_name)?;
}
return Ok(Some(reason.to_string()));
}
if ctx.get_branch_tip(&branch_name).is_some() {
if !is_branch_merged(root, &branch_name) {
return Ok(None);
}
let reason = ctx
.check_run_merged(id)
.unwrap_or(RemovalReason::Merged)
.to_string();
delete_wip_branch_strict(root, &branch_name)?;
return Ok(Some(reason));
}
Ok(None)
}
pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
let res: Result<(), std::io::Error> = (|| {
let wt_dir = root.join(".wt");
std::fs::create_dir_all(&wt_dir)?;
let log_file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(wt_dir.join("clean.log"))?;
let stderr_file = log_file.try_clone()?;
let exe = std::env::current_exe()?;
let mut cmd = std::process::Command::new(exe);
cmd.arg("clean").arg("--quiet");
if let Some(id) = skip_id {
cmd.arg("--skip").arg(id);
}
cmd.current_dir(root)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::from(log_file))
.stderr(std::process::Stdio::from(stderr_file));
let _child = cmd.spawn()?;
Ok(())
})();
if let Err(e) = res {
eprintln!("warning: could not start the background clean: {e}");
}
}
pub fn clean_on_review(root: &Path, id: &str) {
let wt_path = root.join(".wt").join(id);
if !wt_path.exists() {
spawn_background_clean(root, Some(id));
return;
}
let mut ctx = CleanContext::new(root);
let branch_name = format!("wip/{id}");
let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
let verdict_str = std::fs::read_to_string(&verdict_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("verdict")
.and_then(|s| s.as_str())
.map(|s| s.to_string())
})
.unwrap_or_default();
let is_res = ctx.is_research_run(id);
let removal_reason = match ctx.check_removable(id, 14) {
Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
_ => None,
};
let Some(removal_reason) = removal_reason else {
if verdict_str == "accepted" || verdict_str == "fixed" {
println!("worktree .wt/{id} kept until {branch_name} is merged");
}
spawn_background_clean(root, Some(id));
return;
};
if removal_reason == RemovalReason::ResearchReportInWorktree {
let src = wt_path.join("report.md");
let dst = root.join(".wt").join(format!("{id}.report.md"));
if let Err(err) = std::fs::copy(&src, &dst) {
eprintln!(
"error: could not copy {} to {}: {err}",
src.display(),
dst.display()
);
spawn_background_clean(root, Some(id));
return;
}
}
let removed_ok = if is_res {
std::fs::remove_dir_all(&wt_path).is_ok()
} else {
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
.current_dir(root)
.output();
let _ = std::process::Command::new("git")
.args(["worktree", "prune"])
.current_dir(root)
.output();
rm_out.map(|o| o.status.success()).unwrap_or(false)
};
if !removed_ok {
if verdict_str == "accepted" || verdict_str == "fixed" {
println!("worktree .wt/{id} kept until {branch_name} is merged");
}
spawn_background_clean(root, Some(id));
return;
}
if branch_exists {
let is_merged = ctx.check_run_merged(id).is_some();
if is_merged {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", &branch_name])
.current_dir(root)
.output();
if del_out.map(|o| o.status.success()).unwrap_or(false) {
ctx.wip_branch_tips.remove(&branch_name);
println!("removed .wt/{id}; branch {branch_name} deleted");
} else {
println!("removed .wt/{id}; branch {branch_name} kept");
}
} else {
println!("removed .wt/{id}; branch {branch_name} kept");
}
} else {
println!("removed .wt/{id}");
}
spawn_background_clean(root, Some(id));
}