Sub topic 11
Resolving merge conflicts
This chapter assumes you know basic Git (commit, branch, push, merge) and have a pull request open on a feature branch. It shows why a pull request can show conflicts and how to resolve them.
Why conflicts happen
A merge conflict occurs when Git cannot combine two changes on its own. It usually happens when your branch and the base branch (usually main) both changed the same lines of a file. It can also happen when one side deleted a file that the other side edited.
GitHub shows the message "This branch has conflicts that must be resolved" and disables the merge button. Git can only merge cleanly if no changes overlap. Otherwise, a person must choose the result.
The resolution loop
Resolve conflicts on your own machine, where you can run the tests:
git fetch origin
git switch fix-login-timeout
git merge origin/mainGit stops and reports the conflicted files. Run git status to list them. Inside each file, Git marks the competing versions:
<<<<<<< HEAD
const timeoutMs = 30000;
=======
const timeoutMs = 20000;
>>>>>>> origin/mainThe section above ======= is your branch. The section below it is the incoming main. Edit the file to the version you want, and delete all three marker lines. You can keep one side, keep the other, or write a combination:
const timeoutMs = 30000;Then mark the file as resolved and finish the merge:
git add src/config.js
git commit
git pushThe push updates the pull request. GitHub re-checks it, and the conflict warning disappears. If you ran git merge, Git has already prepared a merge commit message, so git commit without -m accepts it.
Merge or rebase
You can also run git rebase origin/main. Rebase replays your commits on top of main, so the history stays linear. You may have to resolve the same conflict once per commit, using git add and git rebase --continue. Rebase rewrites your commits, so the push must be git push --force-with-lease. Merge is safer on a branch that others share.
For small conflicts, GitHub's Resolve conflicts button opens a web editor. It works for text conflicts but does not let you run tests.
Common mistakes
- Committing with markers still in the file. Search for
<<<<<<<before you commit. - Choosing a side without understanding the other change. Read both, and ask the other author if unsure.
- Skipping the tests. A conflict-free merge can still break behavior, so run the suite after resolving.
- Using plain
--force. This can overwrite a teammate's commits, so use--force-with-lease.
Exercise
You merged origin/main into your branch and Git reports a conflict in src/config.js. List the commands you run, in order, to finish and update the pull request.
Show answer
Edit src/config.js and remove the conflict markers. Then run git add src/config.js, git commit, run the tests, and git push. The push updates the pull request.