Revert back to a commit even after you have pushed your code to remote

Problem

Sometimes we end up pushing some commits to remote repository, just realising that it was the wrong branch or any other reason.

The problem here is that you want to save your changes but you need to just put them in the right branch and revert back to a commit where everything was alright. So, how do you do that?

Solution

The way to fix this is 3 fold.

  • First we need to reset to a commit that we want.
  • Next we need to checkout to the right branch and save our changes.
  • Lastly we need to rebase our branch to the commit that we want.

1. Resetting

First let’s “git log” and find the commit that we want to go back to.

$ git log 

This will give you a list of commits in reverse order with the commit message, author, date create, and SHA-1 checksum. The SHA-1 checksum is the part we are interested in.

commit dc251e98c2f79d54ef375b903471754bc72c4699
Author: Thomas Hurd 
Date:   Wed Jun 24 00:13:10 2015 +0300

    change stars pink

commit 4c23aa9bbb41140eb4fdb91cc1e1ae78572d7076
Author: Thomas Hurd 
Date:   Tue Jun 23 06:02:44 2015 +0300

    update header

Once you choose the commit you want to go back to, we will reset our branch to the that specific commit by

$git reset 4c23aa9bbb41140eb4fdb91cc1e1ae78572d7076

When you reset your branch to the commit of you choice, any future commits will be undone and moved to the working directory.

2. Commit in another branch

Once we have made the reset we need need to commit our changes in a seperate branch.

So let’s create a seperate branch and checkout to it

$ git checkout -b new_branch

When you move to a new branch your changes will follow you there as well.
Commit your changes and push your branch to origin.

$ git add .
$ git commit -m "Saving Changes in new branch"
$ git push origin new_branch

Once you have pushed your changes checkout to your original branch.

Rebase your branch

Once you are done with saving the changes that you wanted to change let’s play with history a little. But before that we need to pull remote.

$ git pull origin master

You can use “git rebase” with option “-i “. The option -i stands for interactive and lets us choose the commits we want to modify in an editor.
Rebasing is usually used to merge a change to a commit back in time. But in this case we are going to use rebase to remove the changes on our remote repository and changing the history.

When you use “rebase” with a SHA-1 checksum git will ask which commits we want to keep coming after the one we chose.

$ git rebase -i 4c23aa9bbb41140eb4fdb91cc1e1ae78572d7076

In my machine this will pop vim asking me which commits I want to keep.
Delete the lines you don’t want to have and you are done.

Over and out.


booncon PIXELS is an international digital design studio in the heart of Helsinki.

Pretty code. Smart design.


booncon PIXELS

Comments