What is Three Way Merge in Git: Simple Explanation and Example
three way merge in Git is a method to combine changes from two branches by comparing their latest commits with their common ancestor. It uses three points: the base (common ancestor), and the two branch tips, to automatically merge changes and resolve conflicts if any.How It Works
Imagine you and a friend start writing a story from the same original draft. Later, you both make changes separately. To combine your edits, you look at the original draft and both your versions. This is what a three way merge does in Git.
Git finds the common starting point (called the base), then compares it with the two versions you want to merge. It looks for changes made in each branch since that base. If the changes don't overlap, Git merges them automatically. If there are conflicts, Git asks you to decide which changes to keep.
Example
This example shows a simple three way merge between two branches named feature and main.
git checkout main # Make some changes and commit git checkout -b feature # Make different changes and commit git checkout main # Merge feature branch into main using three way merge git merge feature
When to Use
Use a three way merge when you want to combine changes from two branches that have diverged from a common point. This happens often when multiple people work on the same project in parallel.
It helps keep work organized and integrated without losing anyone's changes. For example, merging a feature branch back into the main branch after development is done uses a three way merge.
Key Points
- Three way merge uses the common ancestor and two branch tips to merge changes.
- It can automatically merge non-conflicting changes.
- Conflicts require manual resolution.
- It is the default merge method in Git.