๐ Chapter 8: Merge Strategies โ Making Parallel Universes Converge โ
Fast-Forward Merge โ
When the main branch has no new commits and the target branch has progressed in a "straight line" from the main branch, Git will simply move the main branch pointer to the target branch's position. This is a "fast-forward merge."
# Scenario: You've been developing on a feature branch, main has no new commits
# Switch back to main
git switch main
# Merge the feature branch
git merge feature/user-login
Updating f4e5d6c..a7b8c9d
Fast-forward
login.html | 15 +++++++++++++++
style.css | 3 +++
2 files changed, 18 insertions(+)
create mode 100644 login.htmlFast-Forward Diagram:
Before merge:
main โ A โ B
feature โ A โ B โ C โ D
After merge (fast-forward):
main โ A โ B โ C โ D (main pointer moves to D)
feature โ A โ B โ C โ DIf you don't want a fast-forward and want to preserve the merge record, use --no-ff:
# Force create a merge commit (recommended! preserves branch history)
git merge --no-ff feature/user-login -m "merge: merge user login feature"Three-Way Merge โ
When both branches have their own new commits, Git needs to perform a "three-way merge" โ finding the common ancestor of both branches, then merging the changes from each.
# Scenario: Both main and feature branches have new commits
git switch main
git merge feature/product-search
Merge made by the 'ort' strategy.
search.html | 20 ++++++++++++++++++++
style.css | 5 +++++
2 files changed, 25 insertions(+)Merge Conflicts โ A Beginner's Nightmare โ
When two branches modify the same location in the same file, Git gets confused โ it doesn't know whose version to use. This results in a merge conflict.
# Scenario: Both Alice and Bob changed the title in index.html
git switch main
git merge feature/new-title
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.Open the conflicted file and you'll see markers like this:
<body>
<<<<<<< HEAD
<h1>Alice's Website</h1>
=======
<h1>Bob's Website</h1>
>>>>>>> feature/new-title
</body>Steps to resolve a conflict:
# Step 1: Open the file and find the conflict markers
# <<<<<<< HEAD -> Your version
# ======= -> Separator
# >>>>>>> feature -> Their version
# Step 2: Edit manually, decide what to keep
# You can choose one, or merge both changes
# Delete all conflict markers <<< === >>>
# Step 3: Add to staging area
git add index.html
# Step 4: Commit the merge
git commit -m "merge: resolve index.html title conflict"
# If you don't want to merge anymore, abort
git merge --abort๐ก Tip: When resolving conflicts, it's recommended to use VS Code or other visual tools. VS Code highlights conflict regions and provides quick buttons for "Accept Current," "Accept Incoming," and "Accept Both," which is much faster than manual editing.