DEV Community

Michael Uloth
Michael Uloth

Posted on • Originally published at michaeluloth.com on

Undoing a Merge to Your Main Git Branch

A yellow roadsign showing a 180-degree curve approach, indicating you'll be heading back the way you came.

You merge your PR only to discover you accidentally missed a bug and now prod is broken. Gah! Is there a quick way to undo that merge?

Yes! What you need to do is “revert” your PR. Here’s how to do that using the GitHub UI.

Reverting a PR

  1. In the browser, go to your merged PR
  2. Click the “Revert” button near the bottom of the page to automatically create a new revert- branch that reverses your changes
  3. When prompted, open a PR for that revert- branch
  4. Merge the PR

That’s it. 😀 Crisis averted. Your main branch is back how it was before you merged your feature.

Restoring your original feature branch

If you want to debug and re-open an improved version of your original PR, here’s what you need to do:

  1. Click the “Revert” button at the bottom of the reversion PR you just merged to create a new revert-revert- branch that includes the same changes as your original feature branch (by reverting the changes that reverted them)
  2. Pull that revert-revert- branch locally (don’t open a PR yet) and make any changes you like to this new copy of your feature branch (not your old one!)
  3. When ready, push your changes and open a new PR for the revert-revert- branch that contains the repaired version of your feature
  4. Merge when ready

Reverting a commit

So far, these steps have assumed the change that broke prod came from a PR. But what if you committed directly to main?

That’s a simpler fix. You’ll just need to revert that bad commit (no PR required):

git checkout main
git log # find the hash of your bad commit ("q" to exit)
git revert HASH
git log # admire your new "Revert X" commit (optional)
git push
Enter fullscreen mode Exit fullscreen mode

Or using Lazygit:

  1. Go to the Branches panel and check out main
  2. Go to the Commits panel and highlight the bad commit
  3. Press t to revert your commit (you’ll see a new commit appear reversing your bad one)
  4. Press P to push the new commit to your remote branch

Try, try again

These steps have helped me out of multiple “oh 💩” moments at work. I hope they help you too!

Reverting your reversion may seem a bit strange the first time you try it, but hopefully it will make sense as you think about it. 🙂

Further reading

Top comments (0)