Resolving Git Merge Conflicts

When multiple developers are working on a project version controlled using Git, there may be occasions where conflicts between modifications to the same file occur. Resolving Git merge conflicts requires human activity to choose which of the changes to keep or discard.

To demonstrate this in action, let’s assume that two developers, Developer A and Developer B are making modifications to the same styles.css file.

Developer A is working on a hotfix/css_improvements branch that has been created off of the master branch. Developer B has a hotfix/css_improvements_2 branch also created from master.

The original contents of the file contain the following:

.container {
    width: 900px;
}

.container .content {
    padding: 5px 10px;
}

Developer A add and commits some changes to the hotfix branch. Their version of styles.css now looks like the below.

.container {
    margin: 0 auto;
    width: 900px;
}

.container .content {
    padding: 5px 10px;
}

a:hover {
    text-decoration: none;
}

These changes have been tested, and merged into the master branch.

On Developer B’s branch, hotfix/css_improvements_2, the styles.css file looks a little different.

.container {
    margin: 0 auto;
    width: 850px;
}

.container .content {
    padding: 5px 10px;
}

h1, h2, h3 {
    font-weight: bold;
}

As Developer B attempts to merge their changes into the master branch, they are presented with the following message.

git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

git merge hotfix/css_improvements_2
Auto-merging styles.css
CONFLICT (content): Merge conflict in styles.css
Automatic merge failed; fix conflicts and then commit the result.

As Developer B’s version of styles.css is different from the version on the master branch (Developer A’s changes), Git does not know whether to keep/discard some of the alterations made to the file.

Open up styles.css and you’ll see that styles.css has now been populated with conflict markers created by Git.

.container {
    margin: 0 auto;
<<<<<<< HEAD
    width: 900px;
=======
    width: 850px;
>>>>>>> hotfix/css_improvements_2
}

.container .content {
    padding: 5px 10px;
}

<<<<<<< HEAD
a:hover {
    text-decoration: none;
=======
h1, h2, h3 {
    font-weight: bold;
>>>>>>> hotfix/css_improvements_2
}

Git now requires you to edit these conflicts choosing what changes to keep or discard.

The lines between the beginning <<<<<<< and ====== lines are the changes what you already had locally.

The lines between the ======= and >>>>>>> are the changes introduces by the latest commit (Developer B's changes).

To resolve the conflicts, you can edit the file manually choosing what changes to keep or discard and removing the conflict markers. The other method is to use git mergetool which is a tool that opens up a GUI allowing to manage conflicts within the file.