In this article, we will have a look at what rebasing a branch in Git means or what git rebase is, how it compares with merging a branch, and what are the tradeoffs of rebasing and merging.
Table of Contents
Our Starting Point
Our project has a master branch that started out with two commits, m1 and m2. Then a feature branch was made from the m2 commit and some work on it was done in the f1 commit.
Then, work was done in both branches independently of each other in m3 and f2 commits such that they are divergent now.
We want to combine the work done in the feature branch into the master branch, namely, we want to combine m3 commit and f2 commit into a single thing:
How can we do Git rebase?
We have two options for achieving our goal: git merge and git rebase.
In the case of merging the feature branch into the master branch, the git merge feature will replay the changes made on the feature branch since it diverged from master (i.e., from m2) until its current commit (f2) on top of master, and record the result in a new merge commit.
While in the case of rebasing, the base (m2) of the feature branch will be changed to the latest commit of the master branch (m3) so that the feature branch is on par with the master branch after rebasing. After this is done, the feature branch will contain all onward work from its previous base (m2) up till the tip of the master branch (m3).
Git does this all by temporarily saving the f1 and f2 commits internally, resetting the feature branch to the master branch, and then applying f1’ and f2’ commits on top of the feature branch one by one and in order.
The entire history of the feature branch is rewritten.
Looking for a Development Team?
Share the details of your request and we will provide you with a full-cycle team under one roof.
What’s the difference between Merging and Rebasing?
They are both pretty similar in effect so it is a bit tricky to understand them both. The big difference is that merging creates a brand new merge commit while rebasing does not.
Pros/Cons of Merging
The logs and history are very exhaustive. This is an advantage because it can help understand how and when each merge happened and it can be easy to find and fix issues. This is also a disadvantage because history can become too unwieldy, complex, and user-unfriendly.
Pros/Cons of Rebasing
Rebasing was introduced to make the repository history look linear and avoid the jumbled mess merging can potentially make. This makes it easier to browse through the commits as they are linear. But the disadvantage is that we can’t track how and when the merging happened.
When to use Rebasing
Because the entire history of the rebased branch is rewritten and it is difficult to understand where the rebased commits come from, it’s best to only rebase branches that are being worked on only by you. The golden rule of rebasing thus reads:
Never rebase while you’re on a public branch
Resource Video: Git REBASE vs MERGE