Why squash
A feature branch often accumulates "WIP", "fix typo", and "address review" commits that bury intent. Squashing condenses these into a small number of logically meaningful commits before merging. Reviewers see clean history; bisect works on real units of change.
Squash on merge
The simplest approach: let the merge collapse the branch:
git checkout main
git merge --squash feature
git commit -m "Add feature X"
This stages the cumulative diff and you write a single commit message. The downside: the branch's history is lost.
Interactive rebase squash
For more nuance, keep a few commits but combine intermediate ones:
git rebase -i main
Change pick to squash (keep both messages) or fixup (drop the squashed message) on the lines you want collapsed. See "Interactive rebase mastery" for the full vocabulary.
Autosquash workflow
Mark a commit as a fixup at creation time:
git commit --fixup=<sha>
git commit --squash=<sha>
git rebase -i --autosquash main
Configure git config rebase.autoSquash true to enable this every rebase.
Reordering for clarity
During interactive rebase, swap lines to reorder. A useful pattern: bring related changes together so each commit makes one logical step. If a refactor must precede a feature, ensure the refactor commit comes first.
Splitting overlarge commits
Mark a line edit, then split:
git reset HEAD^
git add -p src/parser.c
git commit -m "Refactor parser"
git add -p src/runtime.c
git commit -m "Refactor runtime"
git rebase --continue
Common mistakes
Squashing across a merge collapses two branches into one mega-commit, often unintentionally. Squashing already-pushed commits forces collaborators to rebase. Losing context: a squash that replaces a 30-commit history with one bland message hides why you made each decision. Aim for several focused commits, not one giant one.
Preserving authors
If multiple people contributed to a branch, squashing erases their authorship. Add Co-authored-by trailers in the commit message to preserve credit:
git commit -m "Add feature X
Co-authored-by: Alice <[email protected]>
Co-authored-by: Bob <[email protected]>"
Related
See "Interactive rebase mastery", "Rerere: automatic conflict resolution reuse" for surviving repeated squash-rebase conflicts.