Sub topic 8
Resolving Merge Conflicts
This chapter assumes you can create branches, commit, and run a basic git merge. It also assumes you know what a three-way merge is.
Why conflicts happen
Git merges by comparing three commits: the two branch tips and their common ancestor. If only one side changed a line, Git takes that change. If both sides changed the same lines differently, Git can't choose. It stops the merge and asks you to decide. Conflicts also occur when one side edits a file the other side deleted.
Starting a conflicted merge
git switch main
git merge --no-ff feature/loginIf the merge conflicts, Git prints a message like CONFLICT (content): Merge conflict in app.py and stops. The repository is now in a merge in progress. Your other files are merged and staged, and the conflicted files are left for you.
Reading the markers
Run git status. Files under "Unmerged paths" need your attention. Open one and you will see:
<<<<<<< HEAD
timeout = 30
=======
timeout = 60
>>>>>>> feature/login- Between
<<<<<<< HEADand=======is your current branch's version. - Between
=======and>>>>>>> feature/loginis the incoming branch's version.
Resolving
- Edit the file so it contains the final content you want. This can be one side, the other side, or a combination.
- Delete all three marker lines. Git does not check for them, so leftover markers get committed.
- Stage the file and commit.
git add path/to/conflicted-file
git commitGit pre-fills the commit message with the merge details. Save it to complete the merge. Then run git log --oneline --graph to confirm the merge commit has two parents.
Useful commands during a conflict
git merge --abortreturns the repository to the state before the merge. Use it when you started on the wrong branch or want to rethink.git checkout --ours pathorgit checkout --theirs pathtakes one whole side of a file. During a merge, "ours" is your current branch.git diffshows the remaining conflicts in a combined format.git mergetoolopens a configured visual merge tool.
Common errors
- Committing with markers still in the file. The code will usually fail to compile or run.
- Running
git commitbeforegit add. Git refuses while paths are still unmerged. - Resolving in the wrong direction by mixing up "ours" and "theirs". Check which branch you are on first with
git branch.
Exercise
During git merge feature/login, you edit a conflicted file, remove the markers, and run git commit, but Git says you have unmerged paths. What did you skip, and how do you fix it?
Show answer
You did not stage the resolved file. Run git add path/to/conflicted-file to mark the conflict as resolved, then run git commit to finish the merge.