DEV Community

Cover image for Using 'git rebase' to Perfect Commits
Adam Hawley
Adam Hawley

Posted on • Originally published at adamjhawley.com

Using 'git rebase' to Perfect Commits

I have long tried to get into the good habit of committing as I develop. However, I often fell into the same scenario. On commit №4, I would realise that I should have worked something differently in commit №2.

Naively, my old approach was a combination of adding extra re-work commits and different forms of git reset. git rebase to the rescue!

The git rebase -i command was everything I believed had to be part of git but didn't know of. The -i flag is the 'interactive' mode of git rebase. Which allows you to choose which commits you want to rebase.

Let's have a look at an example to illustrate:

 raw `git log` endraw  output before correcting my mistake


At this point I made a mistake a couple of commits ago and have even made further changes to some of the bad code I have written as part of future commits.

To go back in time, I use git rebase -i <COMMIT_ID>. Where <COMMIT_ID> is the commit id of a commit BEFORE my mistake.

 raw `git rebase -i` endraw


As shown in the helpful comments, there are many commands I can use for each commit and each one is explained. The commands I use most-frequently are 'edit' and 'reword' ('reword' is for the times when you have a typo in your commit message).

Here we can change pick to e or edit next to our bad commit before saving and closing the file.

Then I can go in and change my mistake. Once the changes are made, I can git commit --amend to fix the commit itself.

Once my initial mistakes have been corrected and git knows about the fixes I can use git rebase --continue. git will now try to apply my old commits (№3 & №4) on top of my fixes.

If there are any conflicts git will let you know. These happen in this case if your fix for the broken code replaced some of the code that you changed in later, good commits.

You should solve the conflicts so that the code is as you would want it at that commit. Importantly, you should stop before using git commit --amend here. git stopped to let you shape the commit in the way you want it and did not apply it yet. This means that to save this rework in the same commit, you should just go straight to git rebase --continue where git will ask you to confirm/edit the commit message.

 raw `git log` endraw  output as if nothing was ever any different…


And there we have it! A clean git history with useful commits. Learning git rebase has truly given me a greater confidence using git and helped increase both my productivity and the quality of my work. I hope this you have managed to learn something too and thanks for reading this far!

To keep in the loop consider following me or signing up to my mailing list on the original post on my blog.

Top comments (0)