How to Revert a Commit in Git

frustrated young man on a laptop

In the CMS world, it often happens that all of the sudden a module or plugin update doesn’t go as expected, but the issue is identified after you have already performed some other changes.  Let’s see the following Git commits as an example:

36d24dc (HEAD -> master) Define useful variables

3bdc82e Update module1

d755d00 Add module3

83dea80 Add module2

e391dc8 Add module1

6ff320f Initial commit

This is a very common scenario:

  • Modules for the application are added
  • After some days, updates with improvements/security for some of the modules are released
  • As a good practice, changes are tested and once approved, they are committed and pushed to the repo
  • Team members pull those changes to keep their instances up-to-date
  • A team member spotted an issue and the culprit is the last updated module

Here is where things get interesting.  Some may try to reset the HEAD to the commit before the module update:

$ git reset --hard d755d00

This would be useful if changes for updated module haven’t been pushed to the repo.  But, since those changes have been pushed and pulled by team members, using the previous command will generate a headache for all team members.

This is where Git revert should be used.  Git revert will create a new commit with the reverted changes.  This will ensure all team members get all those reverted changes without any complication (a/k/a conflicts.)

To use Git revert command, you should use the commit’s hash of the commit with the changes you want to revert (not the previous commit, as it might happen with Git reset).  This is how the command would look in our example:

$ git revert 3bdc82e

Commit 3bdc82e is the holding module1’s updates.  Once the command is executed, Git will show the editor to edit the commit message (if you want to modify its default revert message.)  Once the message is saved, a new commit will be added to the history.  It now should look like this:

b8afaca (HEAD -> master) Revert “Update module1”

36d24dc Define useful variables

3bdc82e Update module1

d755d00 Add module3

83dea80 Add module2

e391dc8 Add module1

6ff320f Initial commit

You can see how a new commit with changes introduced in commit 3bdc82e has been added.  It’s worth mentioning that changes for commits after 3bdc82e aren’t modified: it only reverted changes for the given commit.

That’s all, folks!  I hope this command helps you avoid conflicts in your workflow for those unexpected issues.