EMZETT.
Login

Git: Resolving a merge conflict

In short: A merge conflict arises when two changes affect the same spot; Git marks the spot and you decide which version applies.

In more detail: Message: CONFLICT (content): Merge conflict in file.txt and Automatic merge failed; fix conflicts and then commit the result. Git can merge two changes automatically as long as they affect different spots. If both touch the same lines, a human must decide.

In Depth

What a conflict looks like

<<<<<<< HEAD
Display in blue
=======
Display in green
>>>>>>> feature/colour

Between <<<<<<< and ======= is your version (HEAD), between ======= and >>>>>>> the other one. To resolve: choose one variant, mix both or rewrite, then delete all markers.

Solutions

  1. git status shows files with “both modified”.
  2. Open the file (VS Code shows buttons Accept Current/Incoming Change).
  3. Resolve the conflict, remove the markers <<<<<<<, =======, >>>>>>>.
  4. git add file
  5. git commit (for merge) or git rebase --continue (for rebase).
  6. Abort: git merge --abort or git rebase --abort restores the previous state. With git mergetool a graphical tool opens.

Preventing

  • Often sync with the main branch (git pull, git merge main) so differences stay small.
  • Small, short branches and small commits.
  • Agree in the team who works on which files.
  • Use formatters consistently so no whitespace conflicts arise.
  • Test after resolving: a conflict can lead to logically wrong but syntactically valid code. For binary files or lock files (package-lock.json) it often helps: choose one side and regenerate.

See also: Git: not a git repository