How to git checkout a remote branch

If you’re the maintainer of an open source project receiving PRs and such, you may want to be able able to check out the exact branch of the PR, and then do your rebasing or modifications that you’ll push back to the PR or whatever.

Here’s how you do that.

In general

git remote add REMOTE_NAME ssh://git@github.com/REMOTE_NAME/THEIR_REPO.git
git fetch REMOTE_NAME
git checkout -b OUR_BRANCH REMOTE_NAME/THEIR_BRANCH

And when you’re ready to push fixups back to the remote:

git push -f -u REMOTE_NAME OUR_BRANCH:THEIR_BRANCH

Specific example

Obviously you’re not the maintainer of node but, if you were, you might do something like this to check out and pull in someone’s PR:

# This is the fork
git remote add therootcompany ssh://git@github.com/therootcompany/node.git
git fetch therootcompany

# This is the EXACT version of the fork, locally (not merged)
git checkout -b add-feature-x upstream/patch-1
# Pushing fixups / rebase to PR
git push -f -u therootcompany add-feature-x:patch-1

As as script

See gh-review. Essentially it does this:

git remote add "${pr_remote}" "ssh://git@github.com/${pr_remote}/${their_repo}.git"
git fetch "${pr_remote}"
git checkout --branch "${our_branch}" "${pr_remote}/${pr_branch}"
git push --force --set-origin "${pr_remote}" "${our_branch}:${pr_branch}"

Reference Material

See also https://therootcompany.com/blog/how-i-rebase-prs/.