Git Squashing

Git Squashing

For the organization to whose codebase I commit regularly, Git squashing is not encouraged but not prohibited. They discourage it because they may need to look through the commit history to ascertain what was done when. But for the good of those who feel it is necessary for them in order to reduce on the number of commits on a pull request hence making it more tidy and to make it a little smarter and easier to read, I found it necessary to document how to squash your commits.

Vim and notepad++ git editors

First things first, Git comes with Vim Editor as its default editor and this can be a little frustrating to folks who have been using windows all their life hence figuring out how to edit , save and then exit the Vim Git editor can be a little scary for them. To those from a Linux background, this is a walk in the park.

So for those who find Vim editor a pain they would rather get rid of, worry no more because there is a way you can change Git's default editor to point to notepad++ which perhaps is more friendly for you. This can be achieved by simply running git config --global core.editor <directory address> in the Git bash and press Enter.

Performing a squash with Git

I have a pull request that i am working on the openMRS QA framework, so it is that example that i will use in this documentation guide. The pull request so far has four(4) commits that i would love to squash into one(1) commit as a way of having a tidy commit history. Let me go a head and jump into the steps to follow;-

  • Open the repository locally in a command prompt and run git log : This is in order to see the commit history of the whole repository am trying to commit to. qacommit.PNG
  • You can type q in the space next to the : character to quite the vim screen.

  • After quitting the vim screen, type in git rebase -i HEAD~4.

  • Vim editor will open showing the the last four(4) and most recent commits in reverse order.

  • Don’t try to edit text directly because all will get messed up, instead press I key on the keyboard to enter Insert mode, edit the all the three commits below the first commit pick with f.

  • Press the Esc key to enter command mode, then Shift + : and finally type in x.

  • Vim closes and Git performs the squashing and when finished, displays a status message: Successfully rebased and updated refs/heads/RATEST-200-Patch.

When i trigger git log again, i will only see the commit i wanted as shown below.

qasq.PNG

  • Finally force push the changes to your fork and check the pull request to ensure only one commit is left. Use git push origin <name of branch> --force.

That's all. 👋