Merge Files with Git Merge Tool
Last time I wrote about git diff and difftool and showed you how to use them to compare different files and versions. Today I am going to focus on the merging and conflict resolution with git merge and mergetool. Merging is an important part of the development process. If you use git you probably work with multiple branches. But even if you develop in trunk with more people, merging and the conflict resolution comes in place when two are working on the same file.
Merge Tool
Mergetool is a command in git that lets you run your custom tool for resolving conflicts in your merged files. Let’s setup the tool and take a closer look at the basic usage.
Setup
We will use p4merge as we already use it for a difftool. It is a great tool with a lot of extra features and very good performance.
For setting up p4merge as your mergetool you have to run these commands.
git config --global merge.tool p4merge
git config --global mergetool.prompt false
git config --global mergetool.p4merge.cmd '\"C:/Program Files/Perforce/p4merge.exe\" $BASE $LOCAL $REMOTE $MERGED'
git config --global mergetool.p4merge.keepTemporaries false
git config --global mergetool.p4merge.trustExitCode false
Usage
So you’ve set up your tool. Let’s resolve our first conflict that I created. I have two branches. Master and iss1. I created file called test.txt in both of them. The content of the file in master branch is master and the content in the iss1 branch is iss1. I committed those changes and now I am trying to merge iss1 into master branch. I ran git merge iss1
command. Take a look at the output.
C:\Users\Jakub\Desktop\ruby-sample [master]> git merge iss1
Auto-merging test.txt
CONFLICT (add/add): Merge conflict in test.txt
Automatic merge failed; fix conflicts and then commit the result.
Merge couldn’t be performed automatically and manual resolution comes into place. Now we run the mergetool command.
git mergetool
P4merge tool starts right away.
You can see that p4merge supports three-way merge. Resolve the conflict and save the file.
Branches were successfully saved. You can notice git created *.orig file with the content from both branches - test.txt.orig. If you’d like to remove this file after merge automatically you have to disable mergetool backups.
git config --global mergetool.keepBackup false
Conclusion
This article gave you a quick introduction to merging with git. You set up p4merge as your primary mergetool and you are able to use it for any conflict resolution.