Three-Way Merges
What you'll learn: How Git creates a merge commit when both branches have independently evolved with new work.
When Branches Diverge
In the previous lesson, you learned about fast-forward merges—the simple case where one branch is directly ahead of another. But what happens when both branches have moved forward independently? This is where three-way merges come into play.
Imagine two developers both branching from the same point, then each making different commits. The branch history has "diverged"—there's no straight line from one branch tip to the other. Git can't simply move the pointer forward; it must reconcile two different lines of development.
The Three-Way Merge Process
Git uses three commits to perform this merge:
- The common ancestor: The point where the branches originally diverged
- Your branch's latest commit: The tip of your current branch
- Their branch's latest commit: The tip of the branch you're merging in
Git compares all three, intelligently combining changes from both branches. If both branches modified different files (or different parts of the same file), Git automatically merges them. The result is a special merge commit with two parents—one from each branch.
Visual Example
A---B---C (feature)
/ \
D---E-----------M (main)
Here, E is the common ancestor. Git looks at changes from E→C and E→M, combines them, and creates merge commit M that represents the unified state.
Automatic vs Manual
When changes don't overlap, Git completes the three-way merge automatically. When both branches modify the same lines, you'll encounter a merge conflict (covered in upcoming lessons).
Key Takeaway: Three-way merges happen when both branches have new commits since diverging; Git uses the common ancestor plus both branch tips to create a merge commit that unifies the work.