Skip to main content

thor_wt/
clean.rs

1use std::process::Command;
2
3/// Result of a clean operation.
4pub struct CleanResult {
5    pub pruned: bool,
6    pub deleted_branches: Vec<String>,
7}
8
9/// Prune worktrees and optionally delete branches merged into main.
10pub fn clean(delete_merged: bool) -> anyhow::Result<CleanResult> {
11    // Prune stale worktree references
12    let prune = Command::new("git")
13        .args(["worktree", "prune"])
14        .status()?;
15    let pruned = prune.success();
16
17    let mut deleted_branches = Vec::new();
18
19    if delete_merged {
20        // Get branches merged into main
21        let output = Command::new("git")
22            .args(["branch", "--merged", "main"])
23            .output()?;
24
25        if output.status.success() {
26            let stdout = String::from_utf8_lossy(&output.stdout);
27            for line in stdout.lines() {
28                let branch = line.trim().trim_start_matches("* ");
29                // Skip main, master, and current branch
30                if branch == "main" || branch == "master" || branch.is_empty() || line.trim().starts_with('*') {
31                    continue;
32                }
33
34                let del = Command::new("git")
35                    .args(["branch", "-d", branch])
36                    .status();
37
38                if del.map(|s| s.success()).unwrap_or(false) {
39                    deleted_branches.push(branch.to_string());
40                }
41            }
42        }
43    }
44
45    Ok(CleanResult { pruned, deleted_branches })
46}