Working with Git Worktrees

Chris Di Carlo • February 16, 2022

While listening to a recent episode of the excellent North Meets South podcast, a random comment sparked a curiosity in me - specifically about Git worktrees.

I had heard of this complex, arcane, guru-level feature of Git before in passing but never really looked further into how it works and how it could be of benefit to my workflow. After using it for a while, the reality is very different. It's actually quite simple to grok.

A codebase I'm working in right now requires a lot of context switching between branches while working on various features and/or bugfixes. My workflow up until now has been to either commit the sometimes incomplete work and checkout the other branch or to stash the changes. That leads to a tedious workflow:

stash -> checkout -> <code, code, code!> -> commit -> checkout -> stash pop.

Ugh. After doing this for a couple of months, the podcast comment spurred me to look deeper into worktrees. And - OMG - what a difference it makes.

Basically, a Git worktree works the same as a normal working directory; the difference is that you can have multiple working directories inside your project folder, each with their own dependencies, etc. Each worktree is placed into it's own self-contained subfolder.

The difference this has made to my workflow is mindblowing. I can point Valet at each working tree subfolder and have multiple versions of the app available at the same time on their own subdomain. No more wondering which version I'm looking at in the browser. No more blowing away my vendor directory because of some weird dependency breakage. No more wondering why something is broken with the database only to realize that the migrations on this branch were not run yet.

Now when I need to work on a branch, I create a worktree and give it it's own database, as well. The entire app is isolated.

The only thing that was a bit of a pain was switching between working trees in VS Code, so I built a quick extension that lets me do it on the fly Switch Git Worktree. Switching between worktrees is now as easy as CTRL+SHIFT+P and selecting the right one.

I've written some scripts to speed up the scaffolding of the environment for each worktree; I'll maybe follow up with another post with how I sped up that process quite a bit, too.

Happy coding! Cheers