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 cherry_pick_set: Option<HashSet<String>>,
409 pub rev_list_cache: HashMap<String, Vec<String>>,
410 pub ancestor_cache: HashMap<(String, String), bool>,
411}
412
413impl<'a> CleanContext<'a> {
414 pub fn new(root: &'a Path) -> Self {
415 let mut start_files = HashMap::new();
416 let mut all_run_ids = Vec::new();
417 let wt_dir = root.join(".wt");
418 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
419 for entry in entries.flatten() {
420 let name = entry.file_name().to_string_lossy().to_string();
421 if let Some(id) = name.strip_suffix(".start.json") {
422 all_run_ids.push(id.to_string());
423 if let Ok(content) = std::fs::read_to_string(entry.path()) {
424 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
425 start_files.insert(id.to_string(), val);
426 }
427 }
428 }
429 }
430 }
431 all_run_ids.sort();
432
433 let mut wip_branch_tips = HashMap::new();
434 let ref_out = std::process::Command::new("git")
435 .args([
436 "for-each-ref",
437 "--format=%(refname:short) %(objectname)",
438 "refs/heads/wip/",
439 ])
440 .current_dir(root)
441 .output();
442 if let Ok(o) = ref_out {
443 if o.status.success() {
444 for line in String::from_utf8_lossy(&o.stdout).lines() {
445 let mut parts = line.split_whitespace();
446 if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
447 wip_branch_tips.insert(refname.to_string(), sha.to_string());
448 }
449 }
450 }
451 }
452
453 let default_branch = find_default_branch(root);
454 let name = default_branch
455 .strip_prefix("origin/")
456 .unwrap_or(&default_branch);
457 let remote = format!("origin/{name}");
458 let origin_default = if remote != default_branch
459 && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
460 {
461 Some(remote)
462 } else {
463 None
464 };
465
466 let default_tree = git_tree_sha(root, &default_branch);
467 let origin_default_tree = origin_default
468 .as_deref()
469 .and_then(|r| git_tree_sha(root, r));
470
471 Self {
472 root,
473 start_files,
474 all_run_ids,
475 wip_branch_tips,
476 default_branch,
477 origin_default,
478 default_tree,
479 origin_default_tree,
480 wip_contains_cache: HashMap::new(),
481 merged_cache: HashMap::new(),
482 branch_contains_calls: 0,
483 cherry_pick_set: None,
484 rev_list_cache: HashMap::new(),
485 ancestor_cache: HashMap::new(),
486 }
487 }
488
489 fn compute_cherry_pick_set(&self) -> HashSet<String> {
490 let unremoved_ids = find_blyte_worktrees(self.root);
491 let candidate_ids: &[String] = if unremoved_ids.is_empty() {
492 &self.all_run_ids
493 } else {
494 &unremoved_ids
495 };
496
497 let mut min_started_at: Option<u64> = None;
498 let mut all_valid = true;
499
500 for id in candidate_ids {
501 let start_val = self.start_files.get(id);
502 let parsed = start_val.and_then(parse_started_at);
503 match parsed {
504 Some(ts) => {
505 min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
506 }
507 None => {
508 all_valid = false;
509 }
510 }
511 }
512
513 let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
514 if min_ts >= 86_400 + 100_000_000 {
515 format!("--since={}", min_ts - 86_400)
516 } else {
517 "--since=1970-01-01T00:00:00Z".to_string()
518 }
519 } else {
520 "--since=1970-01-01T00:00:00Z".to_string()
521 };
522
523 let mut targets = Vec::new();
524 let mut seen = HashSet::new();
525
526 if git_ok(
527 self.root,
528 &["rev-parse", "--verify", "--quiet", &self.default_branch],
529 ) && seen.insert(self.default_branch.clone())
530 {
531 targets.push(self.default_branch.clone());
532 }
533
534 if let Some(ref origin_def) = self.origin_default {
535 if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
536 && seen.insert(origin_def.clone())
537 {
538 targets.push(origin_def.clone());
539 }
540 }
541
542 for id in &self.all_run_ids {
543 if let Some(base_str) = self
544 .start_files
545 .get(id)
546 .and_then(|s| s.get("base"))
547 .and_then(|b| b.as_str())
548 {
549 if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
550 for bt in base_targets {
551 if seen.insert(bt.clone()) {
552 targets.push(bt);
553 }
554 }
555 }
556 }
557 }
558
559 if targets.is_empty() {
560 return HashSet::new();
561 }
562
563 let mut cmd = std::process::Command::new("git");
564 cmd.args(["log", "--format=%B", &since_arg]);
565 for t in &targets {
566 cmd.arg(t);
567 }
568 cmd.current_dir(self.root);
569
570 let mut set = HashSet::new();
571 if let Ok(o) = cmd.output() {
572 if o.status.success() {
573 let text = String::from_utf8_lossy(&o.stdout);
574 for line in text.lines() {
575 let trimmed = line.trim();
576 if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
577 if let Some(sha) = rest.strip_suffix(')') {
578 let sha = sha.trim();
579 if is_commit_id(sha) {
580 set.insert(sha.to_lowercase());
581 }
582 }
583 }
584 }
585 }
586 }
587
588 set
589 }
590
591 pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
592 if self.cherry_pick_set.is_none() {
593 let set = self.compute_cherry_pick_set();
594 self.cherry_pick_set = Some(set);
595 }
596 self.cherry_pick_set.as_ref().unwrap()
597 }
598
599 fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
600 let key = (commit_sha.to_string(), target.to_string());
601 if let Some(&cached) = self.ancestor_cache.get(&key) {
602 return cached;
603 }
604 let is_anc = std::process::Command::new("git")
605 .args(["merge-base", "--is-ancestor", commit_sha, target])
606 .current_dir(self.root)
607 .output()
608 .map(|c| c.status.success())
609 .unwrap_or(false);
610 self.ancestor_cache.insert(key, is_anc);
611 is_anc
612 }
613
614 fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
615 let def = self.default_branch.clone();
616 if self.is_ancestor_of_target(commit_sha, &def) {
617 return true;
618 }
619 if let Some(origin_def) = self.origin_default.clone() {
620 if self.is_ancestor_of_target(commit_sha, &origin_def) {
621 return true;
622 }
623 }
624 false
625 }
626
627 fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
628 if let Some(cached) = self.rev_list_cache.get(tip_sha) {
629 return cached.clone();
630 }
631 let out = std::process::Command::new("git")
632 .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
633 .current_dir(self.root)
634 .output();
635 let commits: Vec<String> = match out {
636 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
637 .lines()
638 .map(|l| l.trim().to_lowercase())
639 .filter(|l| !l.is_empty())
640 .collect(),
641 _ => Vec::new(),
642 };
643 self.rev_list_cache
644 .insert(tip_sha.to_string(), commits.clone());
645 commits
646 }
647
648 fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
649 let commits = self.get_run_commits_against_default(tip_sha);
650 if commits.is_empty() {
651 return false;
652 }
653 let cherry_set = self.get_cherry_pick_set();
654 commits.iter().all(|c| cherry_set.contains(c))
655 }
656
657 pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
658 if let Some(sha) = self.wip_branch_tips.get(branch_name) {
659 return Some(sha.clone());
660 }
661 get_branch_tip(self.root, branch_name)
662 }
663
664 pub fn is_research_run(&self, id: &str) -> bool {
665 self.start_files
666 .get(id)
667 .and_then(|v| v.get("research"))
668 .and_then(|r| r.as_bool())
669 .unwrap_or_else(|| is_research(self.root, id))
670 }
671
672 pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
673 if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
674 return cached.clone();
675 }
676
677 self.branch_contains_calls += 1;
678
679 let out = std::process::Command::new("git")
680 .args([
681 "branch",
682 "--list",
683 "--format=%(refname:short)",
684 "wip/*",
685 "--contains",
686 tip_sha,
687 ])
688 .current_dir(self.root)
689 .output();
690
691 let mut branches = Vec::new();
692 if let Ok(o) = out {
693 if o.status.success() {
694 for line in String::from_utf8_lossy(&o.stdout).lines() {
695 let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
696 if !trimmed.is_empty() {
697 branches.push(trimmed.to_string());
698 }
699 }
700 }
701 }
702 self.wip_contains_cache
703 .insert(tip_sha.to_string(), branches.clone());
704 branches
705 }
706
707 pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
708 let mut children = Vec::new();
709 let mut seen = HashSet::new();
710
711 for (candidate_id, start_val) in &self.start_files {
713 if candidate_id == id {
714 continue;
715 }
716 if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
717 let base_str = base_str.trim().trim_end_matches('/');
718 let target1 = format!("wip/{id}");
719 let target2 = format!("refs/heads/wip/{id}");
720 if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
721 {
722 children.push(candidate_id.clone());
723 }
724 }
725 }
726
727 if !tip_sha.is_empty() {
729 let tip_sha_owned = tip_sha.to_string();
730 let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
731 for b in containing_branches {
732 let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
733 if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
734 if candidate_id == id {
735 continue;
736 }
737 if !self.start_files.contains_key(candidate_id) {
738 continue;
739 }
740 let has_base = self
741 .start_files
742 .get(candidate_id)
743 .and_then(|val| val.get("base"))
744 .is_some_and(|b| !b.is_null());
745 if !has_base && seen.insert(candidate_id.to_string()) {
746 children.push(candidate_id.to_string());
747 }
748 }
749 }
750 }
751
752 children.sort();
753 children
754 }
755
756 pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
757 if self.is_research_run(child) {
758 return false;
759 }
760
761 let branch_name = format!("wip/{child}");
762 let tip = self.get_branch_tip(&branch_name);
763
764 if tip.is_none() {
765 let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
766 let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
767 let v = std::fs::read_to_string(&verdict_path)
768 .ok()
769 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
770 .and_then(|v| {
771 v.get("verdict")
772 .and_then(|s| s.as_str())
773 .map(|s| s.to_string())
774 })
775 .unwrap_or_default();
776 (v == "accepted" || v == "fixed", v == "redone")
777 } else {
778 (false, false)
779 };
780
781 if is_redone {
782 return false;
783 }
784
785 let summary_path = self.root.join(".wt").join(format!("{child}.json"));
786 let is_verified = std::fs::read_to_string(&summary_path)
787 .ok()
788 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
789 .and_then(|v| {
790 v.get("outcome")
791 .and_then(|s| s.as_str())
792 .map(|s| s == "verified")
793 })
794 .unwrap_or(false);
795
796 let wt_gone = !self.root.join(".wt").join(child).is_dir();
797
798 return has_accepted_verdict || (is_verified && wt_gone);
799 }
800
801 self.check_run_merged_internal(child, visited).is_some()
802 }
803
804 pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
805 let mut visited = HashSet::new();
806 self.check_run_merged_internal(id, &mut visited)
807 }
808
809 fn check_run_merged_internal(
810 &mut self,
811 id: &str,
812 visited: &mut HashSet<String>,
813 ) -> Option<RemovalReason> {
814 if visited.contains(id) {
815 return None;
816 }
817
818 if let Some(cached) = self.merged_cache.get(id) {
819 return cached.clone();
820 }
821
822 visited.insert(id.to_string());
823
824 let branch_name = format!("wip/{id}");
825 let tip_sha = self.get_branch_tip(&branch_name);
826
827 let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
828
829 visited.remove(id);
830
831 self.merged_cache.insert(id.to_string(), result.clone());
832 result
833 }
834
835 fn decide_run_merged(
836 &mut self,
837 id: &str,
838 tip_sha: Option<&str>,
839 visited: &mut HashSet<String>,
840 ) -> Option<RemovalReason> {
841 let base_opt = self.start_files.get(id).and_then(|s| {
842 s.get("base")
843 .and_then(|b| b.as_str())
844 .map(|b| b.to_string())
845 });
846 let base_targets = base_opt
847 .as_deref()
848 .and_then(|b| resolve_base_targets(self.root, b));
849 let started_at = self
850 .start_files
851 .get(id)
852 .and_then(|s| s.get("started_at"))
853 .cloned();
854
855 if let Some(tip_sha) = tip_sha {
856 if self.is_ancestor_of_default(tip_sha) {
858 return Some(RemovalReason::Merged);
859 }
860
861 if self.is_in_cherry_pick_record(tip_sha) {
863 return Some(RemovalReason::Merged);
864 }
865
866 if let Some((ref display_name, ref targets)) = base_targets {
868 for target in targets {
869 if self.is_ancestor_of_target(tip_sha, target) {
870 return Some(RemovalReason::MergedInto(display_name.clone()));
871 }
872 if is_cherry_merged_into_target(self.root, tip_sha, target) {
873 return Some(RemovalReason::MergedInto(display_name.clone()));
874 }
875 if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
876 return Some(RemovalReason::MergedInto(display_name.clone()));
877 }
878 }
879 }
880 }
881
882 let children = self.get_children_of(id, tip_sha.unwrap_or(""));
884 for child in children {
885 if visited.contains(&child) {
886 continue;
887 }
888 if self.is_child_run_merged(&child, visited) {
889 return Some(RemovalReason::MergedThrough(child));
890 }
891 }
892
893 if let Some(tip_sha) = tip_sha {
894 if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
896 return Some(RemovalReason::Merged);
897 }
898 if let Some(ref origin_def) = self.origin_default {
899 if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
900 return Some(RemovalReason::Merged);
901 }
902 }
903
904 if is_merge_tree_merged_into_target(
906 self.root,
907 tip_sha,
908 &self.default_branch,
909 self.default_tree.as_deref(),
910 ) {
911 return Some(RemovalReason::Merged);
912 }
913 if let Some(ref origin_def) = self.origin_default {
914 if is_merge_tree_merged_into_target(
915 self.root,
916 tip_sha,
917 origin_def,
918 self.origin_default_tree.as_deref(),
919 ) {
920 return Some(RemovalReason::Merged);
921 }
922 }
923
924 if check_history_merged(
926 self.root,
927 tip_sha,
928 &self.default_branch,
929 started_at.as_ref(),
930 ) {
931 return Some(RemovalReason::Merged);
932 }
933 if let Some(ref origin_def) = self.origin_default {
934 if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
935 return Some(RemovalReason::Merged);
936 }
937 }
938 if let Some((ref display_name, ref targets)) = base_targets {
939 for target in targets {
940 if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
941 return Some(RemovalReason::MergedInto(display_name.clone()));
942 }
943 }
944 }
945
946 if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
948 return Some(reason);
949 }
950 }
951
952 None
953 }
954
955 fn squash_merged_reason(
956 &self,
957 tip_sha: &str,
958 base_targets: &Option<(String, Vec<String>)>,
959 ) -> Option<RemovalReason> {
960 if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
961 return Some(RemovalReason::Merged);
962 }
963 if let Some(ref origin_def) = self.origin_default {
964 if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
965 return Some(RemovalReason::Merged);
966 }
967 }
968 if let Some((ref display_name, ref targets)) = base_targets {
969 for target in targets {
970 if is_squash_merged_into_target(self.root, tip_sha, target) {
971 return Some(RemovalReason::MergedInto(display_name.clone()));
972 }
973 }
974 }
975 None
976 }
977
978 pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
979 let branch_name = format!("wip/{id}");
980 let tip_sha = self.get_branch_tip(&branch_name);
981 let mut visited = HashSet::new();
982 visited.insert(id.to_string());
983 let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
984 children
985 .into_iter()
986 .find(|child| self.is_child_run_merged(child, &mut visited))
987 }
988
989 pub fn check_removable(
990 &mut self,
991 id: &str,
992 older_than_days: u64,
993 ) -> Result<RemovalReason, KeptReason> {
994 let wt_dir = self.root.join(".wt");
995 let summary_path = wt_dir.join(format!("{id}.json"));
996 let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
997 let report_path = wt_dir.join(format!("{id}.report.md"));
998
999 let start_json = self.start_files.get(id);
1000 let summary_exists = summary_path.is_file();
1001
1002 if let Some(start) = start_json {
1004 if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1005 if is_pid_alive(pid) {
1006 if !summary_exists {
1007 return Err(KeptReason::Running);
1008 }
1009 let Some(started_at) = parse_started_at(start) else {
1010 return Err(KeptReason::Running);
1011 };
1012 let summary_mtime = std::fs::metadata(&summary_path)
1013 .ok()
1014 .and_then(|m| m.modified().ok())
1015 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1016 .map(|d| d.as_secs());
1017 if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1018 return Err(KeptReason::Running);
1019 }
1020 }
1021 }
1022 }
1023
1024 let is_res = self.is_research_run(id);
1025
1026 let verdict_str = if verdict_path.is_file() {
1028 std::fs::read_to_string(&verdict_path)
1029 .ok()
1030 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1031 .and_then(|v| {
1032 v.get("verdict")
1033 .and_then(|s| s.as_str())
1034 .map(|s| s.to_string())
1035 })
1036 .unwrap_or_default()
1037 } else {
1038 String::new()
1039 };
1040
1041 if verdict_str == "redone" {
1042 return Ok(RemovalReason::Verdict("redone".to_string()));
1043 }
1044
1045 if summary_exists {
1046 if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1047 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1048 if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1049 return Ok(RemovalReason::NoChanges);
1050 }
1051 }
1052 }
1053 }
1054
1055 if is_res && report_path.is_file() {
1057 return Ok(RemovalReason::ResearchReport);
1058 }
1059
1060 if !is_res {
1062 if let Some(reason) = self.check_run_merged(id) {
1063 return Ok(reason);
1064 }
1065 }
1066
1067 if summary_exists {
1069 if let Ok(meta) = std::fs::metadata(&summary_path) {
1070 if let Ok(mtime) = meta.modified() {
1071 let age = std::time::SystemTime::now()
1072 .duration_since(mtime)
1073 .unwrap_or(std::time::Duration::ZERO);
1074 if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1075 {
1076 return Ok(RemovalReason::OlderThan(older_than_days));
1077 }
1078 }
1079 }
1080 }
1081
1082 if !verdict_str.is_empty() {
1084 return Err(KeptReason::NotMergedYet);
1085 }
1086
1087 if is_res {
1088 Err(KeptReason::NoReport)
1089 } else {
1090 Err(KeptReason::NoVerdict)
1091 }
1092 }
1093}
1094
1095pub fn check_removable(
1097 root: &Path,
1098 id: &str,
1099 older_than_days: u64,
1100) -> Result<RemovalReason, KeptReason> {
1101 let mut ctx = CleanContext::new(root);
1102 ctx.check_removable(id, older_than_days)
1103}
1104
1105pub fn find_default_branch(root: &Path) -> String {
1107 let sym_out = std::process::Command::new("git")
1108 .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1109 .current_dir(root)
1110 .output();
1111 if let Ok(o) = sym_out {
1112 if o.status.success() {
1113 let target = String::from_utf8_lossy(&o.stdout);
1114 let target = target.trim();
1115 let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1116 let local_check = std::process::Command::new("git")
1117 .args([
1118 "rev-parse",
1119 "--verify",
1120 &format!("refs/heads/{branch_name}"),
1121 ])
1122 .current_dir(root)
1123 .output();
1124 if local_check.map(|c| c.status.success()).unwrap_or(false) {
1125 return branch_name.to_string();
1126 }
1127 let remote_check = std::process::Command::new("git")
1128 .args(["rev-parse", "--verify", target])
1129 .current_dir(root)
1130 .output();
1131 if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1132 return target.to_string();
1133 }
1134 return branch_name.to_string();
1135 }
1136 }
1137
1138 let main_check = std::process::Command::new("git")
1139 .args(["rev-parse", "--verify", "refs/heads/main"])
1140 .current_dir(root)
1141 .output();
1142 if main_check.map(|c| c.status.success()).unwrap_or(false) {
1143 return "main".to_string();
1144 }
1145
1146 let master_check = std::process::Command::new("git")
1147 .args(["rev-parse", "--verify", "refs/heads/master"])
1148 .current_dir(root)
1149 .output();
1150 if master_check.map(|c| c.status.success()).unwrap_or(false) {
1151 return "master".to_string();
1152 }
1153
1154 "main".to_string()
1155}
1156
1157fn is_commit_id(s: &str) -> bool {
1159 (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1160}
1161
1162pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1167 let base = base.trim();
1168 if base.is_empty() {
1169 return None;
1170 }
1171
1172 if base == "HEAD"
1173 || base.starts_with("HEAD~")
1174 || base.starts_with("HEAD^")
1175 || base.starts_with("HEAD@")
1176 || base.starts_with("HEAD:")
1177 {
1178 return None;
1179 }
1180
1181 if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1182 return None;
1183 }
1184
1185 if is_commit_id(base) {
1186 return None;
1187 }
1188
1189 let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1190 stripped
1191 } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1192 stripped
1193 } else {
1194 base
1195 };
1196
1197 let is_wip = clean == "wip"
1198 || clean.starts_with("wip/")
1199 || clean == "origin/wip"
1200 || clean.starts_with("origin/wip/");
1201 if is_wip {
1202 return None;
1203 }
1204
1205 let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1206 if without_origin.is_empty()
1207 || without_origin == "wip"
1208 || without_origin.starts_with("wip/")
1209 || without_origin == "HEAD"
1210 || without_origin.starts_with("HEAD~")
1211 || without_origin.starts_with("HEAD^")
1212 || is_commit_id(without_origin)
1213 {
1214 return None;
1215 }
1216 let cand1 = format!("refs/remotes/{clean}");
1217 let cand2 = format!("refs/heads/{without_origin}");
1218 (without_origin.to_string(), vec![cand1, cand2])
1219 } else {
1220 let cand1 = format!("refs/heads/{clean}");
1221 let cand2 = format!("refs/remotes/origin/{clean}");
1222 (clean.to_string(), vec![cand1, cand2])
1223 };
1224
1225 let mut resolved = Vec::new();
1226 for cand in candidates {
1227 if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1228 resolved.push(cand);
1229 }
1230 }
1231
1232 if resolved.is_empty() {
1233 None
1234 } else {
1235 Some((display_name, resolved))
1236 }
1237}
1238
1239pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1241 let start_path = root.join(".wt").join(format!("{id}.start.json"));
1242 std::fs::read_to_string(&start_path)
1243 .ok()
1244 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1245 .and_then(|v| {
1246 v.get("base")
1247 .and_then(|b| b.as_str())
1248 .map(|s| s.to_string())
1249 })
1250}
1251
1252pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1254 let check = std::process::Command::new("git")
1255 .args([
1256 "rev-parse",
1257 "--verify",
1258 &format!("refs/heads/{branch_name}"),
1259 ])
1260 .current_dir(root)
1261 .output()
1262 .ok()?;
1263 if !check.status.success() {
1264 return None;
1265 }
1266
1267 let tip_out = std::process::Command::new("git")
1268 .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1269 .current_dir(root)
1270 .output()
1271 .ok()?;
1272 if tip_out.status.success() {
1273 Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1274 } else {
1275 None
1276 }
1277}
1278
1279pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1286 let mut ctx = CleanContext::new(root);
1287 if let Some(id) = branch_name.strip_prefix("wip/") {
1288 ctx.check_run_merged(id).is_some()
1289 } else {
1290 is_branch_merged_with_targets(root, branch_name, &[])
1291 }
1292}
1293
1294pub fn is_branch_merged_with_targets(
1296 root: &Path,
1297 branch_name: &str,
1298 extra_targets: &[&str],
1299) -> bool {
1300 let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1301 return false;
1302 };
1303
1304 is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1305}
1306
1307pub fn is_branch_merged_with_extra_targets(
1309 root: &Path,
1310 branch_name: &str,
1311 extra_targets: &[&str],
1312) -> bool {
1313 is_branch_merged_with_targets(root, branch_name, extra_targets)
1314}
1315
1316pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1322 is_commit_merged_with_targets(root, commit_sha, &[])
1323}
1324
1325pub fn is_commit_merged_with_targets(
1327 root: &Path,
1328 commit_sha: &str,
1329 extra_targets: &[&str],
1330) -> bool {
1331 let default_branch = find_default_branch(root);
1332 let name = default_branch
1335 .strip_prefix("origin/")
1336 .unwrap_or(&default_branch);
1337 let remote = format!("origin/{name}");
1338 let mut targets = vec![default_branch.clone()];
1339 if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1340 targets.push(remote);
1341 }
1342 for extra in extra_targets {
1343 if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1344 targets.push(extra.to_string());
1345 }
1346 }
1347 targets
1348 .iter()
1349 .any(|target| merged_into(root, commit_sha, target))
1350}
1351
1352fn git_ok(root: &Path, args: &[&str]) -> bool {
1353 std::process::Command::new("git")
1354 .args(args)
1355 .current_dir(root)
1356 .output()
1357 .map(|o| o.status.success())
1358 .unwrap_or(false)
1359}
1360
1361fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1363 let ancestor_check = std::process::Command::new("git")
1365 .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1366 .current_dir(root)
1367 .output();
1368 if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1369 return true;
1370 }
1371
1372 let cherry_out = std::process::Command::new("git")
1374 .args(["cherry", default_branch, commit_sha])
1375 .current_dir(root)
1376 .output();
1377 if let Ok(o) = cherry_out {
1378 if o.status.success() {
1379 let s = String::from_utf8_lossy(&o.stdout);
1380 let lines: Vec<&str> = s
1381 .lines()
1382 .map(|l| l.trim())
1383 .filter(|l| !l.is_empty())
1384 .collect();
1385 if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1386 return true;
1387 }
1388 }
1389 }
1390
1391 let default_tree_out = std::process::Command::new("git")
1394 .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1395 .current_dir(root)
1396 .output();
1397 if let Ok(tree_o) = default_tree_out {
1398 if tree_o.status.success() {
1399 let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1400 let merge_tree_out = std::process::Command::new("git")
1401 .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1402 .current_dir(root)
1403 .output();
1404 if let Ok(mt_o) = merge_tree_out {
1405 if mt_o.status.success() {
1406 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1407 if let Some(first_line) = mt_stdout.lines().next() {
1408 if first_line.trim() == default_tree {
1409 return true;
1410 }
1411 }
1412 }
1413 }
1414 }
1415 }
1416
1417 is_squash_merged_into_target(root, commit_sha, default_branch)
1420}
1421
1422fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
1423 let mb_out = std::process::Command::new("git")
1424 .args(["merge-base", target, commit_sha])
1425 .current_dir(root)
1426 .output();
1427 let Ok(mb_o) = mb_out else {
1428 return false;
1429 };
1430 if !mb_o.status.success() {
1431 return false;
1432 }
1433 let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
1434 if base.is_empty() {
1435 return false;
1436 }
1437
1438 let subj_out = std::process::Command::new("git")
1439 .args([
1440 "log",
1441 "--no-merges",
1442 "--format=%s",
1443 &format!("{target}..{commit_sha}"),
1444 ])
1445 .current_dir(root)
1446 .output();
1447 let Ok(subj_o) = subj_out else {
1448 return false;
1449 };
1450 if !subj_o.status.success() {
1451 return false;
1452 }
1453 let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1454 let subjects: Vec<&str> = subj_stdout
1455 .lines()
1456 .map(|l| l.trim())
1457 .filter(|l| !l.is_empty())
1458 .collect();
1459 if subjects.is_empty() {
1460 return false;
1461 }
1462
1463 let hay_out = std::process::Command::new("git")
1464 .args(["log", "--format=%B", &format!("{base}..{target}")])
1465 .current_dir(root)
1466 .output();
1467 let Ok(hay_o) = hay_out else {
1468 return false;
1469 };
1470 if !hay_o.status.success() {
1471 return false;
1472 }
1473 let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1474 let mut haystack_lines = HashSet::new();
1475 for line in hay_stdout.lines() {
1476 let trimmed = line.trim();
1477 if trimmed.is_empty() {
1478 continue;
1479 }
1480 haystack_lines.insert(trimmed.to_string());
1481 if let Some(stripped) = trimmed
1482 .strip_prefix("* ")
1483 .or_else(|| trimmed.strip_prefix("- "))
1484 {
1485 let stripped = stripped.trim();
1486 if !stripped.is_empty() {
1487 haystack_lines.insert(stripped.to_string());
1488 }
1489 }
1490 }
1491
1492 subjects.iter().all(|s| haystack_lines.contains(*s))
1493}
1494
1495pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1497 let wt_dir = root.join(".wt");
1498 let mut ids = Vec::new();
1499 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1500 for entry in entries.flatten() {
1501 let name = entry.file_name().to_string_lossy().to_string();
1502 if let Some(id) = name.strip_suffix(".start.json") {
1503 ids.push(id.to_string());
1504 }
1505 }
1506 }
1507 ids.sort();
1508 ids
1509}
1510
1511pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1513 let mut ctx = CleanContext::new(root);
1514 ctx.find_merged_followup(id)
1515}
1516
1517pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1519 let wt_dir = root.join(".wt");
1520 if !wt_dir.is_dir() {
1521 return Vec::new();
1522 }
1523 let mut ids = Vec::new();
1524 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1525 for entry in entries.flatten() {
1526 if let Ok(ft) = entry.file_type() {
1527 if ft.is_dir() {
1528 let name = entry.file_name().to_string_lossy().to_string();
1529 let start_file = wt_dir.join(format!("{name}.start.json"));
1530 if start_file.is_file() {
1531 ids.push(name);
1532 }
1533 }
1534 }
1535 }
1536 }
1537 ids.sort();
1538 ids
1539}
1540
1541pub struct CleanRepoStats {
1542 pub removed_worktrees: usize,
1543 pub freed_bytes: u64,
1544}
1545
1546pub fn clean_repo(
1548 root: &Path,
1549 older_than_days: u64,
1550 dry_run: bool,
1551 skip_id: Option<&str>,
1552 quiet: bool,
1553) -> CleanRepoStats {
1554 let mut removed_worktrees = 0;
1555 let mut freed_bytes = 0;
1556
1557 let mut ctx = CleanContext::new(root);
1558 let ids = find_blyte_worktrees(root);
1559 for id in ids {
1560 if skip_id == Some(&id) {
1561 continue;
1562 }
1563
1564 let wt_path = root.join(".wt").join(&id);
1565 match ctx.check_removable(&id, older_than_days) {
1566 Err(kept_reason) => {
1567 if !quiet {
1568 println!("kept .wt/{id} ({kept_reason})");
1569 }
1570 }
1571 Ok(removal_reason) => {
1572 let is_res = ctx.is_research_run(&id);
1573 if !is_res && has_uncommitted_changes(&wt_path) {
1574 if !quiet {
1575 println!("kept .wt/{id} (uncommitted changes)");
1576 }
1577 continue;
1578 }
1579
1580 let size = dir_size(&wt_path);
1581 let branch_name = format!("wip/{id}");
1582 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1583 let is_merged = branch_exists
1584 && (matches!(
1585 removal_reason,
1586 RemovalReason::Merged
1587 | RemovalReason::MergedInto(_)
1588 | RemovalReason::MergedThrough(_)
1589 ) || ctx.check_run_merged(&id).is_some());
1590
1591 if dry_run {
1592 if !quiet {
1593 println!(
1594 "would remove .wt/{id} ({removal_reason}, {})",
1595 format_size(size)
1596 );
1597 if is_merged {
1598 println!("would delete branch {branch_name} (merged)");
1599 }
1600 }
1601 freed_bytes += size;
1602 removed_worktrees += 1;
1603 } else {
1604 let removed_ok = if is_res {
1605 std::fs::remove_dir_all(&wt_path).is_ok()
1606 } else {
1607 let rm_out = std::process::Command::new("git")
1608 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1609 .current_dir(root)
1610 .output();
1611 let _ = std::process::Command::new("git")
1612 .args(["worktree", "prune"])
1613 .current_dir(root)
1614 .output();
1615 rm_out.map(|o| o.status.success()).unwrap_or(false)
1616 };
1617
1618 if removed_ok {
1619 freed_bytes += size;
1620 removed_worktrees += 1;
1621 if !quiet {
1622 println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
1623 }
1624 if is_merged {
1625 let del_out = std::process::Command::new("git")
1626 .args(["branch", "-D", &branch_name])
1627 .current_dir(root)
1628 .output();
1629 if del_out.map(|o| o.status.success()).unwrap_or(false) {
1630 ctx.wip_branch_tips.remove(&branch_name);
1631 if !quiet {
1632 println!("deleted branch {branch_name} (merged)");
1633 }
1634 }
1635 }
1636 } else if !quiet {
1637 println!("kept .wt/{id} (worktree remove failed)");
1638 }
1639 }
1640 }
1641 }
1642 }
1643
1644 if !quiet {
1645 report_other_worktrees(root);
1646 }
1647
1648 CleanRepoStats {
1649 removed_worktrees,
1650 freed_bytes,
1651 }
1652}
1653
1654#[derive(Debug)]
1655pub struct GitWorktreeInfo {
1656 pub path: PathBuf,
1657 pub head_sha: Option<String>,
1658 pub branch: Option<String>,
1659 pub is_detached: bool,
1660 pub is_bare: bool,
1661}
1662
1663pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
1665 let out = std::process::Command::new("git")
1666 .args(["worktree", "list", "--porcelain"])
1667 .current_dir(root)
1668 .output();
1669 let Ok(o) = out else {
1670 return Vec::new();
1671 };
1672 if !o.status.success() {
1673 return Vec::new();
1674 }
1675 let text = String::from_utf8_lossy(&o.stdout);
1676
1677 let mut list = Vec::new();
1678 let mut cur_path: Option<PathBuf> = None;
1679 let mut cur_head: Option<String> = None;
1680 let mut cur_branch: Option<String> = None;
1681 let mut cur_detached = false;
1682 let mut cur_bare = false;
1683
1684 let mut finish_entry = |path: &mut Option<PathBuf>,
1685 head: &mut Option<String>,
1686 branch: &mut Option<String>,
1687 detached: &mut bool,
1688 bare: &mut bool| {
1689 if let Some(p) = path.take() {
1690 list.push(GitWorktreeInfo {
1691 path: p,
1692 head_sha: head.take(),
1693 branch: branch.take(),
1694 is_detached: *detached,
1695 is_bare: *bare,
1696 });
1697 *detached = false;
1698 *bare = false;
1699 }
1700 };
1701
1702 for line in text.lines() {
1703 let line = line.trim();
1704 if line.is_empty() {
1705 finish_entry(
1706 &mut cur_path,
1707 &mut cur_head,
1708 &mut cur_branch,
1709 &mut cur_detached,
1710 &mut cur_bare,
1711 );
1712 } else if let Some(p) = line.strip_prefix("worktree ") {
1713 finish_entry(
1714 &mut cur_path,
1715 &mut cur_head,
1716 &mut cur_branch,
1717 &mut cur_detached,
1718 &mut cur_bare,
1719 );
1720 cur_path = Some(PathBuf::from(p.trim()));
1721 } else if let Some(h) = line.strip_prefix("HEAD ") {
1722 cur_head = Some(h.trim().to_string());
1723 } else if let Some(b) = line.strip_prefix("branch ") {
1724 let b_str = b.trim();
1725 let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
1726 cur_branch = Some(b_name.to_string());
1727 } else if line == "detached" {
1728 cur_detached = true;
1729 } else if line == "bare" {
1730 cur_bare = true;
1731 }
1732 }
1733 finish_entry(
1734 &mut cur_path,
1735 &mut cur_head,
1736 &mut cur_branch,
1737 &mut cur_detached,
1738 &mut cur_bare,
1739 );
1740 list
1741}
1742
1743pub fn display_worktree_path(target: &Path, root: &Path) -> String {
1747 let target_canon = target
1748 .canonicalize()
1749 .unwrap_or_else(|_| target.to_path_buf());
1750 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1751
1752 if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
1754 if !rel.as_os_str().is_empty() {
1755 return rel.to_string_lossy().replace('\\', "/");
1756 }
1757 }
1758
1759 if target_canon != root_canon {
1761 if let (Some(root_parent), Some(target_parent)) =
1762 (root_canon.parent(), target_canon.parent())
1763 {
1764 if root_parent == target_parent {
1765 if let Some(file_name) = target_canon.file_name() {
1766 let rel = Path::new("..").join(file_name);
1767 return rel.to_string_lossy().replace('\\', "/");
1768 }
1769 }
1770 }
1771 }
1772
1773 target_canon.to_string_lossy().replace('\\', "/")
1775}
1776
1777pub fn is_linked_worktree(root: &Path) -> bool {
1779 let git_dir_out = std::process::Command::new("git")
1780 .args(["rev-parse", "--git-dir"])
1781 .current_dir(root)
1782 .output();
1783 let common_dir_out = std::process::Command::new("git")
1784 .args(["rev-parse", "--git-common-dir"])
1785 .current_dir(root)
1786 .output();
1787 match (git_dir_out, common_dir_out) {
1788 (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
1789 let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
1790 let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
1791 if gd_str == cd_str {
1792 return false;
1793 }
1794 let gd_path = if Path::new(&gd_str).is_absolute() {
1795 PathBuf::from(&gd_str)
1796 } else {
1797 root.join(&gd_str)
1798 };
1799 let cd_path = if Path::new(&cd_str).is_absolute() {
1800 PathBuf::from(&cd_str)
1801 } else {
1802 root.join(&cd_str)
1803 };
1804 let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
1805 let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
1806 gd_canon != cd_canon
1807 }
1808 _ => false,
1809 }
1810}
1811
1812pub fn has_wt_component(path: &Path) -> bool {
1814 path.components().any(|c| c.as_os_str() == ".wt")
1815}
1816
1817pub fn is_worktree_clean(wt_path: &Path) -> bool {
1820 let out = std::process::Command::new("git")
1821 .arg("-C")
1822 .arg(wt_path.as_os_str())
1823 .args(["status", "--porcelain", "-u"])
1824 .output();
1825 match out {
1826 Ok(o) if o.status.success() => {
1827 let stdout = String::from_utf8_lossy(&o.stdout);
1828 for line in stdout.lines() {
1829 let trimmed = line.trim();
1830 if trimmed.is_empty() {
1831 continue;
1832 }
1833 if line.len() < 3 {
1834 return false;
1835 }
1836 let mut path_part = line[3..].trim();
1837 if let Some((_, new_path)) = path_part.split_once(" -> ") {
1838 path_part = new_path.trim();
1839 }
1840 let unquoted = path_part
1841 .strip_prefix('"')
1842 .and_then(|p| p.strip_suffix('"'))
1843 .unwrap_or(path_part);
1844 if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
1845 return false;
1846 }
1847 }
1848 true
1849 }
1850 _ => false,
1851 }
1852}
1853
1854pub fn report_other_worktrees(root: &Path) {
1858 if is_linked_worktree(root) {
1861 return;
1862 }
1863
1864 let worktrees = parse_worktree_list(root);
1865 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1866 let main_canon = worktrees
1867 .first()
1868 .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
1869
1870 let mut other_count = 0;
1871 let mut other_bytes = 0;
1872
1873 for (idx, wt) in worktrees.into_iter().enumerate() {
1874 if idx == 0 {
1876 continue;
1877 }
1878 if wt.is_bare {
1879 continue;
1880 }
1881 if !wt.path.exists() {
1882 continue;
1883 }
1884
1885 let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
1886 if wt_canon == root_canon || wt.path == root {
1888 continue;
1889 }
1890 if Some(&wt_canon) == main_canon.as_ref() {
1891 continue;
1892 }
1893 if has_wt_component(&wt.path) || has_wt_component(&wt_canon) {
1895 continue;
1896 }
1897
1898 let is_merged = if let Some(ref branch) = wt.branch {
1900 is_branch_merged(root, branch)
1901 } else if let Some(ref sha) = wt.head_sha {
1902 is_commit_merged(root, sha)
1903 } else {
1904 false
1905 };
1906
1907 if !is_merged {
1908 continue;
1909 }
1910
1911 if !is_worktree_clean(&wt.path) {
1913 continue;
1914 }
1915
1916 let size = dir_size(&wt.path);
1917 let path_str = display_worktree_path(&wt.path, root);
1918 let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
1919 wt.head_sha
1920 .as_deref()
1921 .map(|s| &s[..s.len().min(7)])
1922 .unwrap_or("detached")
1923 });
1924
1925 println!(
1926 "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
1927 format_size(size)
1928 );
1929
1930 other_count += 1;
1931 other_bytes += size;
1932 }
1933
1934 if other_count > 0 {
1935 println!(
1936 "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
1937 format_size(other_bytes)
1938 );
1939 }
1940}
1941
1942struct CleanLockGuard(PathBuf);
1943
1944impl Drop for CleanLockGuard {
1945 fn drop(&mut self) {
1946 let _ = std::fs::remove_file(&self.0);
1947 }
1948}
1949
1950enum LockOutcome {
1951 Acquired(CleanLockGuard),
1952 AlreadyRunning,
1953 Error(String),
1954}
1955
1956fn acquire_clean_lock(root: &Path) -> LockOutcome {
1957 use std::io::Write;
1958 let wt_dir = root.join(".wt");
1959 if let Err(e) = std::fs::create_dir_all(&wt_dir) {
1960 return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
1961 }
1962 let lock_path = wt_dir.join("clean.lock");
1963 let pid_str = format!("{}\n", std::process::id());
1964
1965 match std::fs::OpenOptions::new()
1966 .write(true)
1967 .create_new(true)
1968 .open(&lock_path)
1969 {
1970 Ok(mut f) => {
1971 if let Err(e) = f.write_all(pid_str.as_bytes()) {
1972 let _ = std::fs::remove_file(&lock_path);
1973 return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
1974 }
1975 LockOutcome::Acquired(CleanLockGuard(lock_path))
1976 }
1977 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1978 let contents = match std::fs::read_to_string(&lock_path) {
1979 Ok(c) => c,
1980 Err(read_err) => {
1981 return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
1982 }
1983 };
1984 let old_pid: i64 = match contents.trim().parse() {
1985 Ok(p) => p,
1986 Err(parse_err) => {
1987 return LockOutcome::Error(format!(
1988 "{}: invalid pid: {parse_err}",
1989 lock_path.display()
1990 ));
1991 }
1992 };
1993 if is_pid_alive(old_pid) {
1994 return LockOutcome::AlreadyRunning;
1995 }
1996 eprintln!(
1997 "replacing stale {} from dead pid {old_pid}",
1998 lock_path.display()
1999 );
2000 if let Err(rm_err) = std::fs::remove_file(&lock_path) {
2001 return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
2002 }
2003 match std::fs::OpenOptions::new()
2004 .write(true)
2005 .create_new(true)
2006 .open(&lock_path)
2007 {
2008 Ok(mut f) => {
2009 if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
2010 let _ = std::fs::remove_file(&lock_path);
2011 return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
2012 }
2013 LockOutcome::Acquired(CleanLockGuard(lock_path))
2014 }
2015 Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
2016 }
2017 }
2018 Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
2019 }
2020}
2021
2022pub fn run(args: &crate::cli::CleanArgs) -> i32 {
2024 if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
2025 eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
2026 return 2;
2027 }
2028
2029 let repos = if args.all {
2030 crate::registry::registered()
2031 } else {
2032 match find_repo_root() {
2033 Ok(root) => vec![root],
2034 Err(e) => {
2035 eprintln!("error: {e}");
2036 return 2;
2037 }
2038 }
2039 };
2040
2041 let _lock_guard = if args.quiet {
2042 let Some(root) = repos.first() else {
2043 eprintln!("error: blyte clean --quiet found no repository to clean");
2044 return 1;
2045 };
2046 match acquire_clean_lock(root) {
2047 LockOutcome::Acquired(guard) => Some(guard),
2048 LockOutcome::AlreadyRunning => return 0,
2049 LockOutcome::Error(e) => {
2050 eprintln!("error: {e}");
2051 return 1;
2052 }
2053 }
2054 } else {
2055 None
2056 };
2057
2058 let mut total_freed = 0;
2059 for repo in &repos {
2060 let stats = clean_repo(
2061 repo,
2062 args.older_than,
2063 args.dry_run,
2064 args.skip.as_deref(),
2065 args.quiet,
2066 );
2067 total_freed += stats.freed_bytes;
2068 }
2069
2070 if !args.quiet {
2071 if args.dry_run {
2072 println!("would free {}", format_size(total_freed));
2073 } else {
2074 println!("freed {}", format_size(total_freed));
2075 }
2076 }
2077
2078 0
2079}
2080
2081fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
2082 let del_out = std::process::Command::new("git")
2083 .args(["branch", "-D", branch_name])
2084 .current_dir(root)
2085 .output()
2086 .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
2087 if !del_out.status.success() {
2088 return Err(format!(
2089 "git branch -D {branch_name}: {}",
2090 String::from_utf8_lossy(&del_out.stderr).trim()
2091 ));
2092 }
2093 Ok(())
2094}
2095
2096pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
2099 let wt_path = root.join(".wt").join(id);
2100 let branch_name = format!("wip/{id}");
2101 let mut ctx = CleanContext::new(root);
2102
2103 if wt_path.exists() {
2104 let reason = match ctx.check_removable(id, u64::MAX) {
2105 Ok(
2106 r @ (RemovalReason::Merged
2107 | RemovalReason::MergedInto(_)
2108 | RemovalReason::MergedThrough(_)
2109 | RemovalReason::NoChanges),
2110 ) => r,
2111 Ok(
2112 RemovalReason::Verdict(_)
2113 | RemovalReason::OlderThan(_)
2114 | RemovalReason::ResearchReport,
2115 )
2116 | Err(_) => return Ok(None),
2117 };
2118 if has_uncommitted_changes(&wt_path) {
2119 return Ok(None);
2120 }
2121
2122 let wt_rel = format!(".wt/{id}");
2123 let rm_out = std::process::Command::new("git")
2124 .args(["worktree", "remove", &wt_rel])
2125 .current_dir(root)
2126 .output()
2127 .map_err(|e| format!("git worktree remove {wt_rel}: {e}"))?;
2128 if !rm_out.status.success() {
2129 return Err(format!(
2130 "git worktree remove {wt_rel}: {}",
2131 String::from_utf8_lossy(&rm_out.stderr).trim()
2132 ));
2133 }
2134
2135 if ctx.get_branch_tip(&branch_name).is_some() {
2136 delete_wip_branch_strict(root, &branch_name)?;
2137 }
2138
2139 return Ok(Some(reason.to_string()));
2140 }
2141
2142 if ctx.get_branch_tip(&branch_name).is_some() {
2143 if !is_branch_merged(root, &branch_name) {
2144 return Ok(None);
2145 }
2146 let reason = ctx
2147 .check_run_merged(id)
2148 .unwrap_or(RemovalReason::Merged)
2149 .to_string();
2150 delete_wip_branch_strict(root, &branch_name)?;
2151 return Ok(Some(reason));
2152 }
2153
2154 Ok(None)
2155}
2156
2157pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
2159 let res: Result<(), std::io::Error> = (|| {
2160 let wt_dir = root.join(".wt");
2161 std::fs::create_dir_all(&wt_dir)?;
2162 let log_file = std::fs::OpenOptions::new()
2163 .create(true)
2164 .append(true)
2165 .open(wt_dir.join("clean.log"))?;
2166 let stderr_file = log_file.try_clone()?;
2167 let exe = std::env::current_exe()?;
2168 let mut cmd = std::process::Command::new(exe);
2169 cmd.arg("clean").arg("--quiet");
2170 if let Some(id) = skip_id {
2171 cmd.arg("--skip").arg(id);
2172 }
2173 cmd.current_dir(root)
2174 .stdin(std::process::Stdio::null())
2175 .stdout(std::process::Stdio::from(log_file))
2176 .stderr(std::process::Stdio::from(stderr_file));
2177 let _child = cmd.spawn()?;
2178 Ok(())
2179 })();
2180 if let Err(e) = res {
2181 eprintln!("warning: could not start the background clean: {e}");
2182 }
2183}
2184
2185pub fn clean_on_review(root: &Path, id: &str) {
2190 let wt_path = root.join(".wt").join(id);
2191 if !wt_path.exists() {
2192 spawn_background_clean(root, Some(id));
2193 return;
2194 }
2195
2196 let mut ctx = CleanContext::new(root);
2197 let branch_name = format!("wip/{id}");
2198 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2199
2200 let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
2201 let verdict_str = std::fs::read_to_string(&verdict_path)
2202 .ok()
2203 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2204 .and_then(|v| {
2205 v.get("verdict")
2206 .and_then(|s| s.as_str())
2207 .map(|s| s.to_string())
2208 })
2209 .unwrap_or_default();
2210
2211 let is_res = ctx.is_research_run(id);
2212 let removable = match ctx.check_removable(id, 14) {
2213 Ok(_) => is_res || !has_uncommitted_changes(&wt_path),
2214 Err(_) => false,
2215 };
2216
2217 if !removable {
2218 if verdict_str == "accepted" || verdict_str == "fixed" {
2219 println!("worktree .wt/{id} kept until {branch_name} is merged");
2220 }
2221 spawn_background_clean(root, Some(id));
2222 return;
2223 }
2224
2225 let removed_ok = if is_res {
2226 std::fs::remove_dir_all(&wt_path).is_ok()
2227 } else {
2228 let rm_out = std::process::Command::new("git")
2229 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2230 .current_dir(root)
2231 .output();
2232 let _ = std::process::Command::new("git")
2233 .args(["worktree", "prune"])
2234 .current_dir(root)
2235 .output();
2236 rm_out.map(|o| o.status.success()).unwrap_or(false)
2237 };
2238
2239 if !removed_ok {
2240 if verdict_str == "accepted" || verdict_str == "fixed" {
2241 println!("worktree .wt/{id} kept until {branch_name} is merged");
2242 }
2243 spawn_background_clean(root, Some(id));
2244 return;
2245 }
2246
2247 if branch_exists {
2248 let is_merged = ctx.check_run_merged(id).is_some();
2249 if is_merged {
2250 let del_out = std::process::Command::new("git")
2251 .args(["branch", "-D", &branch_name])
2252 .current_dir(root)
2253 .output();
2254 if del_out.map(|o| o.status.success()).unwrap_or(false) {
2255 ctx.wip_branch_tips.remove(&branch_name);
2256 println!("removed .wt/{id}; branch {branch_name} deleted");
2257 } else {
2258 println!("removed .wt/{id}; branch {branch_name} kept");
2259 }
2260 } else {
2261 println!("removed .wt/{id}; branch {branch_name} kept");
2262 }
2263 } else {
2264 println!("removed .wt/{id}");
2265 }
2266
2267 spawn_background_clean(root, Some(id));
2268}