How to Revert Pull Request with Github CLI in Powershell

Pavol Kutaj
2 min readAug 15, 2023

--

The aim of this page📝 is to explain how to revert a pull request on GitHub using the GitHub CLI and git based on the particular example of creating a PowerShell script to automate the process.

  • NOTE: we’ll get gh pr revert soon that makes the script useless, subscribe to https://github.com/cli/cli/issues/6034 to be notified!
  • NOTE#2: I am also not handling the navigation to the proper repo, that’s up to you
  • A pull request is a way to propose changes to a codebase on GitHub.
  • Once a pull request is merged, the changes are incorporated into the codebase.
  • Sometimes, it may be necessary to revert the changes from a merged pull request.
  • The GitHub CLI is a command-line tool that allows you to interact with GitHub from your terminal.
  • The gh pr view command can be used to view information about a pull request, including the merge commit SHA.
  • The git revert command can be used to create a new commit that reverts the changes from a specified commit.
  • By combining these two commands, it is possible to revert a pull request using the GitHub CLI and git.
  • In this example, we will create a PowerShell script that automates this process.
# Define the function
function revertPR {
# Ask for input for pull request
$pullRequestNumber = Read-Host -Prompt "Enter the pull request number to revert"

# Check out a branch with name the name revert_<pull_request_to_revert>
$branchName = "revert_$pullRequestNumber"
git checkout -b $branchName

# Get the SHA to revert with GH CLI
$mergeCommitSHA = gh pr view $pullRequestNumber --json mergeCommit -q .mergeCommit.oid

# Create a revert commit with git revert
git revert -m 1 $mergeCommitSHA

# Push that to remote
git push --set-upstream origin $branchName

# Create a new PR with GH CLI
gh pr create --title "Revert PR #$pullRequestNumber" --body "This PR reverts the changes from PR #$pullRequestNumber"
}

# Call the function
revertPR

This script defines a function called revertPR that performs the following actions:

  1. Asks for input for the pull request number to revert.
  2. Checks out a new branch with the name revert_<pull_request_to_revert>.
  3. Gets the merge commit SHA for the specified pull request using the gh pr view command.
  4. Creates a new commit that reverts the changes from the specified pull request using git revert.
  5. Pushes the new branch to the remote repository.
  6. Creates a new pull request using the gh pr create command.

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com