Imagine this situation. You've "pulled" in a bunch of code for your project into your local development git repository, but afterward realized you want to go back to a previous version or "commit" in your code. Using the "git revert" command, because it sounds like it is going to put things back to what they were, you actually end up making a mess of your repository and are left scratching your head and wondering what went wrong.

If this has happened to you don't feel too bad, this is a common misconception about how git revert works.

What Git Revert Actually Does

The revert command does not “revert” to a specified commit, it reverts the actual commit itself. Essentially, it undoes everything that was done in the specified commit and then creates a new commit in the process.  The text below is an example of what the inadvertent git error might look like when using git revert incorrectly:

$ git revert 5a82086

error: could not revert 5a82086... Issue 7118 by AB. Initial commit from project.

hint: after resolving the conflicts, mark the corrected paths

hint: with 'git add <paths>' or 'git rm <paths>'

hint: and commit the result with 'git commit'

In the unfortunate example provided above, running the revert command instructed git to delete all the code that was added in that initial commit (i.e. everything). Because there were so many commits after 5a82086, there were many conflicts and git revert was unable to finish. This left the revert in limbo with a bunch staged deletions and unmerged conflicts. So, what are your options for putting things back the way they were?

The Solution

First of all, we need to fix the git errors, and then we'll set everything back to the current master branch and cancel the revert.

$ git reset HEAD ./ # Unstage conflicts  

$ git checkout -- ./ # Unstage deletions and reset everything back to master

$ git revert --abort # Cancel the pending revert operation

Then, change the working directory to a specific commit by running checkout with the commit hash.

$ git checkout 5a82086

Using the “tagging” feature of Git can help us in this kind of situation in the future. In this case, let’s tag the historical commit we want to get back to as "bookmark".

$ git tag bookmark

$ git push origin bookmark

If this happens again, all that needs to be done is:

$ git checkout bookmark

When Would Git Revert Be Applicable?

Regardless of this unfortunate type of episode, git’s revert command is a very useful tool. It could be relied upon when for example you’re tracking down a bug and find that it was introduced by a single commit. Instead of going in and manually fixing and committing a new version or snapshot, you can use git revert to do all of that stead. Even better though, it does not remove the commit from the project history allowing for reliable collaboration and the assured integrity of your repositories history.

Related Articles