Testing Pull Requests Locally with Git Worktrees

Testing Pull Requests Locally with Git Worktrees

Introduction

When reviewing pull requests (PRs), it’s often necessary to run the code locally before approving changes. Instead of old-school branch switching, Git worktrees let you check out a PR into its own directory without touching your current working branch. This, in theory, makes testing PRs a whole lot easier, with the added benefit of a clean main workspace.

Benefits:

  • No branch juggling – Avoid git stash / branch-switching headaches.
  • Lightweight – Multiple working directories share the same Git history.
  • Great for PR reviews – Spin up isolated environments for each PR.

Setup

Using git worktrees can seem intimidating at first, but once you get the hang of it, you’ll appreciate its benefits. That said, I’ve created a one-time setup guide that you can reuse for your projects for those who want to dive right in. We’ll use aliases to simplify the setup and make it user-friendly.

Run this in your terminal:

git config --global alias.pr '!f() { \
  num=$1; \
  branch="pr-$num"; \
  dir="../pr-$num"; \
  git fetch upstream pull/$num/head:$branch && \
  git worktree add $dir $branch && \
  echo "✅ Worktree for PR #$num created at $dir"; \
}; f'

🔹 Usage

Whenever you want to review PR #69:

git pr 69

This command will:

  1. Fetch the PR branch from upstream.
git fetch upstream pull/69/head:pr-69
  1. Create a new worktree at ../pr-69.
git worktree add ../pr-69 pr-69
  1. Print a confirmation message.

Then you can:

cd ../pr-69

…and test/run/review the code safely in isolation.


🔹 Cleanup After Review

When you’re done with the PR:

cd ..
git worktree remove ../pr-69
git branch -D pr-69   # removes the temporary branch



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Honeypots, A Lightweight Bot Defense Strategy
  • How to set up live reloading Golang
  • Running LLMs Locally with Open Web UI and Ollama
  • Google Kubernetes Engine
  • Intro to GCP Cloud Shell and gcloud