Three-Way Merges
What you'll learn: How Git creates merge commits when combining branches that have diverged with separate histories.
When Fast-Forward Isn't Enough
You already know about fast-forward merges, where Git simply moves the branch pointer forward because one branch is directly ahead of the other. But what happens when two branches have both moved forward independently? This is where three-way merges come in.
How Three-Way Merges Work
Imagine two developers working on different features simultaneously. Branch A adds feature X, while Branch B adds feature Y. Both branches started from the same commit, but now they've diverged—they have different histories.
Git can't simply fast-forward because neither branch is "ahead" of the other. Instead, Git performs a three-way merge using:
- The common ancestor (the commit where the branches originally diverged)
- The tip of the first branch (your current branch)
- The tip of the second branch (the branch you're merging in)
Git compares all three commits—hence "three-way"—to intelligently combine the changes. It looks at what changed in each branch relative to their common ancestor and merges those changes together.
The Merge Commit
The result is a special merge commit that has two parent commits (one from each branch). This preserves the full history of both branches and marks where they came back together.
Think of it like two tributaries joining a river: the merge commit is the confluence point, carrying water (code) from both upstream sources.
Key Takeaway: Three-way merges handle divergent branch histories by comparing the common ancestor with both branch tips, creating a merge commit with two parents to preserve the complete history.