Git worktree = ter várias pastas de trabalho para o MESMO repo.
Conceito:
Analogia: é como ter vários escritórios para o mesmo projeto.
Problema clássico:
# Trabalha em feature-A
git checkout feature-A
# Código, código, código... (trabalho por acabar)
# URGÊNCIA: bug em main!
git stash # Salvaguardar work in progress
git checkout main # Mudar para main
# Corrigir o bug...
git checkout feature-A # Voltar ao seu trabalho
git stash pop # Recuperar o work in progressSolução worktree:
# Trabalha em feature-A na pasta principal
# Urgência? Criar uma nova pasta para main!
git worktree add ../hotfix main
# Agora:
# - ./ → feature-A (o seu trabalho continua)
# - ../hotfix → main (para a correção urgente)Vantagem: sem stash/switch. Só 2 pastas, 2 tarefas em paralelo!
mkdir demo-worktree && cd demo-worktree
git init
echo "print('main v1')" > app.py
git add . && git commit -m "Main version"
# Criar branch feature
git checkout -b feature-new
echo "print('feature work')" > feature.py
git add . && git commit -m "Feature work"
git checkout main# Criar worktree para feature-new
git worktree add ../feature-work feature-new
# Criar worktree para uma nova branch
git worktree add ../hotfix-branch -b hotfix
# Ver todos os worktrees
git worktree listdemo-worktree/ → main branch
../feature-work/ → feature-new branch
../hotfix-branch/ → hotfix branch (nova)# Terminal 1: pasta principal (main)
cd demo-worktree
echo "print('main updated')" >> app.py
git add . && git commit -m "Update main"
# Terminal 2: Feature work
cd ../feature-work
echo "print('feature complete')" >> feature.py
git add . && git commit -m "Complete feature"
# Terminal 3: Hotfix
cd ../hotfix-branch
echo "print('urgent fix')" > fix.py
git add . && git commit -m "Critical fix"Magia: 3 branches, 3 pastas, 0 mudança de contexto!
| Comando | Ação |
|---|---|
git worktree add <path> <branch> | Criar worktree numa branch existente |
git worktree add <path> -b <new-branch> | Criar worktree + nova branch |
git worktree list | Ver todos os worktrees |
git worktree remove <path> | Apagar worktree |
git worktree prune | Limpar worktrees apagados |
1. Hotfix urgente:
git worktree add ../hotfix main
cd ../hotfix && echo "fix" > fix.py
git add . && git commit -m "Hotfix"
git push origin main2. Review de PR:
git worktree add ../pr-review pr-branch
cd ../pr-review # Testar a PR sem perturbar o seu trabalho3. Comparação de branches:
git worktree add ../version-a branch-a
git worktree add ../version-b branch-b
# Compare ficheiros entre ../version-a e ../version-bgit worktree remove ../feature-work
git worktree remove ../hotfix-branch
git worktree prune # Limpar as referênciasWorktree = multitarefa Git sem compromissos!