What is Git Squashing?

Git Squashing is a technique which is being used to consolidate few commits to one commit.

Why?

Let’s imagine you are working on a feature; for example, creating shopping cart for an eCommerce website and you created your branch out of master and you are working on this feature for one or two weeks. You are most probably going to have a lot of commits just for saving your hard work, I bet that most of those commits’ message would be like “Adding total prices”, “Fix for adding total prices”, “Another fix for adding total prices” or even worse than these, but I’ll stop going further.

The point is that all of these commits are not helpful and they are just making noises for someone in future who is going to try to find a commit which is introducing a bug, or anyone who are just trying to find something in one of the commits. Therefore, we should combine all those commits into a single commit, with a good explanatory message.

 

Let’s imagine you have these five commits which you can see below, and as you see they don’t look really good and you don’t want to put all these commits to the master because you don’t want your colleagues hate you.

So, I will combine all these five commits to one with “Add shoppingcart feature to the shop” message.

How Do We Squash?

We are going to use git rebase command  for this purpose. Rebase has other uses in git which is out of the scope of this post. Below you can see I prepared these commits and showed them, using git log –oneline command.

Then, you need to type git rebase -i HEAD~5  after tilde (~) you should put the number of commits you want to combine, and you can see that based on my commands, I want to squash all commits from e6c250d to 7fd20be. After this command, your text editor will popup with some existing text, which you can see in the picture below. If your git used Vim as your text editor and you don’t like it, you can read here, how to change it to your favorite text editor.

Now, you can see all the commits with their messages, and some comments bellow them. I would suggest to read them to know how they work. We want to squash all of them to the first commit and not take any messages from those commits, and put a new message for all of them.

I will change the top commit from pick to r and the rest to f. That will make the first commit the main one. So, the rest will squash into and will let us change the message for it.

After saving and closing this editor window, another window will popup to let you type the message you want for your commit.

Then, you will see the following message, which means your rebase was successful.

You can use the git log command again to see how all those ugly commits became one commit with a proper message.

Now, you can use these few simple steps to have cleaner commits and be more respected as a developer.