Git Worktree Overview
Git worktree enables managing multiple working trees attached to the same repository, allowing paralel development across different branches with isolated environments.
Common Use Cases
- Isolating divergent branch dependencies: When branches evolve into separate projects with different dependency requirements, worktrees prevent the need for repeated dependency reinstalls during branch switching
- Parallel development: Work simultaneously on multiple features or bug fixes without constant branch switching
- Experimental changes: Test new appproaches without affecting the main working directory
- Concurrent long-term and short-term tasks: Maintain separation between ongoing development work and immediate fixes
Core Commands
add: Create a new working treeremove: Delete an existing working treelist: Display all active working treeslock: Protect a worktree from accidental deletion during operationsunlock: Remove protection from a locked worktree
Creating Worktrees
# Create worktree at ../feature-branch based on current HEAD
# Equivalent to: git worktree add ../feature-branch -b feature-branch
git worktree add ../feature-branch
# Associate worktree with existing branch 'development'
git worktree add ../dev-space development
# Create worktree with new branch 'experimental'
git worktree add ../test-area -b experimental
Removing Worktrees
# Proper removal method
git worktree remove <worktree-path>
# Alternative: delete directory manually then cleanup
git worktree prune
Listing Worktrees
# Show all worktrees
git worktree list
# Display with full commit hashes
git worktree list --porcelain
Locking Mechanism
# Protect worktree from accidental deletion
git worktree lock <worktree-path>
# Remove protection
git worktree unlock <worktree-path>
Resolving Branch Dependency Conflicts
Scenario
A repository contains two branches (vue and react) that have evolved into separate projects with different dependency requirements.
Implementation Steps
- Reorganize the project structure by moving original content to
project-root/main-project - From
project-root/main-project, execute:git worktree add ../vue-branch vue - From the same directory, execute:
git worktree add ../react-branch react
This creates three isolated working directories:
main-project(original branch)vue-branch(vue framework branch)react-branch(react framework branch)
Each worktree maintains independent dependency environments while allowing standard Git operations including commits, merges, and cherry-picking between branches. Branch switching occurs by navigating to the appropriate working directory rather than using git checkout.