Skip to content
Author: ytianle (76.92%), ytianle (23.08%)

Revert PRs in Master⚓︎

This guide helps you revert merged PRs in master branch.

We are using git revert to revert the merged PRs in master branch. git revert can help to keep revert history while revert specific commits. Below are the steps to revert a merged PR in master branch:

  1. Create a new branch for the revert PR:

    terminal
    git checkout master
    git pull origin master
    git checkout -b <revert-pr-pr_number>
    

  2. Revert the merge commits of the PRs:

    terminal
    git revert -m 1 <merge1_commit_hash> # (1)
    git revert -m 1 <merge2_commit_hash> # (2)
    ...
    

    -m 1 explanation

    -m is required when you touch the merge commit, and you need to specify the parent number to indicate which side of the merge you want to keep. Same theory, git cherry-pick will also require -m flag when you want to cherry-pick a merged PR commit hash.

    -m stands for "mainline" and is used to specify the parent number of the merge commit. Normally, the first parent (1) is the branch you merged into (e.g., master), and the second parent (2) is the branch that was merged (e.g., feature branch).

    By using -m 1, you are telling Git to revert to the state of the first parent, effectively undoing the changes introduced by the merge commit. -m 2 is less commonly used.

  3. Push the revert branch and create a PR to master:

    terminal
    git push origin <revert-pr-pr_number>
    

    Then create a PR from <revert-pr-pr_number> to master.

Why not cherry-pick from the initial point?

After step 1, you might want to git reset --hard <commit_of_original_point> and then cherry-pick the commits you want to keep. However, this will not work. The reason is, when you check the final diff, those positive changes is a subset of the current master branch update. Nothing will be changed while merging.

E.g. You have master branch with PR history like o - A - B - C - D - E - F. You don't want to have C and F in the current master branch.

  • If you reset to o and cherry-pick A, B, D, E, the final diff will be +A +B +D +E, which had been done in current master branch. Nothing will be changed while merging.
  • If you revert C and F, the final diff will be -C -F. It tells git to remove the changes introduced by C and F, which is what we want.