Video in progress
You need to verify a hotfix for prod, but you have a half-finished feature. How does `git worktree` help here?
git worktree opens several working folders from one repo, each with a different branch. You make the hotfix in a separate folder, without stashing and without re-indexing the IDE.
📖 Answer
git worktree add ../shop-hotfix -b hotfix/2.3.1 v2.3.0
cd ../shop-hotfix
./mvnw test
# ... fix, commit, push
cd ../shop
git worktree remove ../shop-hotfix
Both folders use the same .git object database, so it is much faster than cloning again and saves disk space too. You cannot check out one branch in two worktrees at once: Git does not allow it, which prevents confusion.
Where it comes in handy in practice:
- a long build or integration test runs in one folder while you work in another;
- PR review: you open a colleague's branch in a separate folder and run it in the IDE;
- comparing the behavior of the old and new versions side by side.
A small trap: the Maven/Gradle caches are shared, but target/ and build/ are separate in each worktree, so the first build is slower. If you delete a folder by hand, git worktree prune cleans up the leftover entries.
Sign up to mark studied questions and save your progress.