I used to think revert would get you back to the state when a given commit was submitted. It does not. Instead it simply undo’s the given commit. To do the former, you’re better off using reset instead.

git reset --hard HEAD~5

Will take you back to the state of the repo 5 commits ago. If you have uncommited work you want left along then use --soft instead of --hard. git revert undo’s the commit who’s hash was given, and makes new commit with the changes that undo that given commit.

If it’s a merged commit then you have to use the -m option (for merge) along with either a 1 or a 2. 1, meaning you want to take it back to the state of the remote parent. 2 meaning you want to take it back to the state of your local parent. (I usually use 1. I trust remote more than myself)

If anything goes wrong when you try to revert use git cherry-pick --abort and try again.

Sometimes you may have to merge. If anything goes wrong with the merge you can use git merge --abort and start over.

So let’s go through this with a realistic (but hopefully not common) scenario. Let’s say some bad code went live. You’re on your site and notice something terribly wrong. Don’t fret! Let’s say you did a recent push and you think you know which commit has the problem, but don’t want to take the time to debug it while your live app is in a bad state. Here’s what you do (assuming you are up-to-date on your master branch).

$ get checkout -b revert-branch
$ get revert <bad commit hash>
$ git push origin revert-branch

Above we are checking out a new branch, undoing the bad commit, and pushing the branch up. You can find the hash of the bad commit on Github or with git log. git revert will put you in your default text editor with the commit message “revert “, so all you have to do is save and quit (:wq if your editor is vi or vim) and you’re ready to push up. Then pull the pr in and update the site and you’re in the clear!

This has been a quick-n-dirty guide on reverting in git.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s