Get a GitHub pull request to use locally

Posted by: on

Problem

You have some issue with a project from GitHub and you see that someone has submitted a Pull Request that solves your problem. How do you get that pull request into your local workspace before it is merged into the project?

Solution

First, look on GitHub and note:

  1. The Pull Request number

  2. The specific commit associated with that Pull Request that you want.

Finding info on pr

 

1
2
3
4
git clone https://github.com/<the project>
cd <project dir>
git fetch origin pull/<Pull Request ID>/head:mybranch
git checkout <commit id>

So, if I see that Pull Request #199 solves my problem and that the latest commit to that pull request is b6708df713 I can use the following (assuming I already have the project cloned to projdir).

1
2
3
4
5
cd projdir
git fetch origin pull/199/head:trial
git checkout b6708df713
  OR
git checkout trial

Discussion

The fetch on line 2 gathers the whole pull request (#199) into your local git repository (placing it on a new branch trial).

Once your local repository has a copy of the pull request you can checkout the specific commit you are interested in to your workspace (line 3), or if you just want the latest commit you can checkout the branch (line 5, which implicitly check out the HEAD of the branch). No need to specify the branch as that is implicit in the checkout.

Placing the pull request on a temporary branch in you local repository keeps things tidy and ensures these changes will not conflict with the master once it is updated by the project (after which you can throw away your temporary branch).

Once the pull request is merged with the master in the GitHub project we simply checkout master and can now safely remove the temporary trial branch.

1
2
git checkout origin master
git branch -D trial

Note, the use of -D to ‘force’ the deletion as we have not merged the trial branch (hence, using only -d will not delete the branch but results in a warning).