Content
Intro
In a previous article, I explained how to reconcile merge conflicts. I will explain in depth why we see diverging branches and options to resolve them.
Why branches start diverging
Image by Atlassian
As shown above, any dev teams protect the master branch. So you have to branch off the master branch and start making changes. In the meantime, others can update the master branch. If those diverging branches were not overlapping the codebase, that's fine. Yet, we will see the changes in the identical parts. Then Git doesn't know which one takes for consolidation.
So we need to reconcile conflicts before pushing our changes to the prod.
Git merge
Image by Atlassian
Merging is one way to resolve discords. Merging creates a new commit that combines the history of two branches. So, merging doesn't rewrite Git history. Yet, the Git history can become messy when we bring changes from many branches.
How to merge it?
The idea is simple. Go to the target branch and merge the branch you want to bring changes. If there are no conflicts, merging is successful. If not, you have to resolve the conflicts. To do so, refer to the previous article [[Git - Ch3]]
git checkout dev
git merge master
Git rebase
Image by Gitlab
Rebasing is another way to resolve discords. Unlike merging, rebasing doesn't create a new commit. Instead, it brings commits from the branch you want to incorporate and replay all your commits on top of it. Rebasing is nice as it doesn't create a merge commit. It also guarantees the linear Git history, which is cleaner than merging.
How to rebase?
Go to the target branch and rebase the branch. Go to the target branch and rebase the branch you want to bring changes. If there are no conflicts, the rebase is successful.
git checkout dev
git rebase master
When to use merge or rebase
I see the pros and cons of merge/rebase. It has been a debate ever since I started the dev career. The answer is nothing wrong with either approach. It will be beneficial to pick one method and be consistent. So, you can use the following questions to find out which way is better for your team.
Is your team familiar with rebase?
If not, the answer is obvious. As rebasing will rewrite history, this can be a destructive operation.
Is your team big?
If your team size is small, both approaches should work well. If your team size is big, consider rebasing for clean Git history.
Are the branch represents grouped information?
If your team uses a branch-per-feature model, merging will be easier to revert as it contains a set of relative commits.
Conclusion
There is no single answer for all situations. So, check your team's context to find which way will be the best.
Next time, I will cover rebase, which can use for other tasks like squeezing commits.
For more useful content, follow me @bitethecode or on Github!
Top comments (0)