Portal: Master Git branch management
In Git, Git merge and Git rebase are both used to merge changes from one branch into another, but in different ways.
In daily work, there is basically a main branch of work. Generally, we will create a new branch to start our work, so as not to affect the main branch. Let’s assume the following scenario to illustrate code merging.
Xiao Li needed to develop FeatureA, so he created a new branch of FeatureA based on the main branch of the project and started his work. While he was working, his colleague fixed two bugs and merged them into the main branch, so the code branch became the following situation:
git merge
git rebase
git merge
In general, the simplest operation is to perform the following steps:
git checkout featureA
git merge master
Copy the code
Or directly:
git merge master featureA
Copy the code
This results in a three-way merge:
git merge
git rebase
For a more detailed description of Git merge, see my previous article git Branch Management
git rebase
As an alternative to merge, we can do rebase like this:
git checkout featureA
git rebase master
Copy the code
It would move the entire Branch of featureA directly behind the current master branch:
git rebase
git log
git bisect
gitk
If you don’t follow the golden rule of git rebase, it can have a disastrous effect on your project history. Rebase causes your feature branch to have no merge commit history, so you won’t be able to see which changes have been merged upstream.
Interactive Rebase
Suppose that Little A already had three submissions on his featureA branch, and rebase would route all three submissions to the master branch.
rebase
featureA
-i
rebase
git checkout featureA
git rebase -i master
Copy the code
It opens your Git text editor:
pick 33d5b7a Message for commit # 1
pick 9480b3d Message for commit # 2
pick 5c67e61 Message for commit # 3
Copy the code
This list shows your fetureA history and you can merge your history by changing the order, changing pick, or using FixUp. For example, if #2 and #3 contain fixes and you want to merge them, you can add a fixup:
pick 33d5b7a Message for commit # 1
pick 9480b3d Message for commit # 2
fixup 5c67e61 Message for commit # 3
Copy the code
# 2
# 3
git merge
Rebase’s Golden Rule
As you use Rebase to make it easier to handle your branches, you must also understand the potential risks. The golden rule of using Rebase is never to use it on public branches. Assuming you do, the following happens:
git rebase
master
featureA
master
master
git merge
master
master
So, when you do Git rebase, make sure that there is no one else working on the branch, and if so, consider a harmless way to do your commit, such as git Revert.