Revert a merge commit from a protected branch on GitHub.com

nak picture nak · Mar 2, 2017 · Viewed 89.9k times · Source

We have protected our develop branch on GitHub so that nobody downstream can push their commit directly. The commits need to go through specific feature branch and get merged through a pull request.

There came a scenario where a feature branch is merged into the develop branch (after proper review and changes) and we are required to revert it later (maybe due to changes in requirements). If I try to revert the merge commit downstream, it will not allow me to push, since the branch is protected. I remember GitHub providing revert button when we merge the branch. But somehow I am not able to see (or find) the button now. We needed to revert the commit on priority so we removed the protection from the develop branch for the time being and pushed the revert commit (ugliest hack).

Are there any other better alternative for reverting a commit from protected branch? Maybe I am missing or misunderstood some GitHub features.

One more scenario is, what if I have deleted the branch from GitHub after I have merged, how would I revert it then?

Answer

rink.attendant.6 picture rink.attendant.6 · Mar 2, 2017

Reverting on GitHub

You don't need to restore (undelete) branches on GitHub to revert merge commits resulting from pull requests. For example:

Revertable pull request

Non-revertible pull request

Sometimes the revert button doesn't appear. From GitHub Help on reverting a pull request:

Note: You may need to use Git to manually revert the individual commits if:

  • Reverting the pull request causes merge conflicts
  • The original pull request was not originally merged on GitHub (for example, using a fast-forward merge on the command line)

It took me a while to find an example, but if the head branch wasn't merged into the base branch using the big green button on GitHub then it can't be reverted on GitHub:

Non-revertable pull request

git revert

Locally on the command line, you can use the git revert command to revert changes.

This will work on both your protected branch and a downstream branch. git revert creates a new commit ahead of the current HEAD so you don't need to force push, and if from a downstream branch, you can manually create a pull request for the reverted changes.

Reverting a merge commit is slightly more complicated than reverting a single-parent commit, so I'd suggest taking a look at this question for more information, as it's something I've never done before.

If people aren't comfortable using the command line, I think SourceTree has an item on the context menu to revert a commit but I don't know how it handles merge commits. There might be similar options in other GUI applications.

Hope this helps!