When I heard this Git term for the first time from a colleague (who is English 💂), I thought it was a British idiom 🇬🇧. I even looked it up on urbandictionary.com, and I quickly realised that was an actual feature of Git. So, I had to teach this to myself. Then I googled “How to squash commits” and I ended up with a not very useful document on github. (https://github.com/wprig/wprig/wiki/How-to-squash-commits)

In very simple words, squashing your commits merges your several commits into a single commit. And there is no such “git squash blah blah” command either. We actually use “git rebase” command to achieve that. See the example case below to squash your commits 🙂

Example case

Assume that you have a development branch (called dev) and a feature branch (called my-pr-branch). The picture below lists my 4 commits which are on my-pr-branch.

how to squash commits sercan leylek

By following the steps below, I will squash those 4 commits into 1 commit.

STEP-1

Make sure that you are on feature branch:

git checkout my-pr-branch

STEP-2

Run the command below:

git rebase -i HEAD~4

In my case, I will squash 4 commits. Therefore, I rebase HEAD~4.

STEP-3

Previous step will open your default text editor. See my case below:

Screenshot 2019-06-29 at 18.04.27

STEP-4

Leave first line as it is and type ‘s’ for the first word of the other lines. As the comments also elaborate, ‘s’ stands for squash.

Screenshot 2019-06-29 at 18.05.51

STEP-5

After you save the editor (:wq), you will be demanded to save the merge request. Just save and move forward:

Screenshot 2019-06-29 at 18.10.04

FINAL STEP

Push your changes with the command below:

git push origin my-pr-branch --force
Squash commits
Result

And the result will be one commit to rule them all, one commit to find them.

giphy

Sercan Leylek / OSLO

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s