Sub topic 7
Merging diverged branches
This chapter assumes you can commit, create and switch branches, and know what a fast-forward merge is. You need Git 2.28 or later for git init -b.
When a fast-forward is not possible
A fast-forward works only when the target branch has not moved since you branched. Once both branches have new commits, they have diverged. Git cannot slide a pointer forward, because that would drop the commits on one side.
Git performs a three-way merge instead. It uses three commits:
- The tip of the current branch.
- The tip of the branch being merged.
- Their merge base, the most recent commit both branches share.
Git compares each tip to the merge base, combines the two sets of changes, and records the result as a merge commit. A merge commit is a commit with two parents. That is why the history afterwards is a graph, not a line.
Try it
This script builds a diverged history from scratch and merges it.
git init -b main demo
cd demo
echo "base" > app.txt
git add app.txt
git commit -m "Add app.txt"
git switch -c feature/login
echo "login" > login.txt
git add login.txt
git commit -m "Add login page"
git switch main
echo "docs" > README.md
git add README.md
git commit -m "Add README"
git merge feature/login -m "Merge feature/login"
git log --oneline --graph --decorateThe two commits touch different files, so Git merges them without asking you anything. The log shows the merge commit on top, with two lines joining below it. git show --format=%P -s HEAD prints both parent hashes.
Forcing a merge commit
When a fast-forward is possible, git merge takes it by default. Add --no-ff to create a merge commit anyway. Some teams do this so each feature stays visible as a group of commits in the history.
git merge --no-ff feature/loginCommon errors
- Merging in the wrong direction. The branch you have checked out receives the changes. Run
git switch mainfirst to merge a feature intomain. Check withgit branchbefore you merge. - Uncommitted changes. Git refuses to merge if your working tree changes would be overwritten. Commit them, or set them aside with
git stash. - "Already up to date." The branch you named has nothing new for you. Either it is already merged, or you mistyped the name.
- A conflict stops the merge. If both branches changed the same lines, Git pauses and marks the files. The next chapter covers resolving this. To back out, run
git merge --abort.
Exercise
Exercise
You are on main, and feature/login has two commits that main does not have. main has one commit that feature/login does not have. You run git merge feature/login. What kind of merge happens, and how many parents does the new commit have?
Show answer
A three-way merge, because the branches have diverged. Git uses the merge base and both tips to create a merge commit with two parents: the previous tip of main and the tip of feature/login.