Three-Way Merge in Git 🎯

beginner
18 min

Three-Way Merge in Git 🎯

Welcome to our comprehensive guide on Three-Way Merge in Git! This tutorial is designed to help both beginners and intermediates understand this powerful Git feature. Let's dive right in!

Understanding Three-Way Merge 📝

Three-way merge is a process used by Git to resolve merge conflicts when merging two branches with a common ancestor. It compares three revisions of a file:

  1. The version from the branch you're merging (merge-branch).
  2. The version from the branch you're merging into (base-branch).
  3. The common ancestor of the two branches (M).

Why Three-Way Merge? 💡

Three-way merge is necessary because conflicts can occur when both branches have modifications in the same lines. By comparing all three revisions, Git can determine which changes should be kept and how to merge them.

Basic Three-Way Merge Scenario 📝

Let's illustrate a basic three-way merge with a simple example:

diff
M: This is a common ancestor. base-branch: This is the current state of the base branch. This line has been modified. merge-branch: This is the current state of the merge branch. This line has also been modified.

During the merge, Git will create a new file that looks like this:

diff
Merge branch 'merge-branch' conflict: This line has been modified by both branches. This line has been manually resolved. Resolved by: (You, the developer)

You, as the developer, will need to manually resolve the conflict by choosing the appropriate changes from the base-branch and merge-branch.

Performing a Three-Way Merge 💡

To perform a three-way merge in Git, you can use the git merge command followed by the name of the branch you want to merge. If conflicts arise, Git will pause and inform you about them.

bash
$ git checkout base-branch $ git merge merge-branch

Resolving Conflicts 💡

When conflicts occur, Git will pause the merge process and mark conflicting files with the message error: Merge conflict in <file>. You'll need to open the conflicting file, resolve the conflicts manually, and save the file.

Here's how to resolve conflicts:

  1. Identify the conflicting files using the git status command.
  2. Open the conflicting files using a text editor.
  3. Review the marked sections containing the conflicts.
  4. Decide which changes should be kept and remove the conflict markers (<<<<<<<, >>>>>>>, and ======).
  5. Save and close the file.
  6. Stage the resolved file using the git add command.
  7. Continue the merge process using the git merge --continue command.

Quiz 💡

Quick Quiz
Question 1 of 1

What is Three-Way Merge in Git?


We hope this tutorial has helped you understand the Three-Way Merge in Git! As you continue to work with Git, you'll find this feature invaluable for managing complex merge scenarios. Happy coding! 🚀