Merging and conflicts
Merging combines the work from one branch into another. Most merges happen automatically. Occasionally, two branches change the same lines, and Git asks you to decide. That's a merge conflict, and it's nothing to fear.
Fast-forward merge
If main hasn't moved since you branched, Git simply moves the main pointer forward. No new commit is needed.
The output says Fast-forward. The graph is still a straight line.
Three-way merge
If both branches have new commits, Git creates a merge commit with two parents, combining both lines of history.
Look at the graph: the two lines join at a merge commit (the hollow circle). Both search.txt and footer.txt exist.
Git finds the merge base (the last commit both branches share), compares each branch with it, and combines the changes. That's why it's called a "three-way" merge.
Merge conflicts
A conflict happens when both branches change the same part of the same file differently. Git can't know which version you want.
Git marks the conflict inside the file:
<<<<<<< HEAD
Free shipping this week ← your current branch (main)
=======
BIG SALE: 50% off! ← the branch being merged (sale)
>>>>>>> saleResolving a conflict
- Open the file and decide what the result should be: one side, the other, or a combination.
- Delete the conflict markers (
<<<<<<<,=======,>>>>>>>). git addthe file to mark it resolved.git committo complete the merge.
Continue in the terminal above. Type these one at a time:
echo "BIG SALE: 50% off + free shipping!" > banner.txt
git add banner.txt
git status
git commit -m "Merge sale banner"
git log --onelineChanged your mind mid-merge? git merge --abort puts everything back the way it was before you started.
Tools that make conflicts easier
- VS Code highlights conflicts with buttons: Accept Current, Accept Incoming, Accept Both, and a 3-way merge editor.
git mergetoolopens a configured visual diff tool.git diffduring a conflict shows exactly what's clashing.
Avoiding painful conflicts
- Merge or rebase from
mainoften, so your branch never drifts far. - Keep branches short-lived and pull requests small.
- Agree on code formatting (Prettier, Black, gofmt) so formatting changes don't collide.
- Communicate when two people need to change the same file.
Practice
Create a conflict yourself: a file menu.txt with "Coffee", then on a branch tea change it to "Tea", and on main change it to "Juice". Merge tea into main, resolve it so the file says "Coffee, Tea and Juice", and finish the merge. Check the graph shows a merge commit.
1.When does Git perform a fast-forward merge?
2.You've edited a conflicted file and removed the markers. What's next?