Git Worktree Workflow
Yesterday was one of those days where I was working on one branch as my main work, but I kept getting pulled off to work on some bug fixes on another branch. I have a system for that.
git stash -m "wip: the stuff I'm working on"
git checkout bug-fix-branch
# make changes
git commit
git push
git checkout original-branch
git stash apply
It works and is fine, but git worktree is an alternative where I wouldn’t have to stash those changes every time I need to jump on a bug fix. It is like having another branch open at the same time and feels pretty smooth.
Sadly, I can’t really use it in my day to day work for reasons I’ll explain below. But I want to keep notes on how to use it for when I can.
Worktree workflow
- Create new worktree
- Go to worktree path
- Install node modules:
npm install(skip this step if you aren’t working in a project that needs it) - Making changes
- Commit and push changes
- Delete worktree directory
- Navigate to another worktree
- Prune deleted worktree
View all worktrees
This shows a list of all active worktrees and the directories they live in. It also shows prunable worktrees, which are worktrees whose directory has been deleted.
git worktree list
Create new worktree for existing branch
The worktree lives in a different folder, hence adding the path. To work on the branch in that worktree, you will need to go to that path cd ../path
git worktree add ../path branch-name
Create new worktree for new branch
git worktree add ../path -b branch-name
Go to new worktree
cd ../path
Install node modules
The new path doesn’t have node_modules, so you need to install.
npm install
Delete worktree directory
# from your new worktree
cd ..
rm -rf path
Prune worktree
cd other-worktree-directory
git worktree prune
The bad news for me
My day to day work largely happens in dev containers in VS Code. Although there is a way to update the dev container to handle specific worktrees, it isn’t flexible enough to just add them at will and have it work. So I don’t get to use this like I wish I could. Moreover, I can’t just go updating our devcontainer code to fit my personal preferences because other people on my team use them. I basically have the same problem as this person.
So for now I’ll just have to keep this in my mental filing cabinet for a time when it becomes more relevant.
Published Feb 28, 2025