Andrew Heins

default-image

Dealing with Conflicts in Git

Less Catastrophic than you Think


Something that I didn’t find immediately obvious was how to deal with conflicts in Git, so here’s a quick tutorial.

Conflicts arise when two different branches are working on the same file and then try to commit changes.

...A--
  /
M-------M-----X - Conflict
            /
     B------

Conflicts don’t have to be catastrophic, it simply depends on what’s happend with the file.

Simple Conflicts

Generally, if the changes that cause the conflict don’t affect the same lines of code, git can auto-merge your changes together without too much trouble.

For example, if Branch A  was fixing a typo in a method getPatientByID and Branch B was working on a method called printReport, when the two branches are merged back into Master, assuming no other changes took place, git is smart enough to merge those changes.

Complex Conflicts

Sometimes, however, conflicts arise because two changes modify the same line of code.

When this happens (here’s the part it took me a while to actually understand) Git changes the source code of the file, and expects you to manually do the changes.

Git’s response to a failed merge

Git finds a conflict

And the updated source file

Source updated with conflict data

Let’s get a closer look:

<<<<<<< HEAD
         alert("I'm... too lazy to act on my muted outrage!");
=======
        var x = escape("I'm mad as hell, and I'm not going to take it anymore!");
>>>>>>> dev

What are we looking at here?

Git has replaced the offending line of code with the code from both files.

From << HEAD to ===== is the branch you’re currently working with, and from ===== to  >> dev is the branch you’re merging in.

So what’s the resolution? You have to edit the file back to what actually is needed.

So dev represents the new format of that line, and HEAD represents the new language the copywriters want you to use, you’d probably replace the whole thing above with:

var x = escape("I'm... too lazy to act on my muted outrage!");

Once this is done, you’ll likely want to rerun any unit tests to ensure you didn’t break the build, then re-stage the file using add, and commit your set changes.

Conflict resolved

Done!


Join the Conversation!