Friday, May 2, 2014

Different ways to Revert GIT commits


In GIT, there are different requirements to revert changes. This includes reverting local changes in your working copy, revert a commit already made, rewrite already pushed GIT history etc. I'll show you how to do these in this blog. The `git log` I have used can be found at the end of this article.

  • To temporarily go back to a old revision, fool around, then come back to where you are, then you should checkout the desired commit.
git checkout 1f5d1eb7e

If you want to make some commits while you are in this older revision:
git checkout -b old_revision_branch 1f5d1eb7e


But, if you want to completely remove the commits you have made since a given revision, then there are two routes to go:

1. If you have pushed any commits:
#This will destroy all your local modifications:
git reset --hard 1f5d1eb7e

#But, if you have local work to keep:
git stash
git reset --hard 1f5d1eb7e
git stash pop
#This saves the modifications (git stash), and re-applies (git stash pop) it on top of the reset copy. You might get merge conflicts.

2. If you have already pushed the work:
Then you might not want to actually remove all the commits which will effectively rewrite the history. But what you can do is you can revert the commits. With git, revert has a very specific meaning: create a commit with a reverse patch to cancel it out. This way, you don't rewrite any history.

# This will create three separate commits
git revert 2ce3f91c4 0cc5599c5 3e5f8805a

# It also takes ranges. This will revert the last two commits:
git revert HEAD~2..HEAD

#Finally, commit
git commit


`git log`

commit 3e5f8805aa06d80d50f130107d48e4ec67289719
Author: Kasun Gajasinghe <kasung@wso2.com>
Date:   Wed Apr 30 02:14:20 2014 +0530

    cleaning up cxf ws-discovery

commit 0cc5599c57f443a937affcd2045617d8660a58e4
Author: Kasun Gajasinghe <kasung@wso2.com>
Date:   Wed Apr 30 01:51:51 2014 +0530

    moving APIScanner class to correct package

commit 2ce3f91c4262749ca262ddc0bf75924f13bbb485
Author: Kasun Gajasinghe <kasung@wso2.com>
Date:   Wed Apr 30 01:45:12 2014 +0530

    Adding support to read the WSDL 1.1 wsdl:portType from the JAX-WS annotations.

commit 1f5d1eb7ef6152de32f5c8282e765f3e8aaa6468
Author: chanikag <chanika@wso2.com>
Date:   Mon Apr 28 08:37:07 2014 +0530

    upgrade data-bridge conmponent to revision 201003

commit 64958bc9df641b3628d6d88ed39acb5e37eae688
Author: Chamath Gunawardana <chamathg@gmail.com>
Date:   Fri Apr 25 12:56:20 2014 +0530

    Updating pom

This was generously inspired from a Stackoverflow answer at http://stackoverflow.com/questions/4114095/revert-to-previous-git-commit