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
- In the browser, go to your merged PR
- Click the “Revert” button near the bottom of the page to create a new
revert-
branch that reverses your changes - When prompted, open a PR for that
revert-
branch - Merge the PR
That’s it. 😀 Crisis averted. Your main branch is back to how it was before 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:
- 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 (i.e. revert the reversion) - 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!) - When ready, push your changes and open a new PR for the
revert-revert-
branch with the repaired version of your feature - 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
Or using Lazygit:
- Go to the Branches panel and check out
main
- Go to the Commits panel and highlight the bad commit
- Press
t
to revert your commit (you’ll see a new commit appear reversing your bad one) - 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 do it, but hopefully it will make sense as you think about it. 🙂
Further reading
- Reverting a pull request • GitHub Docs 📚
- How to PR and merge again after reverting PR using Github Revert Button • StackOverflow 💬
- Undo a Git Commit • Justin Joyce 📖