Duplicated lines of code after a merge
What just happened
Git merges line by line, it doesn't understand code. Three classic causes: a conflict resolved by keeping both sides; the same code added in both branches at slightly different places (Git keeps both, without any conflict); or the same change brought twice (cherry-picked, then the whole branch merged).
Potential risks
- It may build but run twice (an event handler registered twice, a double payment callโฆ).
- Or break the build with duplicate declarations.
Before you run anything
- Don't undo the merge blindly: first find which copy is the right one.
- After every merge, build and run the tests before pushing.
- Golden rule: before any destructive command, create a safety branch with git branch backup/before-fix โ it costs nothing.
Recovery steps
- 1
See exactly what the merge changed
Right after the merge, ORIG_HEAD is your branch before it. Otherwise compare with the merge commit's first parent (HEAD^1).
Safe$ git diff ORIG_HEAD HEAD -- path/to/file# later on:$ git diff HEAD^1 HEAD -- path/to/file - 2
Find who added each copy
blame on the duplicated lines shows the commit of each copy: you'll know which branch brought which one.
Safe$ git blame -L 10,60 path/to/file - 3
Look for forgotten conflict markers
A resolution done too fast often leaves both sides AND the markers.
Safe$ git grep -n -e "<<<<<<<" -e ">>>>>>>" - 4
Fix it by hand (works pushed or not)
Remove the wrong copy, build, test, then commit the fix. The safest option in every case.
Safe$ git add path/to/file$ git commit -m "fix: remove code duplicated by the merge" - 5
Not pushed: redo the merge properly
Cancel the merge, then merge again with a conflict style that shows the original version: much easier to choose.
Destructive$ git reset --hard ORIG_HEAD$ git config --global merge.conflictStyle zdiff3$ git merge feature/my-branch - 6
Already pushed and badly broken: revert the merge
Cancels the whole merge without rewriting history. Merging the branch again later will need a revert of this revert.
Caution$ git revert -m 1 <merge-commit-hash>$ git push
These procedures are provided for information only. Read each command and adapt it to your situation before running it. Disclaimer