Squashing commits is the act of combining a few commits into one. There are two places the term "squash" appears, in the context of git:
- Squash merge
- Manual squash
The squash merge is a special type of merging, that automatically takes all of the commits in one branch, squashes them together, and adds the result commit into the target branch (usually master).
Squash merge is partially addressed in the following issue of Git Weekly:
In this issue, we're going to talk about the ways one squashes a few commits together manually.
Manual Squash
Manual squash is possible through "interactive rebasing". Let's assume we want to squash 5 last commits together. We'll then do an interactive rebase on the last 5 commits:
git rebase -i HEAD~5
This command will start the interactive rebase. An editor (e.g. nano
) with content similar to what follows will launch:
pick f72e7cb Feat: Resurrect flatMap
pick 1a18b1c Feat: Add list transformations
pick 3420af4 3.0.0
pick f55a9ee Docs: Add marble diagrams to README
pick 0433f9d Update README.md
Keep the first line as is and replace every pick
in the following lines with an s
(for squash):
pick f72e7cb Feat: Resurrect flatMap
s 1a18b1c Feat: Add list transformations
s 3420af4 3.0.0
s f55a9ee Docs: Add marble diagrams to README
s 0433f9d Update README.md
Save and exit. Then the editor launches once more with the commit messages of all 5 commits. Feel free to delete it all and rewrite the whole message. Save and exit. And that would conclude the interactive rebase.
To verify that the squash was complete, do a git log:
git log
After the squash is done, if you want to push to your remote branch and any of the 5 commits were already pushed, you have to force it:
git push --force-with-lease
Notes
- Always push with
--force-with-lease
. Never use--force
. - In the interactive rebase commit picker, you can write
squash
instead ofs
. But I guess a simples
would be easier to write down. - To learn more about auto-squash, please refer to my "16 Git Tips and Tricks". I'll write more about it in detail.
- Subscribe to my Medium publishes to get notified when a new Git Weekly issue is published.
- Follow me on Twitter for weekly articles and daily tweets on git.
Top comments (0)