Squashing commits with rebase

When working with git, you might have the habbit of committing alot, and this is just fine. As long as you clean it up later.

Say you have the following history.

$ git log --graph --pretty=oneline --abbrev-commit --decorate --all
* 0c087b6 (HEAD, master) Even more typo.
* bd09af3 Fix another typo.
* 41205d5 Fix typo.
* 1ad6447 Add sticky footer.
* b93cbbb Add deploy script.
* 3cc4c63 Fix https mixed content.
* 9e42fa0 Add cache headers.
* 3f1b789 Implement homepage.
* 0089cc1 Init project

You might notice multiple commits that are related. Hint: typo's. Reading this log is small and easy, only when your project grows, multiple commits for the same change will create overhead.

Thankfully git can solve this issue with a technique called squashing.

Rebase

I will not be explaining what rebase it. If you want more info, see the manual. For now you only need to know rebase can alter and rewrite your history.

Squaching

As could see in the example, we want to combine the top three commit into one.

$ git rebase -i HEAD~3

The -i indicates we want to rebase using some interaction.

pick 0c087b6 Even more typo.
pick bd09af3 Fix another typo.
pick 41205d5 Fix typo.

# Rebase 0c087b6..41205d5 onto bd09af3
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

You can decide to squach commits into the above commit. Replace the `pick` commands with `s` or `squach` for those commits.

pick 0c087b6 Even more typo.
s bd09af3 Fix another typo.
s 41205d5 Fix typo.

# ...

Save and see the rebase happen. You will be prompted to compose the new commit message. Save your changes and you are done.

$ git log --graph --pretty=oneline --abbrev-commit --decorate --all
* bd09af3 (HEAD, master) Fix multiple typos.
* 1ad6447 Add sticky footer.
* b93cbbb Add deploy script.
* 3cc4c63 Fix https mixed content.
* 9e42fa0 Add cache headers.
* 3f1b789 Implement homepage.
* 0089cc1 Init project

Fork me on GitHub