Learning Git and GitHub [Part Five]

Reverting that Commit 🔄

Hello again, in this last post in the Github series, we are talking about reverting commits. This is a useful feature when you want to undo changes that you have made to your repository. this can be done in a few ways, and in this post, we will be covering how to do this using the command line. However there are a couple of ways to complete this.

Initially we will cover reverting a commit, In this case we’ve made a bad code push and want to remove from the repository.

Reverting a bad commit

Ok, So you’ve made the miscommit or want to remove a commit from your repository. This can be done using the git revert command. This command will create a new commit that undoes the changes that were made in the commit that you specify.

So in this example we have committed a file to the repo which contains some sensitive data which should not have been pushed, This could be for a number of reason. I.e it might have been missed from the .gitignore file or you might have forgotten to remove it before committing.

Ok, So the mistake has been made and I can here you shouting at the screen at the above image 😜. So to fix this!

1
git log 

git log, will show you the commit history of the repository. You will see a list of commits with the most recent commit at the top. If you wish to have a more in-depth read into git log, the git-scm docs page for git log is here

1
git log

From the git log results, you want to copy the commit id for example 1682e96dfe6c999845aecb5e3a5a50d0ab2e5ba3

git revert 1682e96dfe6c999845aecb5e3a5a50d0ab2e5ba3

this will open a vi window where you can add a commit message. Once you have added your message and saved the file, the commit will be reverted.

Public Service Announcement
this is a VI session, so to quit and confirm its :wq

Summary

Using this method, the file has been removed from the repository. But the commit history can still be seen.

Removing the commit history

In some cases, you might have accidentally pushed a commit to the repository containing a production secret (Hey, it happens, we’re all human!) and you want to remove the commit history. This can be done using the git reset command. check out the git-scm docs page for more information.

First you want to use git log to get the commit id on where you want to reset the commit history to. In this example, we are going to reset the commit history to the initial commit 0f466f7e1731af3e59a6f43e12d9e5d30ae8e2ab.

1
git reset --hard 0f466f7e1731af3e59a6f43e12d9e5d30ae8e2ab

1
git push --force

Summary

Adding the git reset and git push –force commands, the commit history has been removed from the repository.