What is Git Merge?
What is Git Merge? κ΄λ ¨
Under the hood, git rebase
and git merge
are very, very different things. Then why do people compare them all the time?
The reason is their usage. When working with Git, we usually work in different branches and introduce changes to those branches.
In a previous tutorial, I gave an example where John and Paul (of the Beatles) were co-authoring a new song. They started from the main
branch, and then each diverged, modified the lyrics and committed their changes.
Then, the two wanted to integrate their changes, which is something that happens very frequently when working with Git.
There are two main ways to integrate changes introduced in different branches in Git, or in other words, different commits and commit histories. These are merge and rebase.
In a previous tutorial, we got to know git merge
pretty well. We saw that when performing a merge, we create a merge commit β where the contents of this commit are a combination of the two branches, and it also has two parents, one in each branch.
So, say you are on the branch john_branch
(assuming the history depicted in the drawing above), and you run git merge paul_branch
. You will get to this state β where on john_branch
, there is a new commit with two parents. The first one will be the commit on john_branch
branch where HEAD
was pointing to before performing the merge, in this case - "Commit 6". The second will be the commit pointed to by paul_branch
, "Commit 9".
Look again at the history graph: you created a diverged history. You can actually see where it branched and where it merged again.
So when using git merge
, you do not rewrite history β but rather, you add a commit to the existing history. And specifically, a commit that creates a diverged history.
How is git rebase
Different from git merge
?
When using git rebase
, something different happens. π₯
Let's start with the big picture: if you are on paul_branch
, and use git rebase john_branch
, Git goes to the common ancestor of John's branch and Paul's branch. Then it takes the patches introduced in the commits on Paul's branch, and applies those changes to John's branch.
So here, you use rebase
to take the changes that were committed on one branch β Paul's branch β and replay them on a different branch, john_branch
.
Wait, what does that mean? π€
We will now take this bit by bit to make sure you fully understand what's happening under the hood π