git mergetool: A Comprehensive Guide for Beginners and Intermediates 🎯

beginner
11 min

git mergetool: A Comprehensive Guide for Beginners and Intermediates 🎯

Understanding git mergetool

git mergetool is a powerful command-line tool that helps you resolve merge conflicts in your Git repository. When you're working on multiple branches, Git can sometimes get confused about what changes to make. In such situations, mergetool can save the day by providing a friendly and intuitive interface to help you merge files manually. 💡 Pro Tip: Use mergetool when you encounter a conflict during a merge operation.

Setting up git mergetool

Before we dive into using git mergetool, let's set it up.

bash
git config --global merge.tool mergetool

By setting the merge.tool configuration, we've told Git to use the mergetool for all future merge conflicts.

Choosing a mergetool

Git comes with several built-in mergetools, but a popular choice is vimdiff. You can set it as the default mergetool for a specific repository like this:

bash
git config merge.tool.vimdiff.cmd "vimdiff $BASE $LOCAL $REMOTE -- $MERGED" git config merge.tool vimdiff

Now, let's explore some basic git mergetool commands.

Invoking git mergetool

To invoke git mergetool during a merge, run:

bash
git mergetool

Git will then open the conflicted files in your chosen mergetool, allowing you to resolve the conflicts manually.

Mergetool in action

Let's walk through a simple example using the vimdiff mergetool.

First, we'll create a new repository and add two files: file1.txt and file2.txt.

bash
mkdir my_repo cd my_repo echo "Content for file1" > file1.txt echo "Content for file2" > file2.txt git init git add . git commit -m "Initial commit"

Now, let's create a new branch and modify the files.

bash
git checkout -b branch1 echo "New content for file1" > file1.txt git add . git commit -m "Update file1 in branch1" git checkout master echo "New content for file2" > file2.txt git add . git commit -m "Update file2 in master"

Now, let's merge branch1 into master.

bash
git checkout master git merge branch1

This will create a merge conflict because both file1.txt and file2.txt have been modified in both branches.

bash
git mergetool

Now, Git will open the conflicted files in the vimdiff mergetool. You can navigate between the local, remote, and merged versions of the files using the keys l, r, and m.

Once you've resolved the conflicts, save the changes and exit the mergetool. Git will then automatically complete the merge.

Recap and quiz 📝

We've learned about git mergetool and how it helps resolve merge conflicts. We've set up a mergetool and seen it in action.

Quick Quiz
Question 1 of 1

What command is used to invoke git mergetool during a merge?

Wrapping up

Now that you understand git mergetool, you'll be better equipped to handle merge conflicts in your projects. Happy coding! ✅