I've always wondered whether it was possible to simultaneously check out multiple branches of the same project on a single device. It can be quite useful for code review, code comparison or working on a hotfix. The answer? Git Worktrees.
TL;DR
Creating multiple worktrees is similar to executing git clone
multiple times for the same Git repository. In both cases, a folder is created for every worktree/clone. The difference is worktrees are interlinked, i.e. we can manage a project's worktrees from any single one of them, e.g. list, add, delete.
A working tree or worktree is the set of files in a project directory. Each project directory gets 1 worktree that's associated to the currently checked out branch. Git supports multiple worktrees, which allows for additional project directories, each with a separate worktree, while sharing the same Git repository data.
Whenever a worktree is created, a new folder (or project directory) is also created.
Avoid nesting worktrees as they mess up the Git history.
Scenario #1
Create a worktree for an existing branch, e.g. develop
. A new folder, e.g. develop-worktree
, will be created at the same level as your project's root Git directory.
# Make sure to cd in the project's root Git directory
git worktree add ../develop-worktree develop
Open develop-worktree
in a new VSCode window. Feel free to use the code editor of your choice.
code ../develop-worktree
Once you're done with your changes, commit and push to remote. Now, the worktree can be deleted.
git worktree remove develop-worktree
Scenario #2
Create a worktree for a new branch, e.g. hotfix
. A new folder, e.g. hotfix-worktree
, will be created at the same level as your project's root Git directory.
# Make sure to cd in the project's root Git directory
git worktree add ../hotfix-worktree -b hotfix
Open hotfix-worktree
in a new VSCode window. Feel free to use the code editor of your choice.
code ../hotfix-worktree
Once you're done with your changes, commit and push to remote. Now, the worktree can be deleted.
git worktree remove hotfix-worktree
The new branch is not deleted along with the worktree.
We can list all worktrees to make sure the worktree has been removed.
git worktree list