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)
<<<<<<< HEAD: This is the version in your current branch (e.g., `main`).=======: This divides the two conflicting versions.>>>>>>> branch-name: This is the version from the branch you are trying to merge.
How to Resolve a Conflict: The 3-Step-Rule
Don’t panic. Just follow these steps.
- Open the conflicted file(s). Your editor will show the markers.
- 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!"; - 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
- Communicate with your team. Know who is working on what part of the codebase.
- Pull `main` frequently. Before you start work, and often while you work, update your branch with the latest changes from `main`. The command
git pull origin main --rebaseis fantastic for this. - Keep branches small and short-lived. The longer a branch exists, the more it diverges from `main`, and the higher the chance of conflicts.
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.