Checkout a GitHub Pull Request

Git, GitHub, Life Hacks Posted on

If you work with a lot of open source projects, you may find a need to modify a GitHub Pull Request before merging to the master branch. This may be because you need to rebase, fix a failing test, or resolve a merge conflict caused by an upstream change.

If you have used the hub gem before, you are probably familiar with the following code:

$ hub checkout custom-branch

But hub has some drawbacks, mainly that it is "yet another thing" you need to install and understand. Thankfully, GitHub provides an easy way to checkout a remote Pull Request just using Git!

From inside the root of your repository, run the following command, replacing $NUMBER with the Pull Request number:

$ git fetch origin pull/$NUMBER/head:pr-$NUMBER

This will create a new branch named pr-$NUMBER. You can then checkout the branch:

$ git checkout pr-$NUMBER

This can easily be converted into a shell function:

checkout-pr () {
  git fetch origin pull/$1/head:pr-$1 && git checkout pr-$1;

You could then use this shell function to checkout a PR:

$ checkout-pr 123

But it seems like this should be a Git command... You can wrap the whole thing up in a Git alias:

  pr = "!f() { git fetch origin pull/$1/head:pr-$1 && git checkout pr-$1; }; f"

Now, when you want to checkout a remote GitHub Pull Request, simply run the following command:

$ git pr NUMBER

I have been using this alias for over a year now, and I absolutely love it. I hope you find it useful too!

About Seth

Seth Vargo is an engineer at Google. Previously he worked at HashiCorp, Chef Software, CustomInk, and some Pittsburgh-based startups. He is the author of Learning Chef and is passionate about reducing inequality in technology. When he is not writing, working on open source, teaching, or speaking at conferences, Seth advises non-profits.