Merging and rebasing
Merge
git merge feature combines histories:
- Fast-forward — if
mainhasn't moved sincefeaturebranched, Git just moves themainpointer forward. No merge commit. (--ff-onlyrefuses anything else.) - Three-way merge — if both moved, Git finds the merge base (common ancestor), combines both sides' changes, and creates a merge commit with two parents.
--no-ffforces a merge commit even when fast-forward is possible, preserving the fact that a feature branch existed.
Merges preserve history exactly as it happened, including the branch topology.
Rebase
git rebase main (on feature) replays your commits on top of the latest main, creating new commits with new hashes:
Result: linear history, no merge commit, easier to read and bisect.
The golden rule: never rebase commits that others have based work on (i.e. already pushed to a shared branch). Rewriting shared history forces everyone else into painful recoveries. Rebasing your own local or personal feature branch before merging is fine — then you'll need git push --force-with-lease.
Interactive rebase: clean up before review
git rebase -i main
# pick 1a2b3c add retry
# squash 4d5e6f fix typo ← combine into previous
# reword 7a8b9c add tests ← edit the message
# drop 0c1d2e debug logging ← remove
Also: fixup (squash and discard message), edit (stop to amend), reorder lines to reorder commits. git commit --fixup <sha> + git rebase -i --autosquash automates fixups.
Merge strategies on pull requests
| PR merge option | Result | Trade-off |
|---|---|---|
| Merge commit | All commits + a merge commit | Full history; noisy graph |
| Squash and merge | One commit per PR on main | Clean main, easy revert of a whole feature; loses individual commits |
| Rebase and merge | PR commits replayed linearly | Linear history with granular commits; commits get new hashes |
Many teams use squash merges for application repos (one PR = one commit = one revertable unit) and enforce linear history with branch protection.
Resolving conflicts
A conflict happens when both sides changed the same lines (or one deleted what the other edited). Git marks the file:
<<<<<<< HEAD
timeout: 30
=======
timeout: 60
>>>>>>> feature/longer-timeout
Resolve by editing to the correct result, git add the file, then git commit (merge) or git rebase --continue. Abort with git merge --abort / git rebase --abort. Tools: git mergetool, IDE merge editors. git config rerere.enabled true ("reuse recorded resolution") remembers how you resolved a conflict and reapplies it — useful with long-lived branches. Keeping branches short-lived is the real cure for painful conflicts.