Fork me on GitHub

Fetching Pull Requests from Open Source projects just got easier!

Fetching Pull Requests from Open Source projects just got easier!

There are some cases when you need to pull a specific Pull Request that hasn’t been merged yet. It’s easy to just checkout a branch from your own repositories. But what about fetching a specific PR from a repository you don’t own - like an Open Source project or a fork?

That’s something I do a lot as an Open Source maintainer.

When someone submits a PR to faker-ruby, and I want to test these changes locally, I can never remember how to checkout their Pull Request on my machine. I always have to search for how to do it.

Here are the two commands I always have to search for:

git fetch upstream pull/$pull_request_number/head:$local_branch_name
git checkout local_branch_name

But then I thought… what if there was a simple way to pass the PR number and the name of my local branch instead?

Well… there is one now!

Some time ago, I was reading about the lsof command and found out about clear-port on thoughtbot/dotfiles - a command to kill a process that is currently using a port. That got me curious about writing a similar command that could save me time when reviewing PRs from contributors.

How to git checkout a Pull Request from a Repository you don’t own

With the help of my teammates at Thoughtbot, I wrote my first bash script. Here’s how to use it next time you need to pull a PR/branch from upstream.

With dotfiles installed, to fetch a specific Pull Request into a new local branch, just run:

git co-upstream-pr $PULL_REQUEST_NUMBER $LOCAL_BRANCH_NAME

Let’s see an example 💡

Say you have faker-ruby set as your remote upstream and you want to checkout this PR. Using the script, you just need to run on your local repository:

cd faker-ruby
git co-upstream-pr 2734 test_locale_setting

and you will create a new local branch called test_locale_setting where you can test the PR changes.

If you’re curious, the script can be found here.

#!/bin/sh

set -e

pull_request_number=$1
local_branch_name=$2

if [ -z "$pull_request_number" -o -z "$local_branch_name" ]; then
  echo "usage: git co-upstream-pr <pull_request_number> <local_branch_name>"
  exit 1
fi

if git remote -v | grep -q upstream; then
  git fetch upstream "pull/$pull_request_number/head:$local_branch_name"
  git checkout "$local_branch_name"
else
  cat <<HELP
You don't have an upstream remote set.
Use:
  git remote add upstream {upstream_remote_url}

to set the reference and then try again.
HELP
fi

This was fun because it was my first time writing a bash script. I learned about gracefully handling script failures and guiding users on how to use the script.

What about you? Do you have any bash scripts that save you time? Let us know by reaching out on Twitter or via email.

See you in the next post!

Did you like this article? Then you're gonna love these other ones: