Introduction
Squash
in Git
means combining multiple commits into a single one. By using this feature, you can keep your repository’s history more readable and understandable.
In order to better illustrate this, let’s use an example.
Creating a new branch
Imagine that you have a LinkedList class and you would like to test its methods.
You start by creating a new branch.
git checkout -b test-linked-list-class
Creating some commits
After writing tests for the different methods in LinkedList
class, you create some commits.
In our case we have five new commits. We create the LinkedListTest
in the first one. Then in the second one we test the initialize
method of the class. In the last 3 commits we add the tests for the push
, pop
and get
methods.
Squashing
So we’re done with our commits and now it’s time to rebase.
Actually, we don’t really need all of the commits we’ve created. It’s enough to say in one commit that we’ve tested the class.
In order to do this and keep the Git
history more readable and understandable, we could squash
them into a single one and provide a meaningful message for it.
Let’s start with an interactive rebase.
git rebase -i main
This will open our favourite editor where we can choose how to manipulate this part of the history.
Here we can see our five new commits with the oldest one on the top.
The different commands that Interactive Rebase
allows will be listed below your commits.
In this example, we’re interested in using squash
. The lines marked as squash
or s
will be combined with the one above.
We can now save the file and close it.
A new editor window will then open where we can enter a message for the new commit.
After saving and closing the window, the Rebase
is completed and here’s the result:
Pushing to GitHub
git push origin test-linked-list-class -f
Conclusion
And here’s the result: the five old commits have been squashed into one and this one commit has been pushed to the remote.
Now we can merge the branch and the history will stay clean. :)
Stay safe!
Rado