The Problem
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 rebase
or merge
.
The Solution
1. Merging
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.
Pros
- It’s a very simple Git methodology to use and understand.
- The existing commits on both branches remain untouched. It preserves the commit history.
Cons
- Whenever
git merge
is run, an extramerge commit
is created. And if themain
branch is very active, this can pollute yourfeature
branch’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 usegit rebase
instead.
2. Rebasing
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.
Pros
Rebasing eliminates the unnecessary
merge commits
required bygit merge
resulting in cleaner project history.It also results in a perfectly
linear
project history—you can follow the tip of the feature all the way to the beginning of the project without any forks.
Cons
- Rebasing is a very powerful feature. That being said, it is
risky
as well if it is not used in the right way. Never use it onpublic
branches. For example, think about what would happen if you rebasedmain
onto yourfeature
branch:
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.
Summary
If you would prefer a clean, linear project history free of unnecessary merge commits, you should go for
git rebase
.If you want to preserve the complete history of your project and avoid the risk of re-writing public commits, you can stick with
git merge
.
References
That’s all for this article. Thank you for reading it.