Squashing Git Commits

Hide your pain by combining commits.

Puneet Sapra
The Mighty Programmer
3 min readJun 17, 2018

--

Git is a leading version control software (VCS). There may be a time in your experience when you have to commit very often with a small change.

Typically, Feedback Loop involving work leads you to commit frequently.

  • To fix a problem, in a message-driven application, the impact of a fix is hard to foresee in downstream systems. The well-known technique: partially fix and verify.
  • You are experimenting with a configuration file driven system like CI (Jenkins, Travis). You have to frequent commits to check or learn the effect of the configuration changes.

Whatever the reason, if you look at the history of the git repository, it may frown or let your boss see your pain ;)

Last three commits are related; All can be combined to one commit

Don’t worry; there is a three-step procedure that may help you to hide your sin.

Step 1: Freeze branch

Forbid anyone to push any new change to the branch whose commits need to be squashed.

Step 2: Rebase

Rebase command let you move commits up or squash.

It opens an editing window and lists the selected commits in chronological order (the first in time tops first).

commits in chronological order

There are multiple commands available, one of them is squash which says:

Type squash by replacing pick to make commit combined with the last commit.

In this case, I am going to combine last two commits to first one. So I typed squash for last two commits. Isn’t simple ?

bb5e3d1 ← bb5e3d1 + d1c8507 + 6d7c3cc

It is can be imagined as
Mathematically

Visually

Once you saved commands, Git allows you to change the message of the newly combined commit.

edit message accordingly
difference between history

There may be chances that you may come across conflicts. In that case, resolve conflicts as your usual process. Once done, the following command will put you back in the race.

For some reason, you may not want to continue with squashing. Git being generous allows you for that too.

Step 3: Force Push

Force Push is crucial to cancel any remote update.

You can try or experiment by forking the following repository on Github
https://github.com/theBeacon/sqaush-gitty-demo
Checkout a new branch from feature/terrible-branch, to play with squashing.

Git allows you to rewrite history. Squashing is one example. Some may argue to use amend commit option, which allows rewriting the last commit. Remember, amend only works if the last commit is not pushed yet.

Some may also argue that it is tampering with history. Remember, It is about cleaning history.

--

--