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
10pub 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 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(¤t_branch, new_name) {
40 println!("{new_name}");
41 return Ok(());
42 }
43
44 let current_branch1 = ¤t_branch;
45 println!("{current_branch1}");
46
47 BranchOperations::rename(new_name)
49 .map_err(|e| GitXError::GitCommand(format!("Failed to rename local branch: {e}")))?;
50
51 RemoteOperations::push(Some("origin"), Some(new_name))
53 .map_err(|e| GitXError::GitCommand(format!("Failed to push new branch: {e}")))?;
54
55 match GitOperations::run_status(&["push", "origin", "--delete", ¤t_branch]) {
57 Ok(()) => {
58 let old_branch = ¤t_branch;
59 println!("Deleted old branch '{old_branch}' from origin.");
60 }
61 Err(_) => {
62 let old_branch = ¤t_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}