Merge or Rebase? The Ultimate Guide to Git Merge Strategies
This article compares Git's merge and rebase commands by walking through a realistic two‑developer scenario, illustrating fast‑forward versus non‑fast‑forward merges, conflict resolution differences, commit‑history rewrites, and practical recommendations on when to choose each approach.
The author writes after a team discussion about Git's two branch‑integration commands, merge and rebase. Merge keeps the branch tree, while rebase rewrites history into a linear line.
Scenario: developers A and B both create feature/A and feature/B from the same master commit. Each adds three commits that modify the same file, guaranteeing conflicts.
Before A merges, the branch graph looks like the first image.
Merge A into master:
git checkout master
git merge feature/AThe second image shows that after the merge, master and feature/A are identical.
When B attempts to merge, a conflict occurs. The merge command:
git checkout master
git merge feature/BMerge creates a single merge commit that resolves all conflicts at once, as shown in the third image. The author notes that a merge commit (mr node) appears only when Git needs to create a new merge commit; fast‑forward merges do not generate one.
Fast‑forward merge : master is still at the branch’s starting point; merging creates no new commit.
Non fast‑forward merge : master has advanced (e.g., docs: add README) while the feature branch started earlier; merging produces a new commit and an mr node.
After undoing B’s merge, the author rebases B onto master:
git checkout feature/B
git rebase masterVS Code prompts a conflict for the first commit (fourth image). If every commit conflicts, each must be resolved individually, followed by git rebase --continue. Repeating conflicts can feel redundant when the same code changes across commits.
The final git tree (fifth image) shows a straight‑line history: no extra merge nodes, but the original commit hashes ( docs:3, docs:4, docs:6) have changed.
Conclusion
Merge preserves a non‑linear history and may create mr nodes.
Rebase rewrites commits into a linear history, eliminating extra mr nodes.
Merge resolves all conflicts in one step; rebase forces per‑commit conflict resolution.
Use rebase only on private, unpushed branches (e.g., to clean up history). For all other cases, merge is safer. git rebase -i can reorder or squash commits.
Never rebase a public branch because it rewrites shared commit hashes and forces others into conflicts.
java1234
Former senior programmer at a Fortune Global 500 company, dedicated to sharing Java expertise. Visit Feng's site: Java Knowledge Sharing, www.java1234.com
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
