Squashing git commit
Hide your sins by combining commits
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 you or anyone.
Don’t worry; there is a three-step procedure that helps you to hide your sins.
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.
git rebase -i HEAD~<no-of-commits> # Example: To squash the last three commits git rebase -i HEAD~3
It opens an editing window and lists the selected commits in chronological order (the first in time tops first).
There are multiple commands available, one of them is squash which says:
# s, squash = use commit, but meld into previous commit
squash by replacing pick to make commit combined with the last commit.
In this case, I am going to combine the last two commits to the first one. So I typed
squash for the last two commits. Isn't simple?
It is can be imagined as
bb5e3d1 ← bb5e3d1 + d1c8507 + 6d7c3c
Once you saved commands, Git allows you to change the message of the newly combined commit.
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.
git rebase --continue
For some reason, you may not want to continue with squashing. Git being generous allows you for that too.
git rebase --abort
Step 3: Force Push
Force Push is crucial to cancel any remote update.
git push <remote-server> +<branch> #notice + symbol # Example git push origin +master
You can try or experiment by forking the following repository on Github
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.