October 1, 2019

Removing a previous git commit

One of the power with using Git is that you have the whole development history. You can go back in time and review past changes. But for the history to be useful, it needs to be relatively clean.

Picture yourself this scenario; there is a bug in your code that someone has spotted. You opt to fix it by making some changes and committing them to the repository. You and your teammates continue to push new commits on top of that bug fix. After a while, you spot a new bug that is more critical than the first one. It turns out that the last bug fix is the cause of it.

Naturally, you would want to undo the changes from the first bug fix. Then, attempt to fix it in another way.

‘Git revert’ offers an easy way to do that by simply adding a commit with the opposite change on the top of your branch.

1
git revert <commit-id>

Looking back at the history now, the tree could look something like this (if you use git lola).

1
2
3
4
5
6
7
* cf9706ee (HEAD -> master) Revert "Bad bug fix"
* 837e6ffb Change some UI design
* 07925c97 Add another cool feature
* e0939308 Bad bug fix
* 1ec8bf77 Add a new feature
* 2cb852ed Make some changes
...

This creates unnecessary clutter to our git tree, which should be avoided if possible. Which finally brings us to using ‘git rebase interactive‘!

Instead of creating a new commit on top of our tree, we will remove the faulty one. First, find out how far down the tree you have to go. Then run the following command in the terminal.

1
git rebase -i HEAD~N

In our example, N is 3, which will prompt us with the following view.

1
2
3
pick e0939308 Bad bug fix
pick 07925c97 Add another cool feature
pick 837e6ffb Change some UI design

Mark the commit you wish to remove as ‘drop’ instead of ‘pick’.

1
2
3
drop e0939308 Bad bug fix
pick 07925c97 Add another cool feature
pick 837e6ffb Change some UI design

Now save, exit and solve any possible conflicts. That’s it!

Note: A downside to using this technique is that a force push is required afterwards. That is a requirement every time the git history is changed.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *