Merging and resolving conflicts with git

I frequently get asked git questions. One of the more common questions is “How do I resolve conflicts?” It is surprisingly easy to do in git, but it isn’t very obvious HOW to do it. So, here we go…

$ git checkout mybranch
Switched to branch 'mybranch'
$ git merge master
Auto-merging somedir/somefile.txt
CONFLICT (content): Merge conflict in somedir/somefile.txt
Automatic merge failed; fix conflicts and then commit the result.

So far most users of git are able to get this far. In fact it’s right about here that the questions begin.

At this point if you open the somedir/somefile.txt in your favorite text editor you will see the conflicts embedded in the contents, something like:

Animals I like:
<<<<<<< HEAD
>>>>>>> master

From this you can see that the current branch contains cats while the master branch contains dogs – this is the conflict that must be resolved. Both copies contain birds, so there is no conflict to resolve there.First we resolve the conflicts and then we commit the results.

Resolve the conflicts

There are three options to resolve the conflicts.

1. Keep changes in current branch

If you want to keep the file as it exists on the current branch (i.e. you want the list to contain cats and birds) you can type the following command:

$ git checkout --ours somedir/somefile.txt

2. Keep changes from merged branch

Alternatively if you want to keep the file as it exists on the master branch (i.e. you want the list to contain dogs and birds) you can type the following command:

$ git checkout --theirs /path/to/file

3. Keep a mix of changes, or neither

More often then not, however, you don’t want one OR the other, you want a mix of the two. Say in this example we want the list to contain cats, dogs, and birds. To accomplish this instead of using either of the checkout commands above you simply edit the file in your favorite file editor and remove the extra conflict information that git has added and make it look exactly as you want it to look. In our case we would edit the file to look like this:

Animals I like:

Once the file looks right we save the changes.

Commit the changes

Once we have resolved the conflicts for a file, we add the file to the index to be commited after all files are resolved. This should feel like comfortable territory again.

$ git add somedir/somefile.txt

After all conflicts have been resolved and all files have been added we can commit the changes.

$ git commit -m "Manual conflict resolution."
Recorded resolution for 'somedir/somefile.txt'.
[mybranch 1234abc] Manual conflict resolution.

And you’re done!


For more info you can look here or here.

You can leave a response, or trackback from your own site.

Leave a Reply