Chapter 10: Merging and Conflict Resolution
Now that you know how to branch, you need to know how to merge those branches back together.
Basic Merging
Suppose you've finished work on your feature-login branch and want to merge it back into main.
-
Switch to the target branch (the one you want to merge into):
git switch main -
Run the merge command:
git merge feature-login
Fast-Forward Merge
If the main branch hasn't moved since you created feature-login, Git performs a "fast-forward." It simply moves the main pointer forward to the feature-login commit.
Three-Way Merge
If main has also received new commits while you were working on feature-login, Git performs a "three-way merge." It uses the common ancestor of the two branches and creates a new merge commit that combines the work.
Merge Conflicts
Sometimes, things don't go smoothly. If you and someone else changed the exact same line in the same file, Git won't know which version to keep. This is a merge conflict.
When a conflict occurs:
- Git stops the merge process.
- It marks the files as "unmerged."
- It adds conflict markers to the affected files:
<<<<<<< HEAD
This is the version on the main branch.
=======
This is the version on the feature branch.
>>>>>>> feature-login
How to Resolve a Conflict
- Open the file: Look for the conflict markers (
<<<<<<<,=======,>>>>>>>). - Choose your version: Manually edit the file to look exactly how you want it (and remove the markers).
- Stage the file:
git add filename.txt - Complete the merge:
git commit(Git will provide a default merge message).
Aborting a Merge
If you get overwhelmed by conflicts and want to start over:
git merge --abort
This returns your repository to the state it was in before you started the merge.
Best Practices for Merging
- Merge often: Don't let your feature branches get too far behind the main branch.
- Keep commits small: Smaller commits are easier to merge and cause fewer conflicts.
- Commit before merging: Always make sure your working directory is clean before starting a merge.
In the next chapter, we'll learn about an alternative to merging: Rebasing.