Git worktrees are a special feature of git that lets you checkout branches/commits into a folder.
You can check each branch out into a separate folder. This means no more stashing/un-stashing or committing just to work on several branches at once.
I start by creating a new shiny empty folder to hold my project
mkdir my-project
Then I clone down my respository inside that folder into a folder named "main"
cd my-project
git clone git@github.com/username/somerepo.git main
Then go into that folder.
This is a normal repo, we just named it main
Now here's where the magic happens. Say we have a branch named "dev"
git worktree add ../dev dev
This makes a folder up one level from main, containing the checked out copy of the dev
branch, and puts it into a folder called dev
You can go into that folder and work as if it's the main repo. The actual .git
folder for the repo lives in the main folder, but you can work out of these other folders. These folders are called worktrees
You can list all your worktrees with
git worktree list
And you can remove a worktree when you want to stop working on a branch with
git worktree remove dev
Git is smart here, and won't let you remove a worktree that has uncommitted changes in it.
Here's how I do it.
git branch new-branch
git worktree add ../new-branch new-branch
I don't use the git checkout -b
command anymore, in fact, I never use git checkout
or git stash
anymore.
I like to make a .workspace file for VSCode and keep that in my project directory, then I add each branch folder to the workspace. This keeps lots of dev tools and extensions in VSCode happy and the git tools in VSCode will even show you all your branches in the sidebar.