Using Git worktrees is an excellent way to review or test a Pull Request (PR) in a completely separate directory without messing up your current working branch or stash.
Here is a systematic procedure to fetch a remote PR, check it out into a dedicated worktree, and keep it updated.
Using Git Worktree ensures you have everything under one roof. However, this is not a hard requirement. If you prefer just a regular repo directory, this is also possible.
-
Create the root directory
Create and enter the top-level directory that will house your setup:
mkdir project cd project -
Clone the remote as a bare repository
Clone your repository using the
--bareflag into a hidden folder. A bare repository contains only the Git tracking database without an active working directory:git clone --bare git@github.com:username/repo.git .bare
-
Establish the Git storage link
Create a special .git file at the root level that explicitly points future worktrees to your hidden bare directory:
echo "gitdir: .bare" > .git
-
Configure GitHub PR tracking
Inject the automated mapping configuration into your bare Git config file so that GitHub PR references are fetched natively as local remote-tracking branches. Then, perform your initial synchronization:
git config --file .bare/config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*" git fetch origin -
Initialize the main branch worktree
Create your primary working environment (
main/) as your first official worktree tracking your default branch:git worktree add main main
Verify the file layout:
project/
├── .git # Core configuration link
├── .bare/ # Hidden Git database tracking objects
└── main/ # Your primary working branch directory
From the root project/ directory, create a dedicated folder to safely review a specific pull request without altering your main codebase:
git worktree add pr-42 -b pr-42 origin/pr/42- What this does: It creates a new local branch (
pr-42)that explicitly tracksorigin/pr/42and checks it out into your new worktree directory.
If you get a error message that the branch exists already, try this command:
git worktree add pr-42 pr-42If the PR author pushes new commits to their pull request, you will need to pull those updates into your worktree.
-
Navigate into your worktree directory.
-
Pull the changes:
git pull
Because the PR reference on GitHub can be force-pushed or rebased by the author, if a standard git pull fails due to a non-fast-forward update, you can safely run:
git fetch origin && git reset --hard origin/pr/PR_NUMBERBe aware
git reset --hardwill immediately discard any uncommitted edits or experimental tweaks you made inside that specific worktree directory.
When your testing or review concludes, return to your root repository structure to safely dismantle the environment and keep your disk space clean:
cd /path/to/project
git worktree remove pr-42
git branch -D pr-42