As we saw in previous posts of this series Commits are the first-class citizens in Git worlds, not the Branches. But, branch names do show up in our commit messages and a few more places. Moreover, build-pipelines and other agile tools are often set up to refer to branch names with predetermined patterns.
Therefore, organizations set up some nomenclature around branch naming. Branch naming strategies are not the topic of this post, the topic is, how to change the branch name if it's not adhering to your organization's standards.
Create the problem
Let's first set up our problem case.
- Let's say we have a repo named
git-renaming
in local as well as remote - Let's create a feature branch and name it incorrectly
git checkout -b feature/master-incorrect-name
- Let's commit a new file in this branch
echo “file1” >> file1 && git add file1 && git commit -m “second commit”
- Let's push this branch with the wrong name to remote.
git push -u origin HEAD
Now we have a branch with the wrong name at local as well as at remote, Next, we will see the step to fix it.
Correct the problem
Before going into fixing things, let's verify what we have
Run below command
git branch -a
Rename the branch at local
Let’s rename the branch to the correct name at local.
Make sure you are on the branch that you want to rename.
Use the below command
git branch -m feature/master-correct-name
Fix the remote branch
Until now we have renamed only the local branch. See highlighted line below, this branch is still tracked with a branch from remote with the old name
Unfortunately, by using the command line, can not rename the remote branch, so we will
- Push the branch with the correct name to remote
git push -u origin HEAD
- Delete the branch at remote with the incorrect name.
git push origin --delete feature/master-incorrect-name
That's all. That's how we rename a pushed branch in git.
Comments