Git worktrees give one repository several working folders, each with its own branch checked out. Instead of switching one folder back and forth between branches, you keep main in one folder and your feature in another, and work on both at once.
The cost of switching branches
A normal clone has one working folder, so it can only have one branch checked out at a time. Say you are halfway through a feature-login branch when a bug turns up on main. With one folder, the routine goes:
- Commit or stash your half-finished work.
git switch main, which rewrites files all over the folder.- Fix the bug, commit and push.
- Switch back to
feature-login. - Restore your stash and try to remember where you were.
Each switch changes files under your editor, so dev servers restart, builds rerun and caches go stale. If the branches have different dependencies, you may need to reinstall them too. Worst of all, it is easy to lose track of which branch you are on and commit to the wrong one.
What a worktree is
A worktree is a working folder: the files you edit, with one branch checked out. Every repository starts with one, the main worktree, which is the folder you cloned into. git worktree add creates linked worktrees: more folders, each with its own branch, all connected to the same repository.
Wondering how this was made? How we make these