Merge#
“What’s the point of having multiple branches?” you might ask. They’re most often used to safely make changes without affecting your (or your team’s) primary branch. However, once you’re happy with your changes, you’ll want to merge them back into the main branch so that they make their way into the final product.
Visual#
Let’s say you’re in a state where you have two branches, each with their own unique commits:
A - B - C main
\
D - E other_branchIf you merge other_branch into main, Git combines both branches by creating a new commit that has both histories as parents. In the diagram below, F is a merge commit that has C and E as parents. F brings all the changes from D and E back into the main branch.
A - B - C - F main
\ /
D - E other_branchMerge Commits#
A merge commit is the result of merging two branches together.
Let’s say we start with this:
A - B - C main
\
D - E vimchadsonlyAnd we merge vimchadsonly into main by running this while on main:
git merge vimchadsonlyThe merge will:
- Find the “merge base” commit, or “best common ancestor” of the two branches. In this case,
A. - Replays the changes from
main, starting from the best common ancestor, into a new commit. - Replays the changes from
vimchadsonlyontomain, starting from the best common ancestor. - Records the result as a new commit, in our case,
F. Fis special because it has two parents,CandE.
After:
A - B - C - F main
\ /
D - E vimchadsonlyFast Forward Merge#
The simplest type of merge is a fast-forward merge. Let’s say we start with this:
C delete_vscode
/
A - B mainAnd we run this while on main:
git merge delete_vscodeBecause delete_vscode has all the commits that main has, Git automatically does a fast-forward merge. It just moves the pointer of the “base” branch to the tip of the “feature” branch:
delete_vscode
A - B - C mainNotice that with a fast-forward merge, no merge commit is created.
This is a common workflow when working with Git on a team of developers:
- Create a branch for a new change
- Make the change
- Merge the branch back into
main(or whatever branch your team dubs the “default” branch) - Remove the branch
- Repeat
Merge#
Just as we merged branches within a single local repo, we can also merge branches between local and remote repos.
Syntax#
git merge remote/branchFor example, if you wanted to merge the primeagen branch of the remote origin into your local main branch, you would run this inside the local repo while on the main branch:
git merge origin/primeagen