// HACKER NEWS — CYBERSECURITY
Parallel development without the headaches using Git worktree
Recently whilst tinkering with a particularly tricky project, I came across Git’s worktree feature. A tool that lets you work on multiple branches simultaneously, each in its own directory, all sharing the same underlying repository history.
All the directories above share the same commit history and are linked to the same .git object database even though each has its own working directory state.
Each directory behaves like a normal checkout, you edit files, commit and push as usual, but you avoid constantly hopping branches in a single working tree.
Traditionally, working on multiple branches meant a lot of git checkout and git stash constantly saving your place, switching context and hoping you didn’t lose anything important. It’s easy to get lost, especially when a production bug interrupts your flow. With git worktree you can add a new working directory for any branch (existing or new) and keep your workstreams separate. For example;
This creates new directories at the same level as your main project, checked out to the branches you specify. You can now edit files, commit and push in each directory independently without touching your main working directory.
One important limitation is that the same branch cannot be checked out in more than one worktree at the same time. Each worktree must have a unique branch checked out. In practice, that encourages a tidy mapping of “one task, one branch, one directory”, which makes it easier to stay oriented mentally.
Here’s a realistic scenario, you’re working on a checkout feature when a production bug appears.
You can easily develop the checkout feature in shop-checkout while keeping shop on main for quick reviews.
Merging changes from a worktree branch is just like any other Git merge, but the context is clearer because each branch lives in its own directory. Here’s a typical workflow for merging the feature branch into main;
Because each worktree is dedicated to a single branch, it’s much harder to accidentally commit to the wrong branch or lose your place when a hotfix interrupts your feature work… anyway, that’s the theory. 😉