Merge Conflicts: From Nightmare to No Big Deal

Muhammad Abdullah
Software Engineer & Tech Enthusiast

The Moment of Panic

You did everything right. You created a branch, wrote perfect code, and opened a pull request. But when you try to merge, Git hits you with the message: "Automatic merge failed; fix conflicts and then commit the result." Your heart sinks. It feels like you’ve failed. But here’s the secret: merge conflicts aren’t your fault, and they aren’t errors. They are Git’s way of saying, "I see two different instructions for the same line of code, and I need a human to make the final decision."

Why Conflicts Happen

A merge conflict occurs when two branches have changed the same part of the same file. For example, you changed a line of text in your feature branch, but in the meantime, a teammate changed that exact same line in the `main` branch. When you try to merge, Git doesn’t know which version to keep. It’s asking you for help.

Anatomy of a Conflict

When a conflict occurs, Git will edit the problematic file and insert markers to show you the conflicting code:

<<<<<<< HEAD (Current Change)
const greeting = "Hello World";
=======
const greeting = "Howdy, World!";
>>>>>>> feat/new-greeting (Incoming Change)

How to Resolve a Conflict: The 3-Step-Rule

Don’t panic. Just follow these steps.

  1. Open the conflicted file(s). Your editor will show the markers.
  2. Edit the file to be correct. Delete the markers and decide which code to keep. You can keep your version, the incoming version, a combination of both, or write something completely new. For the example above, if we want the new greeting, we would edit the file to look like this:
    const greeting = "Howdy, World!";
  3. Save, stage, and commit the fix. This is the crucial final step.
    # Add the file you just fixed
    git add path/to/conflicted/file.js
    # Commit the merge
    git commit -m "Resolve merge conflict in greeting variable"
    # Now you can safely push!
    git push
    

Your code editor (like VS Code) often has buttons to "Accept Current Change," "Accept Incoming Change," or "Accept Both," which makes this process even easier.

How to Avoid Conflicts in the First Place

Once you’ve resolved a few conflicts, you’ll realize they are just a normal part of the development process. They aren't scary, they are a safety feature that ensures code is never merged by accident.