Git checkout non-origin remote pull request

I don’t often review pull requests that come from non-origin remotes. This is largely because Automattic tends to create pull requests in the root repository. So, when I reviewed a pull request from an open source contributor today, I found myself wandering if there was a simple way to checkout the pull request locally for testing.

I knew that I could add a new remote, fetch from the new remote, and then checkout the pull request. But, my lazy developer brain figured there was an easier way. ?

So, I asked my fellow Automatticians if they had any tips/tricks and I got a few good ones.

First, and probably the best solution, is to use the Github’s CLI tool. Once you’ve installed that, you can then checkout a pull request locally with something like:

gh pr checkout {<number> | <url> | <branch>}

But, if you’re relatively happy with your git flow and are looking for a little helper for this specific case, then you may be interested in this blog post by Scott Lowe. In that post, Scott shares a tip for fetching the branch from the non-origin remote to your local machine in a single command:

git fetch origin pull/1234/head:pr-1234

In my testing, this worked very well for me. But, I wanted to be a bit lazier. So, I ended up throwing that command in a shell function that expects the pull request number as an argument and then:

  1. Fetches the branch from the non-origin remote
  2. Checks out the branch from the non-origin remote

That function looks like this:

function gcopr() {
	$( git fetch origin pull/"$1"/head:pr-"$1" )
	$( git checkout pr-"$1" )
}

I’ve got this function in my ~/.oh-my-zsh/custom` directory and I use it like this:

gcopr 42940

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading