How To Squash Existing Commits Into One
Git
24/05/2021
Git allows you to easily change any commit history and this includes merging multiple commits. Assume you want to merge your last 3.
git rebase -i HEAD~3
To achieve this goal, use the rebase
command, which simply allows us to reapply our commits. -i
makes the whole process interactive 🕹 and HEAD~3
represents the 3 latest commits.
Run the command and you'll be greeted by the following:
pick e061ddd Some commit messagepick e215bb2 Another commit messagepick e0401f2 Bananas
# Rebase 1b15b90..e0401f2 onto 1b15b90 (3 commands)## Commands:# p, pick <commit> = use commit# r, reword <commit> = use commit, but edit the commit message# e, edit <commit> = use commit, but stop for amending# s, squash <commit> = use commit, but meld into previous commit## [...]
Your IDE may default to a text editor like Vim or Emacs. If you aren't familiar with the editor, you will need to look up the pertinent keystrokes to interact with the text.
To merge several commits, squash everything into the most recent one. I also prefer to reword the latter to a more descriptive title. You can achieve this by changing the word in front of each commit message to the correct command (as shown in the legend above).
reword e061ddd Some commit messagesquash e215bb2 Another commit messagesquash e0401f2 Bananas
After you apply those changes, you will see another wall of text. 📃
Some commit message # Please enter the commit message for your changes. Lines starting# with '#' will be ignored, and an empty message aborts the commit.## [...]
Here you may rename your commit to something like Many commits and bananas
. Apply the change and you'll be greeted by yet some more text.
# This is a combination of 3 commits.# This is the 1st commit message:
Many commits and bananas
# This is the commit message #2:
Another commit message
# This is the commit message #3:
Bananas
# Please enter the commit message for your changes. Lines starting# with '#' will be ignored, and an empty message aborts the commit.## [...]
I usually comment out all the remaining commit messages with a #
as I already reworded the first message to something more descriptive. Of course, you may keep them if you prefer a more detailed commit history.
Apply the changes and Bob's your uncle! 👨🦳