Git worktrees are great for code reviews
At first, I didn’t understand how to use git worktrees, but now I find myself using it more and more for code reviews.
Here’s what my workflow looks like when I have to review some code:
cd
into a previously created worktree withcd ../code-review
or create a new one withgit worktree add ../code-review
.- Run
git fetch
. - Check out the branch to review with
git checkout <branch>
. - Install dependencies with
npm install
- Run the app with
npm run start
to help me review the code.
When I’m done reviewing, I can just cd
into the folder I was previously
working on.
This saves me from polluting my git stash
or messing up my node_modules
and
.env
(in case I needed to modify them to run the reviewee’s code).
What is a worktree?
A worktree enables you to check out more than one branch at a time per repository.
Each worktree has its own working tree, meaning you can have completely
different files and directories per worktree — untracked files like .env
and
node_modules
may be different.
In practice, a worktree is just like another directory. After you create it
with git worktree add
, you can cd
into it and start working.
We could check out more than one branch by cloning the repository in a different folder, but that’s slower — creating worktrees is instant — and inconvenient — in a worktree you have access to your local branches and stash, no need to push to a remote repository first.
Creating a worktree
The command to add worktree is git worktree add
.
$ git worktree add ../code-review
Actually, this will create a new branch called code-review
and automatically
switch to it.
(master) $ git worktree add ../code-review(master) $ cd ../code-review(code-review) $
You can choose to check out an existing branch instead by passing its name as the second argument:
(master) $ git worktree add ../bugfix JIRA-311(master) $ cd ../bugfix(JIRA-311) $
As I said, I don’t typically create a lot of worktrees, I just have one sitting there, and reuse it whenever I have to do some code review.
Independent working trees
Independent working trees per worktree is a big part of why it’s useful for code reviews.
But even on solo projects, like my blog, this can come in handy — e.g. when
migrating a test suite from Cypress to Playwright, a different worktree would
save me the trouble of having to run npm install
to install correct
dependencies every time I switched branches.
By doing the migration to Playwright in a worktree, my work on that branch wouldn’t interfere with the main worktree with the Cypress-based test suite.
Removing worktrees
To remove a worktree:
$ git worktree remove code-review
This will only succeed if the worktree is clean — which means “no untracked files and no modification in tracked files”.