Jeroen van Baarsen

February 11, 2015
Fetch pull requests from a fork on Github

When I’m reviewing pull requests on Github, it is sometimes easy to be able to fetch the pull request locally. When the pull request is created in the same repository, this is easy; just checkout the branch and you’re done.

But what can you do when the pull request is created from a fork? The most obvious solution is to add the fork as a remote to your local git repository. This can be a great solution if you just review PRs for your team. But I’m reviewing PRs for GitLab, which has over 3800 forks and 390 contributors; It’s just not possible to have a remote setup for all those forks.

I was sure there was a better solution for this, so I went on a Google search and found the following solution. Github keeps a copy of the pull request in the repository. They are located at refs/pull/PR_NUMBER/head. So keeping this in mind we can create a simple git alias that will fetch the code from that “branch” into a local branch.

  1. Open your .gitconfig file: $ vim ~/.gitconfig
  2. Find the heading called [alias], if it’s not yet present add it
  3. Under the [alias] heading add the following alias:

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

  4. Save the config file.

You can now fetch the code for a pull request on a given project by going to that project folder and run the command: $ git pr PULL_REQUEST_NUMBER. So when we want to fetch pull request #2283 we enter: $ git pr 2283. This will then create a local branch called pr/2283 which we can then checkout with: $ git checkout pr/2283

To make things a clearer here is the content of my .gitconfig

  name = Jeroen van Baarsen
  email = jeroenvanbaarsen@gmail.com
  st = status
  lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
  c = checkout
  cb = checkout -b
  b = branch
  pr = "!f() { git fetch origin refs/pull/$1/head:pr/$1; } ; f"
  diff = auto
  status = auto
  branch = auto
[color "diff"]
  meta = yellow
  excludesfile = ~/.gitignore
  editor = /usr/bin/vim
  autocorrect = 1
  default = simple
  user = jvanbaarsen

I keep all my configs in Github, see my dotfile repository for more details.

If you have any questions about this, or just want to talk about git? Find me on Twitter, my handle is @jvanbaarsen