1use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, PartialEq, Eq, Clone)]
7pub enum RemovalReason {
8 Merged,
9 MergedInto(String),
10 MergedThrough(String),
11 Verdict(String),
12 NoChanges,
13 ResearchReport,
14 OlderThan(u64),
15}
16
17impl std::fmt::Display for RemovalReason {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 match self {
20 Self::Merged => write!(f, "merged"),
21 Self::MergedInto(base) => write!(f, "merged into {base}"),
22 Self::MergedThrough(child) => write!(f, "merged through {child}"),
23 Self::Verdict(v) => {
24 if v.is_empty() {
25 write!(f, "verdict")
26 } else {
27 write!(f, "verdict {v}")
28 }
29 }
30 Self::NoChanges => write!(f, "no changes"),
31 Self::ResearchReport => write!(f, "research report"),
32 Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
33 }
34 }
35}
36
37#[derive(Debug, PartialEq, Eq)]
38pub enum KeptReason {
39 UncommittedChanges,
40 Running,
41 NoVerdict,
42 NotMergedYet,
43 NoReport,
44 Custom(String),
45}
46
47impl std::fmt::Display for KeptReason {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 match self {
50 Self::UncommittedChanges => write!(f, "uncommitted changes"),
51 Self::Running => write!(f, "running"),
52 Self::NoVerdict => write!(f, "no verdict"),
53 Self::NotMergedYet => write!(f, "not merged yet"),
54 Self::NoReport => write!(f, "no report"),
55 Self::Custom(s) => write!(f, "{s}"),
56 }
57 }
58}
59
60pub fn dir_size(path: &Path) -> u64 {
62 let mut total = 0;
63 let Ok(meta) = std::fs::symlink_metadata(path) else {
64 return 0;
65 };
66 if meta.file_type().is_symlink() {
67 return 0;
68 }
69 if meta.is_file() {
70 return meta.len();
71 }
72 if meta.is_dir() {
73 let Ok(entries) = std::fs::read_dir(path) else {
74 return 0;
75 };
76 for entry in entries.flatten() {
77 let Ok(ft) = entry.file_type() else {
78 continue;
79 };
80 if ft.is_symlink() {
81 continue;
82 } else if ft.is_dir() {
83 total += dir_size(&entry.path());
84 } else if ft.is_file() {
85 if let Ok(m) = entry.metadata() {
86 total += m.len();
87 }
88 }
89 }
90 }
91 total
92}
93
94pub fn format_size(bytes: u64) -> String {
96 const KB: f64 = 1024.0;
97 const MB: f64 = 1024.0 * 1024.0;
98 const GB: f64 = 1024.0 * 1024.0 * 1024.0;
99 let b = bytes as f64;
100 let (val, unit) = if b >= GB {
101 (b / GB, "GB")
102 } else if b >= MB {
103 (b / MB, "MB")
104 } else if b >= KB {
105 (b / KB, "KB")
106 } else {
107 return format!("{bytes} B");
108 };
109
110 let s = if val >= 100.0 {
111 format!("{val:.0}")
112 } else {
113 let formatted = format!("{val:.1}");
114 formatted
115 .strip_suffix(".0")
116 .unwrap_or(&formatted)
117 .to_string()
118 };
119 format!("{s} {unit}")
120}
121
122pub fn is_pid_alive(pid: i64) -> bool {
124 if pid <= 0 {
125 return false;
126 }
127 let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
128 if ret == 0 {
129 true
130 } else {
131 std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
132 }
133}
134
135pub fn find_repo_root() -> Result<PathBuf, String> {
137 let out = std::process::Command::new("git")
138 .args(["rev-parse", "--show-toplevel"])
139 .output()
140 .map_err(|e| format!("git not found: {e}"))?;
141 if !out.status.success() {
142 return Err("not a git repository".to_string());
143 }
144 let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
145 if has_wt_component(&root) {
146 if let Some(wt_parent) = root.parent().and_then(|p| p.parent()) {
147 if root
148 .parent()
149 .and_then(|p| p.file_name())
150 .is_some_and(|n| n == ".wt")
151 {
152 return Ok(wt_parent.to_path_buf());
153 }
154 }
155 if let Some(main) = crate::config::main_checkout(&root) {
156 return Ok(main);
157 }
158 }
159 Ok(root)
160}
161
162pub fn is_research(root: &Path, id: &str) -> bool {
164 let start_path = root.join(".wt").join(format!("{id}.start.json"));
165 if let Ok(s) = std::fs::read_to_string(&start_path) {
166 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
167 return val
168 .get("research")
169 .and_then(|r| r.as_bool())
170 .unwrap_or(false);
171 }
172 }
173 false
174}
175
176pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
178 let out = std::process::Command::new("git")
179 .args([
180 "-C",
181 wt_path.to_str().unwrap_or(""),
182 "status",
183 "--porcelain",
184 ])
185 .output();
186 match out {
187 Ok(o) if o.status.success() => {
188 !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
189 }
190 _ => true,
191 }
192}
193
194fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
195 let out = std::process::Command::new("git")
196 .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
197 .current_dir(root)
198 .output()
199 .ok()?;
200 if out.status.success() {
201 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
202 } else {
203 None
204 }
205}
206
207fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
208 let cherry_out = std::process::Command::new("git")
209 .args(["cherry", target, commit_sha])
210 .current_dir(root)
211 .output();
212 if let Ok(o) = cherry_out {
213 if o.status.success() {
214 let s = String::from_utf8_lossy(&o.stdout);
215 let lines: Vec<&str> = s
216 .lines()
217 .map(|l| l.trim())
218 .filter(|l| !l.is_empty())
219 .collect();
220 if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
221 return true;
222 }
223 }
224 }
225 false
226}
227
228fn is_merge_tree_merged_into_target(
229 root: &Path,
230 commit_sha: &str,
231 target: &str,
232 target_tree: Option<&str>,
233) -> bool {
234 let target_tree_sha = match target_tree {
235 Some(t) => Some(t.to_string()),
236 None => git_tree_sha(root, target),
237 };
238 if let Some(target_tree_sha) = target_tree_sha {
239 let merge_tree_out = std::process::Command::new("git")
240 .args(["merge-tree", "--write-tree", target, commit_sha])
241 .current_dir(root)
242 .output();
243 if let Ok(mt_o) = merge_tree_out {
244 if mt_o.status.success() {
245 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
246 if let Some(first_line) = mt_stdout.lines().next() {
247 if first_line.trim() == target_tree_sha {
248 return true;
249 }
250 }
251 }
252 }
253 }
254 false
255}
256
257fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
258 let s = val.get("started_at")?;
259 if let Some(n) = s.as_u64() {
260 Some(n)
261 } else if let Some(n) = s.as_i64() {
262 if n >= 0 {
263 Some(n as u64)
264 } else {
265 None
266 }
267 } else if let Some(f) = s.as_f64() {
268 if f >= 0.0 {
269 Some(f as u64)
270 } else {
271 None
272 }
273 } else if let Some(st) = s.as_str() {
274 st.parse::<u64>().ok()
275 } else {
276 None
277 }
278}
279
280fn check_history_merged(
281 root: &Path,
282 tip_sha: &str,
283 target: &str,
284 started_at: Option<&serde_json::Value>,
285) -> bool {
286 let mb_out = std::process::Command::new("git")
287 .args(["merge-base", target, tip_sha])
288 .current_dir(root)
289 .output();
290 let Ok(mb_o) = mb_out else {
291 return false;
292 };
293 if !mb_o.status.success() {
294 return false;
295 }
296 let merge_base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
297 if merge_base.is_empty() {
298 return false;
299 }
300
301 let diff_out = std::process::Command::new("git")
302 .args(["diff", "--name-only", &merge_base, tip_sha])
303 .current_dir(root)
304 .output();
305 let Ok(diff_o) = diff_out else {
306 return false;
307 };
308 if !diff_o.status.success() {
309 return false;
310 }
311 let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
312 .lines()
313 .map(|l| l.trim().to_string())
314 .filter(|l| !l.is_empty())
315 .collect();
316
317 if files.is_empty() {
318 return false;
319 }
320
321 let since_arg = started_at
322 .and_then(|v| {
323 if let Some(n) = v.as_i64() {
324 if n >= 100_000_000 {
325 Some(format!("--since={n}"))
326 } else {
327 Some("--since=1970-01-01T00:00:00Z".to_string())
328 }
329 } else if let Some(n) = v.as_u64() {
330 if n >= 100_000_000 {
331 Some(format!("--since={n}"))
332 } else {
333 Some("--since=1970-01-01T00:00:00Z".to_string())
334 }
335 } else {
336 v.as_str().map(|s| format!("--since={s}"))
337 }
338 })
339 .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
340
341 let mut cmd = std::process::Command::new("git");
342 cmd.args([
343 "rev-list",
344 "--first-parent",
345 &since_arg,
346 "-n",
347 "20",
348 target,
349 "--",
350 ]);
351 for f in &files {
352 cmd.arg(f);
353 }
354 cmd.current_dir(root);
355 let Ok(rev_o) = cmd.output() else {
356 return false;
357 };
358 if !rev_o.status.success() {
359 return false;
360 }
361
362 let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
363 .lines()
364 .map(|l| l.trim().to_string())
365 .filter(|l| !l.is_empty())
366 .collect();
367
368 for c in commits {
369 let mt_out = std::process::Command::new("git")
370 .args(["merge-tree", "--write-tree", &c, tip_sha])
371 .current_dir(root)
372 .output();
373 let Ok(mt_o) = mt_out else {
374 continue;
375 };
376 if !mt_o.status.success() {
377 continue;
378 }
379 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
380 let Some(first_line) = mt_stdout.lines().next() else {
381 continue;
382 };
383 let mt_tree = first_line.trim();
384
385 if let Some(c_tree) = git_tree_sha(root, &c) {
386 if mt_tree == c_tree {
387 return true;
388 }
389 }
390 }
391
392 false
393}
394
395pub struct CleanContext<'a> {
397 pub root: &'a Path,
398 pub start_files: HashMap<String, serde_json::Value>,
399 pub all_run_ids: Vec<String>,
400 pub wip_branch_tips: HashMap<String, String>,
401 pub default_branch: String,
402 pub origin_default: Option<String>,
403 pub default_tree: Option<String>,
404 pub origin_default_tree: Option<String>,
405 pub wip_contains_cache: HashMap<String, Vec<String>>,
406 pub merged_cache: HashMap<String, Option<RemovalReason>>,
407 pub branch_contains_calls: usize,
408 pub quiet: bool,
409 pub cherry_pick_set: Option<HashSet<String>>,
410 pub rev_list_cache: HashMap<String, Vec<String>>,
411 pub ancestor_cache: HashMap<(String, String), bool>,
412}
413
414impl<'a> CleanContext<'a> {
415 pub fn new(root: &'a Path) -> Self {
416 let mut start_files = HashMap::new();
417 let mut all_run_ids = Vec::new();
418 let wt_dir = root.join(".wt");
419 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
420 for entry in entries.flatten() {
421 let name = entry.file_name().to_string_lossy().to_string();
422 if let Some(id) = name.strip_suffix(".start.json") {
423 all_run_ids.push(id.to_string());
424 if let Ok(content) = std::fs::read_to_string(entry.path()) {
425 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
426 start_files.insert(id.to_string(), val);
427 }
428 }
429 }
430 }
431 }
432 all_run_ids.sort();
433
434 let mut wip_branch_tips = HashMap::new();
435 let ref_out = std::process::Command::new("git")
436 .args([
437 "for-each-ref",
438 "--format=%(refname:short) %(objectname)",
439 "refs/heads/wip/",
440 ])
441 .current_dir(root)
442 .output();
443 if let Ok(o) = ref_out {
444 if o.status.success() {
445 for line in String::from_utf8_lossy(&o.stdout).lines() {
446 let mut parts = line.split_whitespace();
447 if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
448 wip_branch_tips.insert(refname.to_string(), sha.to_string());
449 }
450 }
451 }
452 }
453
454 let default_branch = find_default_branch(root);
455 let name = default_branch
456 .strip_prefix("origin/")
457 .unwrap_or(&default_branch);
458 let remote = format!("origin/{name}");
459 let origin_default = if remote != default_branch
460 && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
461 {
462 Some(remote)
463 } else {
464 None
465 };
466
467 let default_tree = git_tree_sha(root, &default_branch);
468 let origin_default_tree = origin_default
469 .as_deref()
470 .and_then(|r| git_tree_sha(root, r));
471
472 Self {
473 root,
474 start_files,
475 all_run_ids,
476 wip_branch_tips,
477 default_branch,
478 origin_default,
479 default_tree,
480 origin_default_tree,
481 wip_contains_cache: HashMap::new(),
482 merged_cache: HashMap::new(),
483 branch_contains_calls: 0,
484 quiet: false,
485 cherry_pick_set: None,
486 rev_list_cache: HashMap::new(),
487 ancestor_cache: HashMap::new(),
488 }
489 }
490
491 pub fn set_quiet(&mut self, quiet: bool) {
492 self.quiet = quiet;
493 }
494
495 fn compute_cherry_pick_set(&self) -> HashSet<String> {
496 let unremoved_ids = find_blyte_worktrees(self.root);
497 let candidate_ids: &[String] = if unremoved_ids.is_empty() {
498 &self.all_run_ids
499 } else {
500 &unremoved_ids
501 };
502
503 let mut min_started_at: Option<u64> = None;
504 let mut all_valid = true;
505
506 for id in candidate_ids {
507 let start_val = self.start_files.get(id);
508 let parsed = start_val.and_then(parse_started_at);
509 match parsed {
510 Some(ts) => {
511 min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
512 }
513 None => {
514 all_valid = false;
515 }
516 }
517 }
518
519 let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
520 if min_ts >= 86_400 + 100_000_000 {
521 format!("--since={}", min_ts - 86_400)
522 } else {
523 "--since=1970-01-01T00:00:00Z".to_string()
524 }
525 } else {
526 "--since=1970-01-01T00:00:00Z".to_string()
527 };
528
529 let mut targets = Vec::new();
530 let mut seen = HashSet::new();
531
532 if git_ok(
533 self.root,
534 &["rev-parse", "--verify", "--quiet", &self.default_branch],
535 ) && seen.insert(self.default_branch.clone())
536 {
537 targets.push(self.default_branch.clone());
538 }
539
540 if let Some(ref origin_def) = self.origin_default {
541 if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
542 && seen.insert(origin_def.clone())
543 {
544 targets.push(origin_def.clone());
545 }
546 }
547
548 for id in &self.all_run_ids {
549 if let Some(base_str) = self
550 .start_files
551 .get(id)
552 .and_then(|s| s.get("base"))
553 .and_then(|b| b.as_str())
554 {
555 if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
556 for bt in base_targets {
557 if seen.insert(bt.clone()) {
558 targets.push(bt);
559 }
560 }
561 }
562 }
563 }
564
565 if targets.is_empty() {
566 return HashSet::new();
567 }
568
569 let mut cmd = std::process::Command::new("git");
570 cmd.args(["log", "--format=%B", &since_arg]);
571 for t in &targets {
572 cmd.arg(t);
573 }
574 cmd.current_dir(self.root);
575
576 let mut set = HashSet::new();
577 if let Ok(o) = cmd.output() {
578 if o.status.success() {
579 let text = String::from_utf8_lossy(&o.stdout);
580 for line in text.lines() {
581 let trimmed = line.trim();
582 if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
583 if let Some(sha) = rest.strip_suffix(')') {
584 let sha = sha.trim();
585 if is_commit_id(sha) {
586 set.insert(sha.to_lowercase());
587 }
588 }
589 }
590 }
591 }
592 }
593
594 set
595 }
596
597 pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
598 if self.cherry_pick_set.is_none() {
599 let set = self.compute_cherry_pick_set();
600 self.cherry_pick_set = Some(set);
601 }
602 self.cherry_pick_set.as_ref().unwrap()
603 }
604
605 fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
606 let key = (commit_sha.to_string(), target.to_string());
607 if let Some(&cached) = self.ancestor_cache.get(&key) {
608 return cached;
609 }
610 let is_anc = std::process::Command::new("git")
611 .args(["merge-base", "--is-ancestor", commit_sha, target])
612 .current_dir(self.root)
613 .output()
614 .map(|c| c.status.success())
615 .unwrap_or(false);
616 self.ancestor_cache.insert(key, is_anc);
617 is_anc
618 }
619
620 fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
621 let def = self.default_branch.clone();
622 if self.is_ancestor_of_target(commit_sha, &def) {
623 return true;
624 }
625 if let Some(origin_def) = self.origin_default.clone() {
626 if self.is_ancestor_of_target(commit_sha, &origin_def) {
627 return true;
628 }
629 }
630 false
631 }
632
633 fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
634 if let Some(cached) = self.rev_list_cache.get(tip_sha) {
635 return cached.clone();
636 }
637 let out = std::process::Command::new("git")
638 .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
639 .current_dir(self.root)
640 .output();
641 let commits: Vec<String> = match out {
642 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
643 .lines()
644 .map(|l| l.trim().to_lowercase())
645 .filter(|l| !l.is_empty())
646 .collect(),
647 _ => Vec::new(),
648 };
649 self.rev_list_cache
650 .insert(tip_sha.to_string(), commits.clone());
651 commits
652 }
653
654 fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
655 let commits = self.get_run_commits_against_default(tip_sha);
656 if commits.is_empty() {
657 return false;
658 }
659 let cherry_set = self.get_cherry_pick_set();
660 commits.iter().all(|c| cherry_set.contains(c))
661 }
662
663 pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
664 if let Some(sha) = self.wip_branch_tips.get(branch_name) {
665 return Some(sha.clone());
666 }
667 get_branch_tip(self.root, branch_name)
668 }
669
670 pub fn is_research_run(&self, id: &str) -> bool {
671 self.start_files
672 .get(id)
673 .and_then(|v| v.get("research"))
674 .and_then(|r| r.as_bool())
675 .unwrap_or_else(|| is_research(self.root, id))
676 }
677
678 pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
679 if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
680 return cached.clone();
681 }
682
683 self.branch_contains_calls += 1;
684
685 let out = std::process::Command::new("git")
686 .args([
687 "branch",
688 "--list",
689 "--format=%(refname:short)",
690 "wip/*",
691 "--contains",
692 tip_sha,
693 ])
694 .current_dir(self.root)
695 .output();
696
697 let mut branches = Vec::new();
698 if let Ok(o) = out {
699 if o.status.success() {
700 for line in String::from_utf8_lossy(&o.stdout).lines() {
701 let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
702 if !trimmed.is_empty() {
703 branches.push(trimmed.to_string());
704 }
705 }
706 }
707 }
708 self.wip_contains_cache
709 .insert(tip_sha.to_string(), branches.clone());
710 branches
711 }
712
713 pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
714 let mut children = Vec::new();
715 let mut seen = HashSet::new();
716
717 for (candidate_id, start_val) in &self.start_files {
719 if candidate_id == id {
720 continue;
721 }
722 if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
723 let base_str = base_str.trim().trim_end_matches('/');
724 let target1 = format!("wip/{id}");
725 let target2 = format!("refs/heads/wip/{id}");
726 if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
727 {
728 children.push(candidate_id.clone());
729 }
730 }
731 }
732
733 if !tip_sha.is_empty() {
735 let tip_sha_owned = tip_sha.to_string();
736 let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
737 for b in containing_branches {
738 let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
739 if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
740 if candidate_id == id {
741 continue;
742 }
743 if !self.start_files.contains_key(candidate_id) {
744 continue;
745 }
746 let has_base = self
747 .start_files
748 .get(candidate_id)
749 .and_then(|val| val.get("base"))
750 .is_some_and(|b| !b.is_null());
751 if !has_base && seen.insert(candidate_id.to_string()) {
752 children.push(candidate_id.to_string());
753 }
754 }
755 }
756 }
757
758 children.sort();
759 children
760 }
761
762 pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
763 if self.is_research_run(child) {
764 return false;
765 }
766
767 let branch_name = format!("wip/{child}");
768 let tip = self.get_branch_tip(&branch_name);
769
770 if tip.is_none() {
771 let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
772 let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
773 let v = std::fs::read_to_string(&verdict_path)
774 .ok()
775 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
776 .and_then(|v| {
777 v.get("verdict")
778 .and_then(|s| s.as_str())
779 .map(|s| s.to_string())
780 })
781 .unwrap_or_default();
782 (v == "accepted" || v == "fixed", v == "redone")
783 } else {
784 (false, false)
785 };
786
787 if is_redone {
788 return false;
789 }
790
791 let summary_path = self.root.join(".wt").join(format!("{child}.json"));
792 let is_verified = std::fs::read_to_string(&summary_path)
793 .ok()
794 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
795 .and_then(|v| {
796 v.get("outcome")
797 .and_then(|s| s.as_str())
798 .map(|s| s == "verified")
799 })
800 .unwrap_or(false);
801
802 let wt_gone = !self.root.join(".wt").join(child).is_dir();
803
804 return has_accepted_verdict || (is_verified && wt_gone);
805 }
806
807 self.check_run_merged_internal(child, visited).is_some()
808 }
809
810 pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
811 let mut visited = HashSet::new();
812 self.check_run_merged_internal(id, &mut visited)
813 }
814
815 fn check_run_merged_internal(
816 &mut self,
817 id: &str,
818 visited: &mut HashSet<String>,
819 ) -> Option<RemovalReason> {
820 if visited.contains(id) {
821 return None;
822 }
823
824 if let Some(cached) = self.merged_cache.get(id) {
825 return cached.clone();
826 }
827
828 visited.insert(id.to_string());
829
830 let branch_name = format!("wip/{id}");
831 let tip_sha = self.get_branch_tip(&branch_name);
832
833 let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
834
835 visited.remove(id);
836
837 self.merged_cache.insert(id.to_string(), result.clone());
838 result
839 }
840
841 fn decide_run_merged(
842 &mut self,
843 id: &str,
844 tip_sha: Option<&str>,
845 visited: &mut HashSet<String>,
846 ) -> Option<RemovalReason> {
847 let base_opt = self.start_files.get(id).and_then(|s| {
848 s.get("base")
849 .and_then(|b| b.as_str())
850 .map(|b| b.to_string())
851 });
852 let base_targets = base_opt
853 .as_deref()
854 .and_then(|b| resolve_base_targets(self.root, b));
855 let started_at = self
856 .start_files
857 .get(id)
858 .and_then(|s| s.get("started_at"))
859 .cloned();
860
861 if let Some(tip_sha) = tip_sha {
862 if self.is_ancestor_of_default(tip_sha) {
864 return Some(RemovalReason::Merged);
865 }
866
867 if self.is_in_cherry_pick_record(tip_sha) {
869 return Some(RemovalReason::Merged);
870 }
871
872 if let Some((ref display_name, ref targets)) = base_targets {
874 for target in targets {
875 if self.is_ancestor_of_target(tip_sha, target) {
876 return Some(RemovalReason::MergedInto(display_name.clone()));
877 }
878 if !self.quiet {
879 if is_cherry_merged_into_target(self.root, tip_sha, target) {
880 return Some(RemovalReason::MergedInto(display_name.clone()));
881 }
882 if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
883 return Some(RemovalReason::MergedInto(display_name.clone()));
884 }
885 }
886 }
887 }
888 }
889
890 let children = self.get_children_of(id, tip_sha.unwrap_or(""));
892 for child in children {
893 if visited.contains(&child) {
894 continue;
895 }
896 if self.is_child_run_merged(&child, visited) {
897 return Some(RemovalReason::MergedThrough(child));
898 }
899 }
900
901 if self.quiet {
905 if let Some(tip_sha) = tip_sha {
906 return self.squash_merged_reason(tip_sha, &base_targets);
907 }
908 return None;
909 }
910
911 if let Some(tip_sha) = tip_sha {
912 if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
914 return Some(RemovalReason::Merged);
915 }
916 if let Some(ref origin_def) = self.origin_default {
917 if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
918 return Some(RemovalReason::Merged);
919 }
920 }
921
922 if is_merge_tree_merged_into_target(
924 self.root,
925 tip_sha,
926 &self.default_branch,
927 self.default_tree.as_deref(),
928 ) {
929 return Some(RemovalReason::Merged);
930 }
931 if let Some(ref origin_def) = self.origin_default {
932 if is_merge_tree_merged_into_target(
933 self.root,
934 tip_sha,
935 origin_def,
936 self.origin_default_tree.as_deref(),
937 ) {
938 return Some(RemovalReason::Merged);
939 }
940 }
941
942 if check_history_merged(
944 self.root,
945 tip_sha,
946 &self.default_branch,
947 started_at.as_ref(),
948 ) {
949 return Some(RemovalReason::Merged);
950 }
951 if let Some(ref origin_def) = self.origin_default {
952 if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
953 return Some(RemovalReason::Merged);
954 }
955 }
956 if let Some((ref display_name, ref targets)) = base_targets {
957 for target in targets {
958 if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
959 return Some(RemovalReason::MergedInto(display_name.clone()));
960 }
961 }
962 }
963
964 if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
966 return Some(reason);
967 }
968 }
969
970 None
971 }
972
973 fn squash_merged_reason(
974 &self,
975 tip_sha: &str,
976 base_targets: &Option<(String, Vec<String>)>,
977 ) -> Option<RemovalReason> {
978 if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
979 return Some(RemovalReason::Merged);
980 }
981 if let Some(ref origin_def) = self.origin_default {
982 if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
983 return Some(RemovalReason::Merged);
984 }
985 }
986 if let Some((ref display_name, ref targets)) = base_targets {
987 for target in targets {
988 if is_squash_merged_into_target(self.root, tip_sha, target) {
989 return Some(RemovalReason::MergedInto(display_name.clone()));
990 }
991 }
992 }
993 None
994 }
995
996 pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
997 let branch_name = format!("wip/{id}");
998 let tip_sha = self.get_branch_tip(&branch_name);
999 let mut visited = HashSet::new();
1000 visited.insert(id.to_string());
1001 let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1002 children
1003 .into_iter()
1004 .find(|child| self.is_child_run_merged(child, &mut visited))
1005 }
1006
1007 pub fn check_removable(
1008 &mut self,
1009 id: &str,
1010 older_than_days: u64,
1011 ) -> Result<RemovalReason, KeptReason> {
1012 let wt_dir = self.root.join(".wt");
1013 let summary_path = wt_dir.join(format!("{id}.json"));
1014 let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1015 let report_path = wt_dir.join(format!("{id}.report.md"));
1016
1017 let start_json = self.start_files.get(id);
1018 let summary_exists = summary_path.is_file();
1019
1020 if let Some(start) = start_json {
1022 if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1023 if is_pid_alive(pid) {
1024 if !summary_exists {
1025 return Err(KeptReason::Running);
1026 }
1027 let Some(started_at) = parse_started_at(start) else {
1028 return Err(KeptReason::Running);
1029 };
1030 let summary_mtime = std::fs::metadata(&summary_path)
1031 .ok()
1032 .and_then(|m| m.modified().ok())
1033 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1034 .map(|d| d.as_secs());
1035 if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1036 return Err(KeptReason::Running);
1037 }
1038 }
1039 }
1040 }
1041
1042 let is_res = self.is_research_run(id);
1043
1044 let verdict_str = if verdict_path.is_file() {
1046 std::fs::read_to_string(&verdict_path)
1047 .ok()
1048 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1049 .and_then(|v| {
1050 v.get("verdict")
1051 .and_then(|s| s.as_str())
1052 .map(|s| s.to_string())
1053 })
1054 .unwrap_or_default()
1055 } else {
1056 String::new()
1057 };
1058
1059 if verdict_str == "redone" {
1060 return Ok(RemovalReason::Verdict("redone".to_string()));
1061 }
1062
1063 if summary_exists {
1064 if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1065 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1066 if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1067 return Ok(RemovalReason::NoChanges);
1068 }
1069 }
1070 }
1071 }
1072
1073 if is_res && report_path.is_file() {
1075 return Ok(RemovalReason::ResearchReport);
1076 }
1077
1078 if !is_res {
1080 if let Some(reason) = self.check_run_merged(id) {
1081 return Ok(reason);
1082 }
1083 }
1084
1085 if summary_exists {
1087 if let Ok(meta) = std::fs::metadata(&summary_path) {
1088 if let Ok(mtime) = meta.modified() {
1089 let age = std::time::SystemTime::now()
1090 .duration_since(mtime)
1091 .unwrap_or(std::time::Duration::ZERO);
1092 if age >= std::time::Duration::from_secs(older_than_days * 86400) {
1093 return Ok(RemovalReason::OlderThan(older_than_days));
1094 }
1095 }
1096 }
1097 }
1098
1099 if !verdict_str.is_empty() {
1101 return Err(KeptReason::NotMergedYet);
1102 }
1103
1104 if is_res {
1105 Err(KeptReason::NoReport)
1106 } else {
1107 Err(KeptReason::NoVerdict)
1108 }
1109 }
1110}
1111
1112pub fn check_removable(
1114 root: &Path,
1115 id: &str,
1116 older_than_days: u64,
1117) -> Result<RemovalReason, KeptReason> {
1118 let mut ctx = CleanContext::new(root);
1119 ctx.check_removable(id, older_than_days)
1120}
1121
1122pub fn find_default_branch(root: &Path) -> String {
1124 let sym_out = std::process::Command::new("git")
1125 .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1126 .current_dir(root)
1127 .output();
1128 if let Ok(o) = sym_out {
1129 if o.status.success() {
1130 let target = String::from_utf8_lossy(&o.stdout);
1131 let target = target.trim();
1132 let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1133 let local_check = std::process::Command::new("git")
1134 .args([
1135 "rev-parse",
1136 "--verify",
1137 &format!("refs/heads/{branch_name}"),
1138 ])
1139 .current_dir(root)
1140 .output();
1141 if local_check.map(|c| c.status.success()).unwrap_or(false) {
1142 return branch_name.to_string();
1143 }
1144 let remote_check = std::process::Command::new("git")
1145 .args(["rev-parse", "--verify", target])
1146 .current_dir(root)
1147 .output();
1148 if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1149 return target.to_string();
1150 }
1151 return branch_name.to_string();
1152 }
1153 }
1154
1155 let main_check = std::process::Command::new("git")
1156 .args(["rev-parse", "--verify", "refs/heads/main"])
1157 .current_dir(root)
1158 .output();
1159 if main_check.map(|c| c.status.success()).unwrap_or(false) {
1160 return "main".to_string();
1161 }
1162
1163 let master_check = std::process::Command::new("git")
1164 .args(["rev-parse", "--verify", "refs/heads/master"])
1165 .current_dir(root)
1166 .output();
1167 if master_check.map(|c| c.status.success()).unwrap_or(false) {
1168 return "master".to_string();
1169 }
1170
1171 "main".to_string()
1172}
1173
1174fn is_commit_id(s: &str) -> bool {
1176 (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1177}
1178
1179pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1184 let base = base.trim();
1185 if base.is_empty() {
1186 return None;
1187 }
1188
1189 if base == "HEAD"
1190 || base.starts_with("HEAD~")
1191 || base.starts_with("HEAD^")
1192 || base.starts_with("HEAD@")
1193 || base.starts_with("HEAD:")
1194 {
1195 return None;
1196 }
1197
1198 if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1199 return None;
1200 }
1201
1202 if is_commit_id(base) {
1203 return None;
1204 }
1205
1206 let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1207 stripped
1208 } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1209 stripped
1210 } else {
1211 base
1212 };
1213
1214 let is_wip = clean == "wip"
1215 || clean.starts_with("wip/")
1216 || clean == "origin/wip"
1217 || clean.starts_with("origin/wip/");
1218 if is_wip {
1219 return None;
1220 }
1221
1222 let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1223 if without_origin.is_empty()
1224 || without_origin == "wip"
1225 || without_origin.starts_with("wip/")
1226 || without_origin == "HEAD"
1227 || without_origin.starts_with("HEAD~")
1228 || without_origin.starts_with("HEAD^")
1229 || is_commit_id(without_origin)
1230 {
1231 return None;
1232 }
1233 let cand1 = format!("refs/remotes/{clean}");
1234 let cand2 = format!("refs/heads/{without_origin}");
1235 (without_origin.to_string(), vec![cand1, cand2])
1236 } else {
1237 let cand1 = format!("refs/heads/{clean}");
1238 let cand2 = format!("refs/remotes/origin/{clean}");
1239 (clean.to_string(), vec![cand1, cand2])
1240 };
1241
1242 let mut resolved = Vec::new();
1243 for cand in candidates {
1244 if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1245 resolved.push(cand);
1246 }
1247 }
1248
1249 if resolved.is_empty() {
1250 None
1251 } else {
1252 Some((display_name, resolved))
1253 }
1254}
1255
1256pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1258 let start_path = root.join(".wt").join(format!("{id}.start.json"));
1259 std::fs::read_to_string(&start_path)
1260 .ok()
1261 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1262 .and_then(|v| {
1263 v.get("base")
1264 .and_then(|b| b.as_str())
1265 .map(|s| s.to_string())
1266 })
1267}
1268
1269pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1271 let check = std::process::Command::new("git")
1272 .args([
1273 "rev-parse",
1274 "--verify",
1275 &format!("refs/heads/{branch_name}"),
1276 ])
1277 .current_dir(root)
1278 .output()
1279 .ok()?;
1280 if !check.status.success() {
1281 return None;
1282 }
1283
1284 let tip_out = std::process::Command::new("git")
1285 .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1286 .current_dir(root)
1287 .output()
1288 .ok()?;
1289 if tip_out.status.success() {
1290 Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1291 } else {
1292 None
1293 }
1294}
1295
1296pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1303 let mut ctx = CleanContext::new(root);
1304 if let Some(id) = branch_name.strip_prefix("wip/") {
1305 ctx.check_run_merged(id).is_some()
1306 } else {
1307 is_branch_merged_with_targets(root, branch_name, &[])
1308 }
1309}
1310
1311pub fn is_branch_merged_with_targets(
1313 root: &Path,
1314 branch_name: &str,
1315 extra_targets: &[&str],
1316) -> bool {
1317 let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1318 return false;
1319 };
1320
1321 is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1322}
1323
1324pub fn is_branch_merged_with_extra_targets(
1326 root: &Path,
1327 branch_name: &str,
1328 extra_targets: &[&str],
1329) -> bool {
1330 is_branch_merged_with_targets(root, branch_name, extra_targets)
1331}
1332
1333pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1339 is_commit_merged_with_targets(root, commit_sha, &[])
1340}
1341
1342pub fn is_commit_merged_with_targets(
1344 root: &Path,
1345 commit_sha: &str,
1346 extra_targets: &[&str],
1347) -> bool {
1348 let default_branch = find_default_branch(root);
1349 let name = default_branch
1352 .strip_prefix("origin/")
1353 .unwrap_or(&default_branch);
1354 let remote = format!("origin/{name}");
1355 let mut targets = vec![default_branch.clone()];
1356 if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1357 targets.push(remote);
1358 }
1359 for extra in extra_targets {
1360 if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1361 targets.push(extra.to_string());
1362 }
1363 }
1364 targets
1365 .iter()
1366 .any(|target| merged_into(root, commit_sha, target))
1367}
1368
1369fn git_ok(root: &Path, args: &[&str]) -> bool {
1370 std::process::Command::new("git")
1371 .args(args)
1372 .current_dir(root)
1373 .output()
1374 .map(|o| o.status.success())
1375 .unwrap_or(false)
1376}
1377
1378fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1380 let ancestor_check = std::process::Command::new("git")
1382 .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1383 .current_dir(root)
1384 .output();
1385 if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1386 return true;
1387 }
1388
1389 let cherry_out = std::process::Command::new("git")
1391 .args(["cherry", default_branch, commit_sha])
1392 .current_dir(root)
1393 .output();
1394 if let Ok(o) = cherry_out {
1395 if o.status.success() {
1396 let s = String::from_utf8_lossy(&o.stdout);
1397 let lines: Vec<&str> = s
1398 .lines()
1399 .map(|l| l.trim())
1400 .filter(|l| !l.is_empty())
1401 .collect();
1402 if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1403 return true;
1404 }
1405 }
1406 }
1407
1408 let default_tree_out = std::process::Command::new("git")
1411 .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1412 .current_dir(root)
1413 .output();
1414 if let Ok(tree_o) = default_tree_out {
1415 if tree_o.status.success() {
1416 let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1417 let merge_tree_out = std::process::Command::new("git")
1418 .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1419 .current_dir(root)
1420 .output();
1421 if let Ok(mt_o) = merge_tree_out {
1422 if mt_o.status.success() {
1423 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1424 if let Some(first_line) = mt_stdout.lines().next() {
1425 if first_line.trim() == default_tree {
1426 return true;
1427 }
1428 }
1429 }
1430 }
1431 }
1432 }
1433
1434 is_squash_merged_into_target(root, commit_sha, default_branch)
1437}
1438
1439fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
1440 let mb_out = std::process::Command::new("git")
1441 .args(["merge-base", target, commit_sha])
1442 .current_dir(root)
1443 .output();
1444 let Ok(mb_o) = mb_out else {
1445 return false;
1446 };
1447 if !mb_o.status.success() {
1448 return false;
1449 }
1450 let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
1451 if base.is_empty() {
1452 return false;
1453 }
1454
1455 let subj_out = std::process::Command::new("git")
1456 .args([
1457 "log",
1458 "--no-merges",
1459 "--format=%s",
1460 &format!("{target}..{commit_sha}"),
1461 ])
1462 .current_dir(root)
1463 .output();
1464 let Ok(subj_o) = subj_out else {
1465 return false;
1466 };
1467 if !subj_o.status.success() {
1468 return false;
1469 }
1470 let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1471 let subjects: Vec<&str> = subj_stdout
1472 .lines()
1473 .map(|l| l.trim())
1474 .filter(|l| !l.is_empty())
1475 .collect();
1476 if subjects.is_empty() {
1477 return false;
1478 }
1479
1480 let hay_out = std::process::Command::new("git")
1481 .args(["log", "--format=%B", &format!("{base}..{target}")])
1482 .current_dir(root)
1483 .output();
1484 let Ok(hay_o) = hay_out else {
1485 return false;
1486 };
1487 if !hay_o.status.success() {
1488 return false;
1489 }
1490 let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1491 let mut haystack_lines = HashSet::new();
1492 for line in hay_stdout.lines() {
1493 let trimmed = line.trim();
1494 if trimmed.is_empty() {
1495 continue;
1496 }
1497 haystack_lines.insert(trimmed.to_string());
1498 if let Some(stripped) = trimmed
1499 .strip_prefix("* ")
1500 .or_else(|| trimmed.strip_prefix("- "))
1501 {
1502 let stripped = stripped.trim();
1503 if !stripped.is_empty() {
1504 haystack_lines.insert(stripped.to_string());
1505 }
1506 }
1507 }
1508
1509 subjects.iter().all(|s| haystack_lines.contains(*s))
1510}
1511
1512pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1514 let wt_dir = root.join(".wt");
1515 let mut ids = Vec::new();
1516 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1517 for entry in entries.flatten() {
1518 let name = entry.file_name().to_string_lossy().to_string();
1519 if let Some(id) = name.strip_suffix(".start.json") {
1520 ids.push(id.to_string());
1521 }
1522 }
1523 }
1524 ids.sort();
1525 ids
1526}
1527
1528pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1530 let mut ctx = CleanContext::new(root);
1531 ctx.find_merged_followup(id)
1532}
1533
1534pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1536 let wt_dir = root.join(".wt");
1537 if !wt_dir.is_dir() {
1538 return Vec::new();
1539 }
1540 let mut ids = Vec::new();
1541 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1542 for entry in entries.flatten() {
1543 if let Ok(ft) = entry.file_type() {
1544 if ft.is_dir() {
1545 let name = entry.file_name().to_string_lossy().to_string();
1546 let start_file = wt_dir.join(format!("{name}.start.json"));
1547 if start_file.is_file() {
1548 ids.push(name);
1549 }
1550 }
1551 }
1552 }
1553 }
1554 ids.sort();
1555 ids
1556}
1557
1558pub struct CleanRepoStats {
1559 pub removed_worktrees: usize,
1560 pub freed_bytes: u64,
1561}
1562
1563pub fn clean_repo(
1565 root: &Path,
1566 older_than_days: u64,
1567 dry_run: bool,
1568 skip_id: Option<&str>,
1569 quiet: bool,
1570) -> CleanRepoStats {
1571 let mut removed_worktrees = 0;
1572 let mut freed_bytes = 0;
1573
1574 let mut ctx = CleanContext::new(root);
1575 ctx.set_quiet(quiet);
1576 let start_time = std::time::Instant::now();
1577 let ids = find_blyte_worktrees(root);
1578 for id in ids {
1579 if quiet && start_time.elapsed() >= std::time::Duration::from_secs(1) {
1580 break;
1581 }
1582 if skip_id == Some(&id) {
1583 continue;
1584 }
1585
1586 let wt_path = root.join(".wt").join(&id);
1587 match ctx.check_removable(&id, older_than_days) {
1588 Err(kept_reason) => {
1589 if !quiet {
1590 println!("kept .wt/{id} ({kept_reason})");
1591 }
1592 }
1593 Ok(removal_reason) => {
1594 let is_res = ctx.is_research_run(&id);
1595 if !is_res && has_uncommitted_changes(&wt_path) {
1596 if !quiet {
1597 println!("kept .wt/{id} (uncommitted changes)");
1598 }
1599 continue;
1600 }
1601
1602 let size = dir_size(&wt_path);
1603 let branch_name = format!("wip/{id}");
1604 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1605 let is_merged = branch_exists
1606 && (matches!(
1607 removal_reason,
1608 RemovalReason::Merged
1609 | RemovalReason::MergedInto(_)
1610 | RemovalReason::MergedThrough(_)
1611 ) || ctx.check_run_merged(&id).is_some());
1612
1613 if dry_run {
1614 if !quiet {
1615 println!(
1616 "would remove .wt/{id} ({removal_reason}, {})",
1617 format_size(size)
1618 );
1619 if is_merged {
1620 println!("would delete branch {branch_name} (merged)");
1621 }
1622 }
1623 freed_bytes += size;
1624 removed_worktrees += 1;
1625 } else {
1626 let removed_ok = if is_res {
1627 std::fs::remove_dir_all(&wt_path).is_ok()
1628 } else {
1629 let rm_out = std::process::Command::new("git")
1630 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1631 .current_dir(root)
1632 .output();
1633 let _ = std::process::Command::new("git")
1634 .args(["worktree", "prune"])
1635 .current_dir(root)
1636 .output();
1637 rm_out.map(|o| o.status.success()).unwrap_or(false)
1638 };
1639
1640 if removed_ok {
1641 freed_bytes += size;
1642 removed_worktrees += 1;
1643 if !quiet {
1644 println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
1645 }
1646 if is_merged {
1647 let del_out = std::process::Command::new("git")
1648 .args(["branch", "-D", &branch_name])
1649 .current_dir(root)
1650 .output();
1651 if del_out.map(|o| o.status.success()).unwrap_or(false) {
1652 ctx.wip_branch_tips.remove(&branch_name);
1653 if !quiet {
1654 println!("deleted branch {branch_name} (merged)");
1655 }
1656 }
1657 }
1658 } else if !quiet {
1659 println!("kept .wt/{id} (worktree remove failed)");
1660 }
1661 }
1662 }
1663 }
1664 }
1665
1666 if !quiet {
1667 report_other_worktrees(root);
1668 }
1669
1670 CleanRepoStats {
1671 removed_worktrees,
1672 freed_bytes,
1673 }
1674}
1675
1676#[derive(Debug)]
1677pub struct GitWorktreeInfo {
1678 pub path: PathBuf,
1679 pub head_sha: Option<String>,
1680 pub branch: Option<String>,
1681 pub is_detached: bool,
1682 pub is_bare: bool,
1683}
1684
1685pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
1687 let out = std::process::Command::new("git")
1688 .args(["worktree", "list", "--porcelain"])
1689 .current_dir(root)
1690 .output();
1691 let Ok(o) = out else {
1692 return Vec::new();
1693 };
1694 if !o.status.success() {
1695 return Vec::new();
1696 }
1697 let text = String::from_utf8_lossy(&o.stdout);
1698
1699 let mut list = Vec::new();
1700 let mut cur_path: Option<PathBuf> = None;
1701 let mut cur_head: Option<String> = None;
1702 let mut cur_branch: Option<String> = None;
1703 let mut cur_detached = false;
1704 let mut cur_bare = false;
1705
1706 let mut finish_entry = |path: &mut Option<PathBuf>,
1707 head: &mut Option<String>,
1708 branch: &mut Option<String>,
1709 detached: &mut bool,
1710 bare: &mut bool| {
1711 if let Some(p) = path.take() {
1712 list.push(GitWorktreeInfo {
1713 path: p,
1714 head_sha: head.take(),
1715 branch: branch.take(),
1716 is_detached: *detached,
1717 is_bare: *bare,
1718 });
1719 *detached = false;
1720 *bare = false;
1721 }
1722 };
1723
1724 for line in text.lines() {
1725 let line = line.trim();
1726 if line.is_empty() {
1727 finish_entry(
1728 &mut cur_path,
1729 &mut cur_head,
1730 &mut cur_branch,
1731 &mut cur_detached,
1732 &mut cur_bare,
1733 );
1734 } else if let Some(p) = line.strip_prefix("worktree ") {
1735 finish_entry(
1736 &mut cur_path,
1737 &mut cur_head,
1738 &mut cur_branch,
1739 &mut cur_detached,
1740 &mut cur_bare,
1741 );
1742 cur_path = Some(PathBuf::from(p.trim()));
1743 } else if let Some(h) = line.strip_prefix("HEAD ") {
1744 cur_head = Some(h.trim().to_string());
1745 } else if let Some(b) = line.strip_prefix("branch ") {
1746 let b_str = b.trim();
1747 let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
1748 cur_branch = Some(b_name.to_string());
1749 } else if line == "detached" {
1750 cur_detached = true;
1751 } else if line == "bare" {
1752 cur_bare = true;
1753 }
1754 }
1755 finish_entry(
1756 &mut cur_path,
1757 &mut cur_head,
1758 &mut cur_branch,
1759 &mut cur_detached,
1760 &mut cur_bare,
1761 );
1762 list
1763}
1764
1765pub fn display_worktree_path(target: &Path, root: &Path) -> String {
1769 let target_canon = target
1770 .canonicalize()
1771 .unwrap_or_else(|_| target.to_path_buf());
1772 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1773
1774 if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
1776 if !rel.as_os_str().is_empty() {
1777 return rel.to_string_lossy().replace('\\', "/");
1778 }
1779 }
1780
1781 if target_canon != root_canon {
1783 if let (Some(root_parent), Some(target_parent)) =
1784 (root_canon.parent(), target_canon.parent())
1785 {
1786 if root_parent == target_parent {
1787 if let Some(file_name) = target_canon.file_name() {
1788 let rel = Path::new("..").join(file_name);
1789 return rel.to_string_lossy().replace('\\', "/");
1790 }
1791 }
1792 }
1793 }
1794
1795 target_canon.to_string_lossy().replace('\\', "/")
1797}
1798
1799pub fn is_linked_worktree(root: &Path) -> bool {
1801 let git_dir_out = std::process::Command::new("git")
1802 .args(["rev-parse", "--git-dir"])
1803 .current_dir(root)
1804 .output();
1805 let common_dir_out = std::process::Command::new("git")
1806 .args(["rev-parse", "--git-common-dir"])
1807 .current_dir(root)
1808 .output();
1809 match (git_dir_out, common_dir_out) {
1810 (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
1811 let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
1812 let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
1813 if gd_str == cd_str {
1814 return false;
1815 }
1816 let gd_path = if Path::new(&gd_str).is_absolute() {
1817 PathBuf::from(&gd_str)
1818 } else {
1819 root.join(&gd_str)
1820 };
1821 let cd_path = if Path::new(&cd_str).is_absolute() {
1822 PathBuf::from(&cd_str)
1823 } else {
1824 root.join(&cd_str)
1825 };
1826 let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
1827 let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
1828 gd_canon != cd_canon
1829 }
1830 _ => false,
1831 }
1832}
1833
1834pub fn has_wt_component(path: &Path) -> bool {
1836 path.components().any(|c| c.as_os_str() == ".wt")
1837}
1838
1839pub fn is_worktree_clean(wt_path: &Path) -> bool {
1842 let out = std::process::Command::new("git")
1843 .arg("-C")
1844 .arg(wt_path.as_os_str())
1845 .args(["status", "--porcelain", "-u"])
1846 .output();
1847 match out {
1848 Ok(o) if o.status.success() => {
1849 let stdout = String::from_utf8_lossy(&o.stdout);
1850 for line in stdout.lines() {
1851 let trimmed = line.trim();
1852 if trimmed.is_empty() {
1853 continue;
1854 }
1855 if line.len() < 3 {
1856 return false;
1857 }
1858 let mut path_part = line[3..].trim();
1859 if let Some((_, new_path)) = path_part.split_once(" -> ") {
1860 path_part = new_path.trim();
1861 }
1862 let unquoted = path_part
1863 .strip_prefix('"')
1864 .and_then(|p| p.strip_suffix('"'))
1865 .unwrap_or(path_part);
1866 if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
1867 return false;
1868 }
1869 }
1870 true
1871 }
1872 _ => false,
1873 }
1874}
1875
1876pub fn report_other_worktrees(root: &Path) {
1880 if is_linked_worktree(root) {
1883 return;
1884 }
1885
1886 let worktrees = parse_worktree_list(root);
1887 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1888 let main_canon = worktrees
1889 .first()
1890 .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
1891
1892 let mut other_count = 0;
1893 let mut other_bytes = 0;
1894
1895 for (idx, wt) in worktrees.into_iter().enumerate() {
1896 if idx == 0 {
1898 continue;
1899 }
1900 if wt.is_bare {
1901 continue;
1902 }
1903 if !wt.path.exists() {
1904 continue;
1905 }
1906
1907 let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
1908 if wt_canon == root_canon || wt.path == root {
1910 continue;
1911 }
1912 if Some(&wt_canon) == main_canon.as_ref() {
1913 continue;
1914 }
1915 if has_wt_component(&wt.path) || has_wt_component(&wt_canon) {
1917 continue;
1918 }
1919
1920 let is_merged = if let Some(ref branch) = wt.branch {
1922 is_branch_merged(root, branch)
1923 } else if let Some(ref sha) = wt.head_sha {
1924 is_commit_merged(root, sha)
1925 } else {
1926 false
1927 };
1928
1929 if !is_merged {
1930 continue;
1931 }
1932
1933 if !is_worktree_clean(&wt.path) {
1935 continue;
1936 }
1937
1938 let size = dir_size(&wt.path);
1939 let path_str = display_worktree_path(&wt.path, root);
1940 let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
1941 wt.head_sha
1942 .as_deref()
1943 .map(|s| &s[..s.len().min(7)])
1944 .unwrap_or("detached")
1945 });
1946
1947 println!(
1948 "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
1949 format_size(size)
1950 );
1951
1952 other_count += 1;
1953 other_bytes += size;
1954 }
1955
1956 if other_count > 0 {
1957 println!(
1958 "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
1959 format_size(other_bytes)
1960 );
1961 }
1962}
1963
1964pub fn run(args: &crate::cli::CleanArgs) -> i32 {
1966 let repos = if args.all {
1967 crate::registry::registered()
1968 } else {
1969 match find_repo_root() {
1970 Ok(root) => vec![root],
1971 Err(e) => {
1972 eprintln!("error: {e}");
1973 return 2;
1974 }
1975 }
1976 };
1977
1978 let mut total_freed = 0;
1979 for repo in &repos {
1980 let stats = clean_repo(repo, args.older_than, args.dry_run, None, false);
1981 total_freed += stats.freed_bytes;
1982 }
1983
1984 if args.dry_run {
1985 println!("would free {}", format_size(total_freed));
1986 } else {
1987 println!("freed {}", format_size(total_freed));
1988 }
1989
1990 0
1991}
1992
1993pub fn clean_quiet(root: &Path, skip_id: Option<&str>) {
1997 let stats = clean_repo(root, 14, false, skip_id, true);
1998 if stats.removed_worktrees > 0 {
1999 eprintln!(
2000 "blyte: removed {} finished worktrees ({})",
2001 stats.removed_worktrees,
2002 format_size(stats.freed_bytes)
2003 );
2004 }
2005}
2006
2007pub fn clean_on_review(root: &Path, id: &str) {
2012 let wt_path = root.join(".wt").join(id);
2013 if !wt_path.exists() {
2014 clean_quiet(root, Some(id));
2015 return;
2016 }
2017
2018 let mut ctx = CleanContext::new(root);
2019 let branch_name = format!("wip/{id}");
2020 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2021
2022 let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
2023 let verdict_str = std::fs::read_to_string(&verdict_path)
2024 .ok()
2025 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2026 .and_then(|v| {
2027 v.get("verdict")
2028 .and_then(|s| s.as_str())
2029 .map(|s| s.to_string())
2030 })
2031 .unwrap_or_default();
2032
2033 let is_res = ctx.is_research_run(id);
2034 let removable = match ctx.check_removable(id, 14) {
2035 Ok(_) => is_res || !has_uncommitted_changes(&wt_path),
2036 Err(_) => false,
2037 };
2038
2039 if !removable {
2040 if verdict_str == "accepted" || verdict_str == "fixed" {
2041 println!("worktree .wt/{id} kept until {branch_name} is merged");
2042 }
2043 clean_quiet(root, Some(id));
2044 return;
2045 }
2046
2047 let removed_ok = if is_res {
2048 std::fs::remove_dir_all(&wt_path).is_ok()
2049 } else {
2050 let rm_out = std::process::Command::new("git")
2051 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2052 .current_dir(root)
2053 .output();
2054 let _ = std::process::Command::new("git")
2055 .args(["worktree", "prune"])
2056 .current_dir(root)
2057 .output();
2058 rm_out.map(|o| o.status.success()).unwrap_or(false)
2059 };
2060
2061 if !removed_ok {
2062 if verdict_str == "accepted" || verdict_str == "fixed" {
2063 println!("worktree .wt/{id} kept until {branch_name} is merged");
2064 }
2065 clean_quiet(root, Some(id));
2066 return;
2067 }
2068
2069 if branch_exists {
2070 let is_merged = ctx.check_run_merged(id).is_some();
2071 if is_merged {
2072 let del_out = std::process::Command::new("git")
2073 .args(["branch", "-D", &branch_name])
2074 .current_dir(root)
2075 .output();
2076 if del_out.map(|o| o.status.success()).unwrap_or(false) {
2077 ctx.wip_branch_tips.remove(&branch_name);
2078 println!("removed .wt/{id}; branch {branch_name} deleted");
2079 } else {
2080 println!("removed .wt/{id}; branch {branch_name} kept");
2081 }
2082 } else {
2083 println!("removed .wt/{id}; branch {branch_name} kept");
2084 }
2085 } else {
2086 println!("removed .wt/{id}");
2087 }
2088
2089 clean_quiet(root, Some(id));
2090}