git_x/
rename_branch.rs

1use std::process::{Command, exit};
2
3pub fn run(new_name: &str) {
4    // Step 1: Get current branch name
5    let output = Command::new("git")
6        .args(["rev-parse", "--abbrev-ref", "HEAD"])
7        .output()
8        .expect("Failed to execute git");
9
10    if !output.status.success() {
11        eprintln!("Error: Failed to get current branch name.");
12        exit(1);
13    }
14
15    let current_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
16
17    if current_branch == new_name {
18        println!("Current branch is already named '{new_name}'. Nothing to do.");
19        return;
20    }
21
22    println!("Renaming branch '{current_branch}' to '{new_name}'");
23
24    // Step 2: Rename branch locally
25    let status = Command::new("git")
26        .args(["branch", "-m", new_name])
27        .status()
28        .expect("Failed to rename branch");
29
30    if !status.success() {
31        eprintln!("Error: Failed to rename local branch.");
32        exit(1);
33    }
34
35    // Step 3: Push the new branch to origin
36    let status = Command::new("git")
37        .args(["push", "-u", "origin", new_name])
38        .status()
39        .expect("Failed to push new branch");
40
41    if !status.success() {
42        eprintln!("Error: Failed to push new branch to origin.");
43        exit(1);
44    }
45
46    // Step 4: Delete the old branch from origin
47    let status = Command::new("git")
48        .args(["push", "origin", "--delete", &current_branch])
49        .status()
50        .expect("Failed to delete old branch");
51
52    if !status.success() {
53        eprintln!("Warning: Failed to delete old branch '{current_branch}' from origin.");
54    } else {
55        println!("Deleted old branch '{current_branch}' from origin.");
56    }
57
58    println!("Branch renamed successfully.");
59}