DevOpsGitHub

Resolving Git Merge Conflicts: A Step-by-Step Guide

TT
TopicTrick Team
Resolving Git Merge Conflicts: A Step-by-Step Guide

Resolving Git Merge Conflicts: A Step-by-Step Guide


1. Anatomy of a Conflict (The Markers)

When a conflict happens, Git pauses the merge and writes specific "Markers" directly into your code:

text
  • HEAD (Top): The code currently in your local branch.
  • ======= (Center): The "Fence."
  • Branch (Bottom): The code coming from the branch you are trying to merge.

2. The 3-Step Resolution Workflow

  1. Identify: Run git status to see which files are "Unmerged."
  2. Decide: Open the file. Delete the markers and choose which code to keep (or combine both!).
  3. Finish: Once the file is fixed, run git add [file] and then git commit. The conflict is resolved.

3. Visual Tools: Using VS Code

Don't resolve conflicts in a raw text editor. Professional developers use a Visual Merge Editor (like the one built into VS Code).

  • It provides buttons: "Accept Current Change," "Accept Incoming Change," or "Accept Both."
  • It highlights the specific lines, making it impossible to accidentally delete a bracket or a semicolon.

4. Proactive Prevention: The "Pull Early" Strategy

The best way to resolve a conflict is to never have it.

  • Pull Often: Every morning, run git pull origin main. This brings your teammates' changes into your code in small, easy-to-manage pieces.
  • Small Commits: If you change 1,000 lines, you will HAVE a conflict. If you change 10 lines, it's very unlikely.
  • Communication: If two people are editing the same function, talk to each other!

Frequently Asked Questions

What is 'ours' vs 'theirs'?

  • Ours: The branch you are currently on.
  • Theirs: The branch you are merging in. If you are 100% sure the other person's code is better, you can skip the manual edit and run: git checkout --theirs filename.java.

Can I undo a merge if it becomes too messy? YES. If you are halfway through a conflict and you realize you've made a mistake, run: git merge --abort. This instantly resets everything to the way it was before you started the merge.


Key Takeaway

A merge conflict is a Communication Opportunity. By staying calm, reading the markers carefully, and using visual editors, you turn a scary error into a simple decision. By pulling early and often, you build a workflow where conflicts are rare, minor, and easily handled in seconds.

Read next: Mastering the Pull Request: Professional Code Review →


Part of the GitHub Mastery Course — engineering the peace.