Rebasing & Merging
Two ways of solving the same problem
3 min read
Suppose you started working on a new feature in a dedicated branch meanwhile another team member updates the
main branch with new commits. This results in a
forked history, which should be familiar to anyone who has used Git as a collaboration tool.
You may want to integrate them into your feature branch. You can either
The easiest option is to merge the
main branch into the
feature branch using the commands:
git checkout feature git merge main
The above merge process will create a new
merge commit in the
feature branch which will have a history of both branches.
- It’s a very simple Git methodology to use and understand.
- The existing commits on both branches remain untouched. It preserves the commit history.
git mergeis run, an extra
merge commitis created. And if the
mainbranch is very active, this can pollute your
featurebranch’s history quite a bit. While it’s possible to mitigate this issue with advanced git log options, it can make it hard for other developers to understand the history of the project. One way to avoid the merge commit is to use
You can instead rebase the
feature branch onto the
main branch using the commands:
git checkout feature git rebase main
This moves the entire feature branch so that it begins at the tip of the main branch. All of the work is still there, but you have re-written history.
Instead of creating a
merge commit in the
feature branch, rebasing re-writes the commit history by creating brand new commits for each commit in the feature branch.
Rebasing eliminates the unnecessary
merge commitsrequired by
git mergeresulting in cleaner project history.
It also results in a perfectly
linearproject history—you can follow the tip of the feature all the way to the beginning of the project without any forks.
- Rebasing is a very powerful feature. That being said, it is
riskyas well if it is not used in the right way. Never use it on
publicbranches. For example, think about what would happen if you rebased
Now, you are referring to a new
main branch and everybody else’s referring to the old
main branch. The only way to synchronize the two
main branches is to
merge them back together, resulting in an extra merge commit and two sets of commits that contain the same changes (the original ones, and the ones from your rebased branch). Needless to say, this is a very confusing situation.
If you would prefer a clean, linear project history free of unnecessary merge commits, you should go for
If you want to preserve the complete history of your project and avoid the risk of re-writing public commits, you can stick with
That’s all for this article. Thank you for reading it.
Did you find this article valuable?
Support Piyush Sinha by becoming a sponsor. Any amount is appreciated!