Bird
Raised Fist0
Gitdevops~15 mins

Three-way merge in Git - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Three-way merge
What is it?
A three-way merge is a method used in git to combine changes from two different branches by comparing them with a common base version. It looks at the original file, the changes made in one branch, and the changes made in another branch to create a new merged file. This helps git understand how to integrate changes without losing any work. It is essential when multiple people work on the same code and want to bring their changes together.
Why it matters
Without three-way merge, combining changes from different branches would be error-prone and manual, often leading to lost work or broken code. It solves the problem of safely integrating parallel work by understanding the history and differences between versions. This makes collaboration smoother and reduces conflicts, saving time and frustration for developers.
Where it fits
Before learning three-way merge, you should understand basic git concepts like commits, branches, and diffs. After mastering it, you can explore advanced git topics like conflict resolution, rebasing, and merge strategies to handle complex workflows.
Mental Model
Core Idea
A three-way merge combines two sets of changes by comparing them against their shared original version to create a unified result.
Think of it like...
Imagine two friends editing copies of the same recipe from a cookbook. The original recipe is the base. Each friend changes some ingredients. To make a final recipe, you compare both friends' versions with the original to decide which changes to keep without losing anyone's improvements.
Original (Base)
   │        │
Branch A    Branch B
   │        │
   └───► Three-way Merge ───► Merged Result
Build-Up - 7 Steps
1
FoundationUnderstanding Git Branches and Commits
🤔
Concept: Learn what branches and commits are in git as the foundation for merging.
In git, a commit is a snapshot of your project at a point in time. A branch is a separate line of development that allows you to work on changes without affecting the main code. When you create a branch, you start from a commit and add new commits on top.
Result
You can create and switch between branches, each with its own commit history.
Knowing branches and commits is essential because merges combine these separate lines of work.
2
FoundationWhat Is a Merge in Git?
🤔
Concept: Introduce the idea of combining changes from different branches.
A merge in git takes the changes from one branch and integrates them into another. This can be done automatically if there are no conflicting changes. The merge creates a new commit that has two parents, representing the combined history.
Result
Branches are combined, and the project history reflects both sets of changes.
Understanding merges as combining histories helps grasp why conflicts happen and how git tracks changes.
3
IntermediateHow Two-way Merge Differs from Three-way Merge
🤔Before reading on: do you think merging only compares the two files being merged, or does it also use their common ancestor? Commit to your answer.
Concept: Explain why three-way merge uses a base version instead of just two files.
A two-way merge compares only the two files being merged, which can cause confusion if both changed the same lines differently. A three-way merge uses the common ancestor (base) to understand what changed in each branch, making it smarter at combining changes.
Result
Merges are more accurate and less likely to overwrite changes unintentionally.
Knowing the base version is key to resolving differences correctly and avoiding lost work.
4
IntermediateThe Three Versions in a Three-way Merge
🤔Before reading on: can you name the three versions git compares during a three-way merge? Commit to your answer.
Concept: Identify the base, local, and remote versions used in the merge process.
The three versions are: - Base: the common ancestor commit where branches diverged. - Local: the current branch's version. - Remote: the branch being merged in. Git compares changes from base to local and base to remote to decide how to merge.
Result
You understand the roles of each version in the merge process.
Recognizing these three versions clarifies how git detects conflicts and merges changes.
5
IntermediateHow Git Detects and Handles Conflicts
🤔Before reading on: do you think git can always merge automatically, or are there cases it needs help? Commit to your answer.
Concept: Explain when and why conflicts happen during a three-way merge.
Conflicts occur when both local and remote branches change the same part of the file differently from the base. Git cannot decide which change to keep automatically. It marks the conflict in the file for the user to resolve manually.
Result
You know when merges require manual intervention and how git signals conflicts.
Understanding conflict detection helps you prepare to resolve issues and keep code correct.
6
AdvancedUsing Three-way Merge in Git Commands
🤔Before reading on: do you think git merge uses three-way merge by default or only sometimes? Commit to your answer.
Concept: Show how git commands like 'git merge' and 'git rebase' use three-way merge internally.
When you run 'git merge', git automatically performs a three-way merge if the branches have diverged. It finds the base commit and compares changes to create the merged result. Similarly, 'git rebase' uses three-way merges to apply commits onto a new base. You can see conflicts during these operations if they arise.
Result
You can predict when and how git merges changes and handle conflicts during merges and rebases.
Knowing git's internal use of three-way merge empowers you to troubleshoot merge issues effectively.
7
ExpertAdvanced Merge Strategies and Customization
🤔Before reading on: do you think git always uses the same merge strategy, or can it be customized? Commit to your answer.
Concept: Explore different merge strategies and how experts customize merges for complex workflows.
Git supports multiple merge strategies like 'recursive' (default for three-way merges), 'ours', and 'theirs'. Experts customize merges using options like '--strategy' and '--strategy-option' to control conflict resolution. For example, 'recursive' can do rename detection and handle criss-cross merges. Understanding these helps manage large projects with complex histories.
Result
You can choose and configure merge strategies to fit your project's needs and reduce manual conflict resolution.
Mastering merge strategies prevents common pitfalls in large-scale collaboration and improves merge reliability.
Under the Hood
Git stores commits as snapshots with pointers to parent commits. During a three-way merge, git finds the common ancestor commit (base) of the two branches. It then compares the base to each branch's tip to identify changes. Git applies these changes together, line by line, to create a merged file. If both branches changed the same lines differently, git marks a conflict for manual resolution.
Why designed this way?
Three-way merge was designed to handle parallel development safely by using the common ancestor as a reference point. Earlier methods like two-way merges were error-prone because they lacked context about the original state. Using the base commit allows git to understand what changed in each branch independently, reducing accidental overwrites and lost work.
┌─────────────┐       ┌─────────────┐
│  Base Commit│──────▶│  Local Head │
└─────┬───────┘       └─────┬───────┘
      │                     │
      │                     │
      │                     │
      ▼                     ▼
┌─────────────────────────────────┐
│        Three-way Merge          │
└─────────────┬───────────────────┘
              │
              ▼
       ┌─────────────┐
       │ Merged Head │
       └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does git always merge changes automatically without conflicts? Commit yes or no.
Common Belief:Git merges always happen automatically without any user intervention.
Tap to reveal reality
Reality:Git can automatically merge changes only if they do not conflict. When both branches change the same lines differently, git stops and asks the user to resolve conflicts manually.
Why it matters:Assuming automatic merges always work leads to surprise conflicts and broken code if not handled properly.
Quick: Is the base version in a three-way merge always the latest commit on the main branch? Commit yes or no.
Common Belief:The base version is always the latest commit on the main branch or master.
Tap to reveal reality
Reality:The base is the most recent common ancestor commit of the two branches being merged, which may not be the latest main branch commit.
Why it matters:Misunderstanding the base can cause confusion about why certain changes appear as conflicts or why merges behave unexpectedly.
Quick: Does a three-way merge mean git merges three files into one? Commit yes or no.
Common Belief:Three-way merge means git merges three separate files into one final file.
Tap to reveal reality
Reality:Three-way merge compares three versions of the same file (base, local, remote) but merges them into a single file representing combined changes.
Why it matters:Thinking git merges three separate files can confuse learners about the process and the role of the base version.
Quick: Can you always avoid conflicts by merging more often? Commit yes or no.
Common Belief:Merging frequently always prevents conflicts from happening.
Tap to reveal reality
Reality:While frequent merges reduce conflict size, conflicts can still happen if changes overlap. Some conflicts are unavoidable and require manual resolution.
Why it matters:Believing frequent merges eliminate conflicts can lead to frustration when conflicts still occur.
Expert Zone
1
Git's recursive merge strategy can detect file renames and handle complex histories like criss-cross merges, which simpler merges cannot.
2
Three-way merges rely on the commit graph structure; shallow clones or rebases can affect the base commit detection and cause unexpected conflicts.
3
Merge conflicts are not just about lines changed but also about context; git uses heuristics to decide when to flag conflicts, which can be tuned with merge options.
When NOT to use
Three-way merge is not suitable when you want to rewrite history cleanly; in such cases, rebasing or cherry-picking is preferred. Also, for trivial fast-forward merges where no divergence exists, a simple pointer move is better. For binary files or large files, specialized merge tools or manual merges may be necessary.
Production Patterns
In professional workflows, three-way merges are used daily during feature integration. Teams often combine it with pull requests and continuous integration to catch conflicts early. Advanced users customize merge strategies and use merge drivers for special file types. Automated conflict resolution scripts are sometimes employed for repetitive patterns.
Connections
Version Control Systems
Three-way merge is a core technique used in many version control systems to integrate parallel changes.
Understanding three-way merge helps grasp how tools like Mercurial or SVN handle merging, revealing common principles across systems.
Conflict Resolution in Negotiations
Both involve finding a common ground between differing positions by referencing a shared starting point.
Knowing how three-way merge uses a base to reconcile differences can illuminate strategies for resolving human conflicts by focusing on original agreements.
Data Synchronization in Distributed Systems
Three-way merge parallels how distributed systems reconcile divergent data copies by comparing with a known common state.
Recognizing this connection helps understand eventual consistency and conflict resolution in databases and cloud storage.
Common Pitfalls
#1Ignoring conflicts and forcing merge without resolution
Wrong approach:git merge feature-branch --no-edit --strategy=recursive -X theirs
Correct approach:git merge feature-branch # Resolve conflicts manually in files # Then git add resolved files # Finally git commit
Root cause:Misunderstanding that automatic options override conflicts safely, leading to lost changes.
#2Assuming the base commit is always the main branch tip
Wrong approach:Manually choosing the main branch tip as base for a three-way merge
Correct approach:Let git find the common ancestor automatically during merge
Root cause:Lack of understanding of git's commit graph and base commit selection.
#3Using two-way merge tools for git merges
Wrong approach:Using simple diff tools that compare only two files to resolve git merges
Correct approach:Use git's built-in three-way merge tools or specialized merge tools that support three-way merging
Root cause:Not realizing that two-way comparisons miss context from the base version, causing incorrect merges.
Key Takeaways
Three-way merge uses a common ancestor to combine changes from two branches safely and accurately.
It is essential for collaboration in git, preventing lost work and reducing manual errors during merges.
Conflicts happen when both branches change the same lines differently, requiring manual resolution.
Git's merge commands use three-way merge by default, but advanced strategies and options exist for complex cases.
Understanding three-way merge deeply helps troubleshoot merge issues and manage large projects effectively.

Practice

(1/5)
1. What is the main purpose of a three-way merge in Git?
easy
A. To combine changes from two branches using a common base
B. To delete a branch after merging
C. To create a new branch from the current branch
D. To reset the current branch to a previous commit

Solution

  1. Step 1: Understand the concept of three-way merge

    A three-way merge uses the common ancestor of two branches to combine their changes safely.
  2. Step 2: Identify the purpose in Git workflow

    This process helps merge changes from two branches without losing work, especially when both branches have edits.
  3. Final Answer:

    To combine changes from two branches using a common base -> Option A
  4. Quick Check:

    Three-way merge = combine changes safely [OK]
Hint: Three-way merge combines two branches with a common ancestor [OK]
Common Mistakes:
  • Confusing merge with branch deletion
  • Thinking merge creates new branches
  • Mixing merge with reset commands
2. Which Git command automatically performs a three-way merge when integrating changes from a remote branch?
easy
A. git pull
B. git merge
C. git commit
D. git branch

Solution

  1. Step 1: Recall commands that fetch and merge

    git pull fetches changes from a remote branch and merges them locally, often using a three-way merge.
  2. Step 2: Differentiate from other commands

    git merge merges branches locally but does not fetch remote changes; git branch manages branches; git commit records changes.
  3. Final Answer:

    git pull -> Option A
  4. Quick Check:

    git pull = fetch + merge (three-way) [OK]
Hint: git pull fetches and merges remotely with three-way merge [OK]
Common Mistakes:
  • Choosing git merge without fetching first
  • Confusing git commit with merge
  • Using git branch for merging
3. Given the following scenario:
Branch A has file.txt with content: "Hello World"
Branch B modifies file.txt to: "Hello Git"
Common base has file.txt: "Hi World"
What will be the content of file.txt after a successful three-way merge of Branch B into Branch A?
medium
A. "Hello"
B. "Hello Git"
C. "Hello World Git"
D. "Hello World"

Solution

  1. Step 1: Identify changes from base to each branch

    Base has "Hi World". Branch A changed "Hi" to "Hello". Branch B changed "Hi" to "Hello" and "World" to "Git".
  2. Step 2: Understand three-way merge result

    Since the change "Hi" -> "Hello" is common to both branches, and Branch B has an additional change "World" -> "Git", Git's three-way merge automatically combines them, resulting in "Hello Git".
  3. Final Answer:

    "Hello Git" -> Option B
  4. Quick Check:

    Three-way merge picks combined changes, here "Hello Git" [OK]
Hint: Merged content reflects changes from both branches via base [OK]
Common Mistakes:
  • Assuming content concatenates both changes
  • Ignoring base version in merge
  • Confusing which branch's changes apply
4. You ran git merge feature but got a conflict in app.js. What should you do to resolve this three-way merge conflict?
medium
A. Run git reset --hard immediately to discard all changes
B. Delete app.js and run git merge --abort
C. Edit app.js to fix conflicts, then run git add app.js and git commit
D. Run git branch -d feature to delete the feature branch

Solution

  1. Step 1: Understand merge conflict resolution

    When a conflict occurs, you must manually edit the conflicting file to resolve differences.
  2. Step 2: Stage and commit resolved file

    After fixing conflicts in app.js, use git add to stage and then git commit to complete the merge.
  3. Final Answer:

    Edit app.js, then git add and git commit -> Option C
  4. Quick Check:

    Fix conflicts, stage, commit to resolve merge [OK]
Hint: Fix conflicts manually, then add and commit [OK]
Common Mistakes:
  • Deleting files instead of resolving conflicts
  • Aborting merge without fixing conflicts
  • Deleting branches to fix conflicts
5. You have two branches, main and feature. Both modified the same function in utils.py differently. After running git merge feature into main, a three-way merge conflict occurs. Which approach best resolves this conflict while preserving both changes?
hard
A. Delete feature branch and continue with main unchanged
B. Force merge with git merge --strategy=ours to keep main version only
C. Reset main to the common ancestor commit and retry merge
D. Manually edit utils.py to combine both changes logically, then stage and commit

Solution

  1. Step 1: Recognize conflict in same function

    Both branches changed the same function differently, causing a conflict during merge.
  2. Step 2: Choose best resolution method

    Manually editing the file to combine both changes logically preserves work from both branches, which is the best practice.
  3. Step 3: Stage and commit after resolving

    After editing, stage the file with git add and commit to complete the merge.
  4. Final Answer:

    Manually edit utils.py to combine changes, then stage and commit -> Option D
  5. Quick Check:

    Manual merge preserves both changes best [OK]
Hint: Edit conflicts to combine changes, then add and commit [OK]
Common Mistakes:
  • Using --strategy=ours loses feature changes
  • Deleting branches to avoid conflicts
  • Resetting loses recent work