GENERAL

Think Like a Git, Commit Like a Boss: Squash like a Pro


During the course of working on projects, situations will arise where you have to send pull requests to a branch on a project.

Note: If you don’t know what a pull request means, don’t worry we’ll cover it soon in a later post.

What if you had to work on a little feature or fix a bug and you worked on it  and sent multiple pull requests before the developer in charge of merging the commits into the master/staging/feature branch finally decides to accept?.

Many times, especially when you are contributing to Open Source Projects, you’ll be asked to squash those multiple commits into just one commit.

So, what the hell is Squash? A drink?, A type of Food?, A sporting activity?

Let’s get to work

Back to our git-education project:

Let’s add 3 more commits and push to the master branch:

Open your notes.txt and add a line to it like so:

Add the first commit:

Let’s add more text to the initial text we added to the notes.txt file, Now that text should look like this:

Add the second commit:

Let’s add more text again to the text we added to the notes.txt file, Now that text should look like this:

Add the third commit:

Now, check the history using git log:

We should have something like this showing our last 3 commits:

Now, let’s push to the master branch like so:

Time to Squash :smile:

Let’s see how to squash those three commits into just one commit. Run this command:

3 just simply means the latest 3 commits

Your terminal should open an editor with the three latest commits like this:

with the latest commits at the bottom.

We want the latest, so go ahead and enter the INSERT mode by pressing I. change the other two commits to squash like so:

then save and exit the editor.

If you get this error message: “Could not execute editor“. Just run this command like so:

Now, saving and exiting the editor will perform some rebase and open another window like so:

 

You can choose to delete all the commit messages and write a completely new commit message or you can decide to comment out the commit messages you don’t want and leave one to serve as the new commit message.

In our situation, I’ll prefer to just comment out the first and second commit by prepending # to the commit messages. So our commit message will be the third one which is Add squash and stash notes properly. Save and exit the editor.

Run git log again to see the git history:

Voila!!!!, now those 3 commits have been squashed into one!

Note: Since we have only squashed them locally, if we want it to reflect on the commits online, we’ll have to force push.

Let’s do that by doing:

Awesome, Now you have all the power in the world to squash like a Pro! :smile:

Please, let me know if you have any questions or observations in the comments section below.

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.