Git Merging and Conflicts
Merging brings the work from one branch into another, usually a finished feature into main.
How to Merge
Go to the branch that should receive the changes, then merge the other branch into it:
Example
git switch main
git merge order-formUpdating 8b41d07..5c7e2d1 Fast-forward order.html | 1 + 1 file changed, 1 insertion(+) create mode 100644 order.html
Now main has the order form. You can delete the feature branch:
Example
git branch -d order-formTwo Kinds of Merge
| Type | When it happens | Result |
|---|---|---|
| Fast-forward | main had no new commits since the branch started | Git just moves the main label forward |
| Three-way merge | Both branches have new commits | Git creates a new merge commit joining them |
A three-way merge opens an editor for the merge commit message. Save and close it to finish (in the default Vim editor, type :wq and press Enter).
Merge Conflicts
A conflict happens when both branches changed the same lines of the same file. Git cannot decide which version is right, so it asks you.
Example: on main, Ayesha changed the heading to "Ali's Bakery". On the branch new-heading, Ali changed the same line to "Fresh Bakes Karachi".
Example
git merge new-headingAuto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result.
Reading Conflict Markers
Open index.html. Git has marked the conflict:
Example
<html>
<<<<<<< HEAD
<h1>Ali's Bakery</h1>
=======
<h1>Fresh Bakes Karachi</h1>
>>>>>>> new-heading
</html>| Marker | Meaning |
|---|---|
<<<<<<< HEAD | Start of your current branch's version |
======= | Divider between the two versions |
>>>>>>> new-heading | End of the other branch's version |
Resolving the Conflict
- Decide what the final text should be: one version, the other, or a mix.
- Delete the markers and keep only the final text.
- Stage the file and commit.
Example
<html>
<h1>Ali's Bakery: Fresh Bakes in Karachi</h1>
</html>Example
git add index.html
git commit -m "Merge new-heading and combine both headings"[main 7d1f3a8] Merge new-heading and combine both headings
VS Code shows conflicts with buttons: Accept Current, Accept Incoming and Accept Both. It makes resolving conflicts much easier.
Cancelling a Merge
If a merge goes wrong and you want to start again:
Example
git merge --abortYour files return to how they were before the merge.
Avoiding Conflicts
- Merge
maininto your feature branch often, so you deal with small differences early - Keep branches short-lived: merge within days, not months
- Talk to your team about who is editing which files
- Make small, focused commits
Exercise
Exercise
You see <<<<<<< HEAD in a file after git merge. What should you do?
