Squash Git Commits
Git has a feature called squash, which allows users to combine multiple commits into a single commit in a branch. By squashing commits, we can keep repository’s commit history clean and neat.
Users generally squash commits when merging branches into “master” or “main” branches
Why Squashing?
When a team is working on a feature branch, based on number of developers and complexity, it will have more number of commits. When we merge feature branch with main or master branch all feature branch commits will be added to main or master branch commit history. this makes main or master branch commit history lengthy and has lot of unnecessary commit mesages.
so by Squashing, we can combine all feature branch commits into single commit.
How to Squash commits?
we can squash commits by using git’s “Interactive Rebase” or while merging into main or master branch.
Interactive Rebase
I have a branch called squash-demo with 3 commits, now I’m going to squash them into a single commit and update my remote branch.
To rebase we need to run below command.
git rebase -i HEAD~3
Since I’m combining last 3 commits I used HEAD~3.
Interactive rebase will open an editor for us to pick and squash commits, it looks like below screen shot before modifications.
Now we need replace pick with squash to combine bottom 2 with above one
after marking bottom 2 commits as squash then we need to save the file and exit, it will take us to another editor to edit commit messages. before making changes it appears like below.
after deleted/modifying commit messages my final commit message look like below.
once done save and exit the editor, that will squash commits into a single commit. to see changes run git log command.
To update remote branch, we need to force push.
git push origin squash-demo --force
the above command will update remote branch like below.
Using Squashing and Merge Option
We can also use “squash and merge” option to squash commits when merging pull requests.
Conclusion
In this quick demo we have successfully squashed commits of a branch to have clean history when we merge feature branch with main branch. you can find more information in Git official documentation.
For more on Git:
Git: Update a feature branch with remote main branch