How to Revert a Remote Branch Merge Commit in git

Sometimes you need to revert a merge that was made some time ago and has been integrated into another branch (probably master, but it could be any branch).

Here is the approach I use.

I like to use SourceTree for day to day operations, but not for reverting a remote branch. For this, I use the command prompt.

Here are some things that you need to do before running the command to revert:

  • Make sure that you have checked out the branch that has been merged to.
    • This is because, when you revert the merge, the reverse changes will be calculated against the target branch of the original merge.
    • Also, this will put you in a good position to test the reverted changes (i.e. perform a build and some bench testing) to make sure that it did what you wanted.
    • And if that were not enough, if everything checks out, you can now commit the reversed changes back into the correct branch. Of course, this is git, and your goals may be different – you may want to start a branch from the reverted changes! The possibilities are endless…
  • Get the commit hash of the merge commit – this is the commit that is the merge into the branch.
    • The <commit hash> is the first 7 characters of the commit guid. You can look this up in your UX tool or with a git command. I do not cover that here.

Once you have this, you can run the command

git revert <commit hash> -m 1

Keep in mind, though – nothing says that this will be without file conflicts. The more time that has passed (or specifically the more changes that have been made since the commit that you want to rollback), the greater the chance for conflicts.