16th March 2023

Checkout a branch from a fork

Situation

I need to get started on a ticket which needs some of the changes implemented by a colleague whose PR is still in review. So, the best way to continue from their work, would be to branch off their branch. Easy Right? Yes...until you find out that they submitted a PR from a fork 🫀.

Solution

When someone submits a PR a Git reference for it is created to store a reference to the commits in that PR. By running:

git ls-remote --refs origin

You will be able to see all the refs on the origin remote. The reference of the head of a branch for a pr would be in the format refs/pull/456/head. This is the reference for PR`#456. After knowing the PR ref we can fetch it locally and check out the branch using the following command.

git fetch origin pull/456/head:pr-456 && git checkout pr-456

You will now find yourself on branch pr-456containing code from PR #456.