Skip to main content

git_cli/
branch.rs

1use crate::commit_shared::{git_output, git_status_success, git_stdout_trimmed};
2use crate::prompt;
3use crate::worktree;
4use std::collections::HashSet;
5use std::process::Output;
6
7pub fn dispatch(cmd: &str, args: &[String]) -> Option<i32> {
8    match cmd {
9        "cleanup" | "delete-merged" => Some(run_cleanup(args)),
10        _ => None,
11    }
12}
13
14struct CleanupArgs {
15    base_ref: String,
16    squash_mode: bool,
17    remove_worktrees: bool,
18    help: bool,
19}
20
21fn run_cleanup(args: &[String]) -> i32 {
22    let parsed = match parse_args(args) {
23        Ok(value) => value,
24        Err(code) => return code,
25    };
26
27    if parsed.help {
28        print_help();
29        return 0;
30    }
31
32    if !git_status_success(&["rev-parse", "--is-inside-work-tree"]) {
33        eprintln!("❌ Not in a git repository");
34        return 1;
35    }
36
37    let base_ref = parsed.base_ref;
38    let squash_mode = parsed.squash_mode;
39    let remove_worktrees = parsed.remove_worktrees;
40
41    if !git_status_success(&["rev-parse", "--verify", "--quiet", &base_ref]) {
42        eprintln!("❌ Invalid base ref: {base_ref}");
43        return 1;
44    }
45
46    let base_commit = match git_stdout_trimmed(&["rev-parse", &format!("{base_ref}^{{commit}}")]) {
47        Ok(value) => value,
48        Err(_) => {
49            eprintln!("❌ Unable to resolve base commit: {base_ref}");
50            return 1;
51        }
52    };
53
54    let head_commit = match git_stdout_trimmed(&["rev-parse", "HEAD"]) {
55        Ok(value) => value,
56        Err(_) => {
57            eprintln!("❌ Unable to resolve HEAD commit");
58            return 1;
59        }
60    };
61
62    let delete_flag = if base_commit != head_commit {
63        "-D"
64    } else {
65        "-d"
66    };
67
68    let current_branch = match git_stdout_trimmed(&["rev-parse", "--abbrev-ref", "HEAD"]) {
69        Ok(value) => value,
70        Err(_) => {
71            eprintln!("❌ Unable to resolve current branch");
72            return 1;
73        }
74    };
75
76    let mut protected: HashSet<String> = ["main", "master", "develop", "trunk"]
77        .iter()
78        .map(|name| (*name).to_string())
79        .collect();
80
81    if current_branch != "HEAD" {
82        protected.insert(current_branch.clone());
83    }
84    protected.insert(base_ref.clone());
85
86    if let Some(base_local) = resolve_base_local(&base_ref) {
87        protected.insert(base_local);
88    }
89
90    let merged_branches = match git_output(&[
91        "for-each-ref",
92        "--merged",
93        &base_ref,
94        "--format=%(refname:short)",
95        "refs/heads",
96    ]) {
97        Ok(output) => parse_lines(&output),
98        Err(err) => {
99            eprintln!("{err:#}");
100            return 1;
101        }
102    };
103
104    let mut merged_set: HashSet<String> = HashSet::new();
105    for branch in &merged_branches {
106        merged_set.insert(branch.clone());
107    }
108
109    let linked_worktrees = match worktree::linked_worktrees_by_branch() {
110        Ok(value) => value,
111        Err(err) => {
112            eprintln!("{err:#}");
113            return 1;
114        }
115    };
116
117    if !squash_mode && merged_branches.is_empty() {
118        println!("✅ No merged local branches found.");
119        return 0;
120    }
121
122    let mut candidates: Vec<String> = Vec::new();
123
124    if squash_mode {
125        let local_branches =
126            match git_output(&["for-each-ref", "--format=%(refname:short)", "refs/heads"]) {
127                Ok(output) => parse_lines(&output),
128                Err(err) => {
129                    eprintln!("{err:#}");
130                    return 1;
131                }
132            };
133
134        if local_branches.is_empty() {
135            println!("✅ No local branches found.");
136            return 0;
137        }
138
139        for branch in local_branches {
140            if protected.contains(&branch) {
141                continue;
142            }
143
144            if merged_set.contains(&branch) {
145                candidates.push(branch);
146                continue;
147            }
148
149            // Providers squash a branch's commits into a single commit on base,
150            // so the branch's per-commit patch ids never match a plain
151            // `git cherry base branch`. Collapse the branch's whole diff into one
152            // synthetic commit on top of the merge-base, then ask whether base
153            // already contains a patch-equivalent commit.
154            let merge_base = match git_stdout_trimmed(&["merge-base", &base_ref, &branch]) {
155                Ok(value) => value,
156                // No merge-base means unrelated history (e.g. an orphan fixture
157                // branch). It cannot be a squash-merge of base, so skip it
158                // instead of aborting the whole sweep.
159                Err(_) => continue,
160            };
161
162            let branch_tree =
163                match git_stdout_trimmed(&["rev-parse", &format!("{branch}^{{tree}}")]) {
164                    Ok(value) => value,
165                    Err(_) => {
166                        eprintln!("❌ Failed to resolve tree for {branch}");
167                        return 1;
168                    }
169                };
170
171            let squashed_commit = match git_stdout_trimmed(&[
172                "commit-tree",
173                &branch_tree,
174                "-p",
175                &merge_base,
176                "-m",
177                "squash-detect",
178            ]) {
179                Ok(value) => value,
180                Err(_) => {
181                    eprintln!("❌ Failed to synthesize squash commit for {branch}");
182                    return 1;
183                }
184            };
185
186            let cherry_output = match git_output(&["cherry", &base_ref, &squashed_commit]) {
187                Ok(output) => output,
188                Err(_) => {
189                    eprintln!("❌ Failed to compare {branch} against {base_ref}");
190                    return 1;
191                }
192            };
193
194            let cherry_text = String::from_utf8_lossy(&cherry_output.stdout);
195            let has_plus = cherry_text.lines().any(|line| line.starts_with('+'));
196            if has_plus {
197                continue;
198            }
199
200            candidates.push(branch);
201        }
202    } else {
203        for branch in merged_branches {
204            if protected.contains(&branch) {
205                continue;
206            }
207            candidates.push(branch);
208        }
209    }
210
211    if candidates.is_empty() {
212        if squash_mode {
213            println!("✅ No deletable branches found.");
214        } else {
215            println!("✅ No deletable merged branches.");
216        }
217        return 0;
218    }
219
220    if squash_mode {
221        println!("🧹 Branches to delete (base: {base_ref}, mode: squash):");
222    } else {
223        println!("🧹 Merged branches to delete (base: {base_ref}):");
224    }
225    for branch in &candidates {
226        println!("  - {branch}");
227    }
228
229    if remove_worktrees {
230        let removable_worktrees: Vec<_> = candidates
231            .iter()
232            .filter_map(|branch| {
233                linked_worktrees
234                    .get(branch)
235                    .map(|worktree_path| (branch, worktree_path))
236            })
237            .collect();
238
239        if !removable_worktrees.is_empty() {
240            println!("⚠️  Linked worktrees to remove (--remove-worktrees):");
241            for (branch, worktree_path) in removable_worktrees {
242                println!("  - {branch}: {worktree_path}");
243            }
244        }
245    }
246
247    if prompt::confirm_or_abort("❓ Proceed with deleting these branches? [y/N] ").is_err() {
248        return 1;
249    }
250
251    let mut deleted_count = 0usize;
252    let mut removed_worktrees_count = 0usize;
253    let mut failed_deletions: Vec<(String, String)> = Vec::new();
254
255    for branch in &candidates {
256        let mut branch_delete_flag = delete_flag;
257        if delete_flag == "-d" && squash_mode && !merged_set.contains(branch) {
258            branch_delete_flag = "-D";
259        }
260
261        if remove_worktrees && let Some(worktree_path) = linked_worktrees.get(branch) {
262            match git_output(&["worktree", "remove", "--force", worktree_path]) {
263                Ok(_) => {
264                    removed_worktrees_count += 1;
265                }
266                Err(err) => {
267                    failed_deletions.push((
268                        branch.clone(),
269                        format!(
270                            "failed to remove linked worktree {worktree_path}: {}",
271                            summarize_git_error(&err.to_string())
272                        ),
273                    ));
274                    continue;
275                }
276            }
277        }
278
279        match git_output(&["branch", branch_delete_flag, "--", branch]) {
280            Ok(_) => {
281                deleted_count += 1;
282            }
283            Err(err) => {
284                failed_deletions.push((branch.clone(), summarize_git_error(&err.to_string())));
285            }
286        }
287    }
288
289    if removed_worktrees_count > 0 {
290        println!("✅ Removed {removed_worktrees_count} linked worktree(s).");
291    }
292
293    if !failed_deletions.is_empty() {
294        if deleted_count > 0 {
295            println!("✅ Deleted {deleted_count} branch(es).");
296        }
297
298        eprintln!(
299            "⚠️  Failed to delete {} branch(es):",
300            failed_deletions.len()
301        );
302        for (branch, reason) in &failed_deletions {
303            eprintln!("  - {branch}: {reason}");
304        }
305        return 1;
306    }
307
308    println!("✅ Deleted {deleted_count} branch(es).");
309    0
310}
311
312fn parse_args(args: &[String]) -> Result<CleanupArgs, i32> {
313    let mut base_ref = "HEAD".to_string();
314    let mut squash_mode = false;
315    let mut remove_worktrees = false;
316    let mut help = false;
317
318    let mut i = 0usize;
319    while i < args.len() {
320        match args[i].as_str() {
321            "-h" | "--help" => {
322                help = true;
323            }
324            "-s" | "--squash" => {
325                squash_mode = true;
326            }
327            "-w" | "--remove-worktrees" => {
328                remove_worktrees = true;
329            }
330            "-b" | "--base" => {
331                let Some(value) = args.get(i + 1) else {
332                    return Err(2);
333                };
334                base_ref = value.to_string();
335                i += 1;
336            }
337            _ => {}
338        }
339        i += 1;
340    }
341
342    Ok(CleanupArgs {
343        base_ref,
344        squash_mode,
345        remove_worktrees,
346        help,
347    })
348}
349
350fn print_help() {
351    println!(
352        "Usage: git-delete-merged-branches [-b|--base <ref>] [-s|--squash] [-w|--remove-worktrees]"
353    );
354    println!("  -b, --base <ref>  Base ref used to determine merged branches (default: HEAD)");
355    println!("  -s, --squash      Include branches whose squashed diff already landed on base");
356    println!("  -w, --remove-worktrees  Force-remove linked worktrees for candidate branches");
357}
358
359fn parse_lines(output: &Output) -> Vec<String> {
360    String::from_utf8_lossy(&output.stdout)
361        .lines()
362        .filter(|line| !line.trim().is_empty())
363        .map(|line| line.to_string())
364        .collect()
365}
366
367fn summarize_git_error(message: &str) -> String {
368    let trimmed = message.trim();
369    let summary = trimmed
370        .rsplit_once(" failed: ")
371        .map(|(_, suffix)| suffix.trim())
372        .unwrap_or(trimmed);
373    summary.replace('\n', " ")
374}
375
376fn resolve_base_local(base_ref: &str) -> Option<String> {
377    let remote_ref = format!("refs/remotes/{base_ref}");
378    if git_status_success(&["show-ref", "--verify", "--quiet", &remote_ref]) {
379        return Some(
380            base_ref
381                .split_once('/')
382                .map(|(_, tail)| tail.to_string())
383                .unwrap_or_else(|| base_ref.to_string()),
384        );
385    }
386
387    let local_ref = format!("refs/heads/{base_ref}");
388    if git_status_success(&["show-ref", "--verify", "--quiet", &local_ref]) {
389        return Some(base_ref.to_string());
390    }
391
392    None
393}
394
395#[cfg(test)]
396mod tests {
397    use super::{dispatch, parse_args, parse_lines, resolve_base_local, summarize_git_error};
398    use crate::worktree;
399    use nils_test_support::{EnvGuard, GlobalStateLock, StubBinDir};
400    use pretty_assertions::assert_eq;
401    use std::process::Command;
402
403    #[test]
404    fn dispatch_unknown_returns_none() {
405        assert_eq!(dispatch("unknown", &[]), None);
406    }
407
408    #[test]
409    fn cleanup_help_exits_success_without_git_runtime() {
410        let args = vec!["--help".to_string()];
411        assert_eq!(dispatch("cleanup", &args), Some(0));
412        assert_eq!(dispatch("delete-merged", &args), Some(0));
413    }
414
415    #[test]
416    fn parse_args_supports_base_and_squash_flags() {
417        let args = vec![
418            "--base".to_string(),
419            "origin/main".to_string(),
420            "--squash".to_string(),
421            "--remove-worktrees".to_string(),
422            "--unknown".to_string(),
423        ];
424        let parsed = parse_args(&args).expect("parsed");
425        assert_eq!(parsed.base_ref, "origin/main");
426        assert!(parsed.squash_mode);
427        assert!(parsed.remove_worktrees);
428        assert!(!parsed.help);
429    }
430
431    #[test]
432    fn parse_args_requires_value_for_base_flag() {
433        let args = vec!["--base".to_string()];
434        let err_code = match parse_args(&args) {
435            Ok(_) => panic!("expected usage error"),
436            Err(code) => code,
437        };
438        assert_eq!(err_code, 2);
439    }
440
441    #[test]
442    fn parse_lines_skips_blank_entries() {
443        let output = Command::new("/bin/sh")
444            .arg("-c")
445            .arg("printf 'main\\n\\nfeature/a\\n'")
446            .output()
447            .expect("output");
448        let lines = parse_lines(&output);
449        assert_eq!(lines, vec!["main".to_string(), "feature/a".to_string()]);
450    }
451
452    #[test]
453    fn summarize_git_error_strips_prefix_and_normalizes_lines() {
454        let message =
455            "git [\"branch\", \"-d\"] failed: error: cannot delete branch\nhint: checked out";
456        let summary = summarize_git_error(message);
457        assert_eq!(summary, "error: cannot delete branch hint: checked out");
458    }
459
460    #[test]
461    fn linked_worktrees_by_branch_parses_porcelain_output() {
462        let lock = GlobalStateLock::new();
463        let stubs = StubBinDir::new();
464        stubs.write_exe(
465            "git",
466            r#"#!/bin/bash
467set -euo pipefail
468if [[ "${1:-}" == "worktree" && "${2:-}" == "list" && "${3:-}" == "--porcelain" ]]; then
469  printf 'worktree /repo\n'
470  printf 'HEAD 1111111111111111111111111111111111111111\n'
471  printf 'branch refs/heads/main\n'
472  printf '\n'
473  printf 'worktree /repo/wt/topic\n'
474  printf 'HEAD 2222222222222222222222222222222222222222\n'
475  printf 'branch refs/heads/feature/topic\n'
476  exit 0
477fi
478exit 1
479"#,
480        );
481
482        let _guard = EnvGuard::set(&lock, "PATH", &stubs.path_str());
483        let mapping = worktree::linked_worktrees_by_branch().expect("parse linked worktrees");
484        assert_eq!(
485            mapping.get("feature/topic"),
486            Some(&"/repo/wt/topic".to_string())
487        );
488        assert_eq!(mapping.get("main"), Some(&"/repo".to_string()));
489    }
490
491    #[test]
492    fn resolve_base_local_prefers_remote_then_local_then_none() {
493        let lock = GlobalStateLock::new();
494
495        let remote_stubs = StubBinDir::new();
496        remote_stubs.write_exe(
497            "git",
498            r#"#!/bin/bash
499set -euo pipefail
500if [[ "${1:-}" == "show-ref" && "${2:-}" == "--verify" && "${3:-}" == "--quiet" ]]; then
501  if [[ "${4:-}" == "refs/remotes/origin/main" ]]; then
502    exit 0
503  fi
504  exit 1
505fi
506exit 1
507"#,
508        );
509        let remote_guard = EnvGuard::set(&lock, "PATH", &remote_stubs.path_str());
510        assert_eq!(resolve_base_local("origin/main"), Some("main".to_string()));
511        drop(remote_guard);
512
513        let local_stubs = StubBinDir::new();
514        local_stubs.write_exe(
515            "git",
516            r#"#!/bin/bash
517set -euo pipefail
518if [[ "${1:-}" == "show-ref" && "${2:-}" == "--verify" && "${3:-}" == "--quiet" ]]; then
519  if [[ "${4:-}" == "refs/heads/main" ]]; then
520    exit 0
521  fi
522  exit 1
523fi
524exit 1
525"#,
526        );
527        let local_guard = EnvGuard::set(&lock, "PATH", &local_stubs.path_str());
528        assert_eq!(resolve_base_local("main"), Some("main".to_string()));
529        drop(local_guard);
530
531        let none_stubs = StubBinDir::new();
532        none_stubs.write_exe(
533            "git",
534            r#"#!/bin/bash
535set -euo pipefail
536exit 1
537"#,
538        );
539        let _none_guard = EnvGuard::set(&lock, "PATH", &none_stubs.path_str());
540        assert_eq!(resolve_base_local("feature/topic"), None);
541    }
542}