From time to time I usually create a branch and then start messing with the code, and then I realize that what I'm doing has nothing to do with the name of that branch.
So how do I rename a branch? According to the documentation, to rename a local branch in git there's only one command: git branch -m "new-name".
Simple, right? But there are other things to learn about renaming a branch.
How to rename a local branch
If you are already in the branch you want to change the name, use:
git branch -m "new-name"
If you want to change the name of another branch, while in the master, for example, use:
git branch -m "old-name" "new-name"
In some cases, you may want to change only the capitalization of some letter. To do this, you should use
git branch -M with the capital M. According to the documentation (
git branch -h), this parameter changes the name, even if it already exists. Just be careful not to use -M and overwrite another important branch by mistake.
How to rename a remote branch
Unfortunately, there is no command that changes the name of the remote branch directly in Github, Bitbucket, etc., but we can remove and resend the branch with the desired name.
First, we must change the name of our local branch as explained above:
git branch -m "new-name"
Warning: The method below excludes the remote branch. Make sure you have the latest version of the remote branch in your local repository so you can push it right away.
Note: Replace "old-name" below with the old name of your branch to remove it.
git push origin :old-name
The following command sends the renamed branch to the remote repository
git push --set-upstream origin new-name
That's it. Both your local and remote branch have been renamed.
What about the right way?
By the title of this article, I mean how to name a branch in the most correct manner according to common conventions and practices.
A convention, in practice, is an agreement with your team and yourself.
It's normal to have this doubt when naming a branch. And in order not to be ashamed of sending a pull request, I always try to follow a certain logic.
There is common a practice of keeping the "master" branch always with the code in production, while using a "dev" branch where we mix all the code from other intermediate branches to test everything before we go into production.
But, besides we can't use spaces and some special characters, there are no definitive conventions for branch naming where we can say "this is wrong" and "this is right", but some good practices are recommended:
- Always use lowercase letters. The default already indicates - master
- Use hyphens to separate words. E.g.: product-landing-page
- Use bars for subdivisions into a larger scope. E.g.: blog/comments, blog/article-list
- Dots to split versions when appropriate - Many open source projects use this convention to keep older versions of code. E.g.: source-v1.2.2