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.
Before we dive into using git mergetool, let's set it up.
git config --global merge.tool mergetoolBy setting the merge.tool configuration, we've told Git to use the mergetool for all future merge conflicts.
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:
git config merge.tool.vimdiff.cmd "vimdiff $BASE $LOCAL $REMOTE -- $MERGED"
git config merge.tool vimdiffNow, let's explore some basic git mergetool commands.
To invoke git mergetool during a merge, run:
git mergetoolGit will then open the conflicted files in your chosen mergetool, allowing you to resolve the conflicts manually.
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.
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.
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.
git checkout master
git merge branch1This will create a merge conflict because both file1.txt and file2.txt have been modified in both branches.
git mergetoolNow, 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.
We've learned about git mergetool and how it helps resolve merge conflicts. We've set up a mergetool and seen it in action.
What command is used to invoke git mergetool during a merge?
Now that you understand git mergetool, you'll be better equipped to handle merge conflicts in your projects. Happy coding! ✅