Why Squash Commits?
When working with Git, it’s common to make multiple small commits while developing a feature or fixing a bug. However, before merging changes into the main branch, squashing commits can offer several benefits:
1. Keeps History Clean
Squashing reduces noise in the commit history, making it easier to read and understand. Instead of dozens of incremental commits, a single well-written commit message explains the changes.
2. Easier to Revert
If a bug is introduced, reverting a single squashed commit is simpler than reverting multiple related commits.
3. Enhances Code Review
A smaller, well-structured commit history makes it easier for reviewers to understand what changed and why.
4. Reduces Merge Conflicts
Multiple small commits can increase the chance of merge conflicts. Squashing minimizes this risk by consolidating changes.
How to Squash Commits
There are several ways to squash commits in Git, depending on your workflow.
1. Interactive Rebase (git rebase -i
):
To squash commits using interactive rebase, run:
# Rebase the last N commits
git rebase -i HEAD~N
Replace N
with the number of commits you want to squash.
Git will open an interactive editor listing the commits:
pick 123abc First commit
pick 456def Second commit
pick 789ghi Third commit
Change pick
to squash
(or s
) for all but the first commit:
pick 123abc First commit
squash 456def Second commit
squash 789ghi Third commit
Save and close the editor. Git will prompt you to write a new commit message.
2. Squash While Merging (git merge --squash
):
If you’ve been working on a feature branch and want to merge it with a single commit, use:
git checkout main
git merge --squash feature-branch
git commit -m "Merged feature-branch as a single commit"
3. Squashing in Pull Requests (GitHub/GitLab/Bitbucket UI):
Many Git hosting services offer an option to squash commits when merging a pull request:
- GitHub: Choose “Squash and merge” when merging a pull request.
- GitLab: Select “Squash commits” before merging.
- Bitbucket: Similar options exist in the merge request interface.
Conclusion
Squashing commits is a great way to maintain a clean, readable Git history, making it easier to collaborate with others. Whether using git rebase -i
, git merge --squash
, or a Git hosting service, squashing should be a regular part of your Git workflow.
Do you squash your commits? Let me know your thoughts in the comments!