git_x/
rename_branch.rs

1use crate::GitXError;
2use crate::command::Command;
3use crate::core::git::{BranchOperations, GitOperations, RemoteOperations};
4
5pub fn run(new_name: &str) -> Result<(), GitXError> {
6    let cmd = RenameBranchCommand;
7    cmd.execute(new_name.to_string())
8}
9
10/// Command implementation for git rename-branch
11pub struct RenameBranchCommand;
12
13impl Command for RenameBranchCommand {
14    type Input = String;
15    type Output = ();
16
17    fn execute(&self, new_name: String) -> Result<(), GitXError> {
18        run_rename_branch(&new_name)
19    }
20
21    fn name(&self) -> &'static str {
22        "rename-branch"
23    }
24
25    fn description(&self) -> &'static str {
26        "Rename the current branch both locally and remotely"
27    }
28
29    fn is_destructive(&self) -> bool {
30        true
31    }
32}
33
34fn run_rename_branch(new_name: &str) -> Result<(), GitXError> {
35    // Step 1: Get current branch name
36    let current_branch = GitOperations::current_branch()
37        .map_err(|e| GitXError::GitCommand(format!("Failed to get current branch: {e}")))?;
38
39    if is_branch_already_named(&current_branch, new_name) {
40        println!("{new_name}");
41        return Ok(());
42    }
43
44    let current_branch1 = &current_branch;
45    println!("{current_branch1}");
46
47    // Step 2: Rename branch locally
48    BranchOperations::rename(new_name)
49        .map_err(|e| GitXError::GitCommand(format!("Failed to rename local branch: {e}")))?;
50
51    // Step 3: Push the new branch to origin
52    RemoteOperations::push(Some("origin"), Some(new_name))
53        .map_err(|e| GitXError::GitCommand(format!("Failed to push new branch: {e}")))?;
54
55    // Step 4: Delete the old branch from origin
56    match GitOperations::run_status(&["push", "origin", "--delete", &current_branch]) {
57        Ok(()) => {
58            let old_branch = &current_branch;
59            println!("Deleted old branch '{old_branch}' from origin.");
60        }
61        Err(_) => {
62            let old_branch = &current_branch;
63            eprintln!("Warning: Failed to delete old branch '{old_branch}' from origin.");
64        }
65    }
66
67    println!("Branch renamed successfully.");
68    Ok(())
69}
70
71fn is_branch_already_named(current_branch: &str, new_name: &str) -> bool {
72    current_branch == new_name
73}