using-git-worktrees

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Using Git Worktrees

使用Git Worktrees

Overview

概述

Create isolated working directories for parallel development tasks using
git worktree
, allowing multiple branches to be checked out simultaneously without conflicts. This skill enforces a deterministic, multi-phase process from directory selection through setup verification, ensuring every worktree is production-ready before any work begins.
通过
git worktree
为并行开发任务创建隔离的工作目录,支持同时检出多个分支且无冲突。本技能遵循确定性的多阶段流程,从目录选择到设置校验全链路覆盖,确保所有worktree在开始工作前均达到生产可用标准。

When to Use

适用场景

  • Starting a new feature branch that should not interfere with current work
  • Working on multiple tasks simultaneously (bug fix + feature)
  • Creating a clean environment for testing or code review
  • Running long processes (tests, builds) while continuing development
  • 开启不会影响当前工作的新功能分支
  • 同时处理多项任务(比如修复Bug+开发新功能)
  • 为测试或代码评审创建干净环境
  • 运行长时间流程(测试、构建)的同时继续开发工作

Phase 1: Select Worktree Directory

阶段1:选择Worktree目录

[HARD-GATE] Do NOT skip directory selection. Do NOT assume a default path without checking priorities.
Follow this priority order exactly:
[强制门槛] 不得跳过目录选择步骤,未确认优先级前不得假设默认路径。
严格遵循以下优先级顺序:

Priority 1: Existing Worktree Matching Task

优先级1:匹配当前任务的已有Worktree

Check if a worktree already exists for the task:
bash
git worktree list
If a matching worktree exists, use it. Do NOT create a duplicate.
检查当前任务是否已存在对应worktree:
bash
git worktree list
如果存在匹配的worktree,直接复用即可,不得创建重复实例。

Priority 2: CLAUDE.md Worktree Directory Hint

优先级2:CLAUDE.md中的Worktree目录配置提示

Check the project's CLAUDE.md for a configured worktree directory:
undefined
检查项目CLAUDE.md文件中是否配置了worktree存储目录:
undefined

Example CLAUDE.md entry

CLAUDE.md配置示例

worktree-directory: ../worktrees

If specified, create worktrees under that directory.
worktree-directory: ../worktrees

如果有指定配置,在该目录下创建worktree。

Priority 3: Ask the User

优先级3:询问用户

If no hint is configured and no convention is obvious, ask the user where worktrees should be created. Suggest a sensible default:
../worktrees/<project-name>/<branch-name>
STOP — Confirm the worktree directory with the user before proceeding.
如果没有配置提示且没有明确的使用惯例,询问用户希望将worktree创建在哪个位置,可提供合理的默认路径建议:
../worktrees/<项目名称>/<分支名称>
暂停 — 继续操作前需先和用户确认worktree存储目录。

Directory Selection Decision Table

目录选择决策表

ConditionAction
Worktree for this branch already existsNavigate to existing worktree
CLAUDE.md has
worktree-directory
Use configured path
Project has existing worktreesUse same parent directory pattern
No convention foundAsk user, suggest
../worktrees/<project>/<branch>
User specifies path inside repo rootWarn — must add to
.gitignore
条件操作
目标分支对应的worktree已存在直接进入已有worktree
CLAUDE.md中配置了
worktree-directory
使用配置的路径
项目已有现存的worktree沿用相同的父目录规则
未找到使用惯例询问用户,建议路径为
../worktrees/<项目名>/<分支名>
用户指定的路径在仓库根目录内发出警告 — 必须将该路径添加到
.gitignore

Phase 2: Safety Verification

阶段2:安全校验

[HARD-GATE] Do NOT create any worktree until all safety checks pass.
[强制门槛] 所有安全检查通过前,不得创建任何worktree。

Check .gitignore Coverage

校验.gitignore覆盖情况

If the worktree directory is inside the repository root, ensure it is in
.gitignore
:
bash
undefined
如果worktree目录在仓库根目录内,确保该路径已被加入
.gitignore
bash
undefined

Check if the worktree path would be tracked

检查worktree路径是否会被Git追踪

git check-ignore <worktree-path>

If not ignored, warn the user and suggest adding it to `.gitignore`.
git check-ignore <worktree-path>

如果未被忽略,向用户发出警告并建议将其添加到`.gitignore`中。

Verify Clean Working Tree

校验工作树状态干净

Check for uncommitted changes that could cause issues:
bash
git status --porcelain
If the working tree is dirty, inform the user and ask how to proceed:
  • Commit changes first
  • Stash changes
  • Proceed anyway (worktree creation itself is safe)
检查是否存在可能引发问题的未提交变更:
bash
git status --porcelain
如果工作树状态为脏,告知用户并询问后续处理方式:
  • 先提交变更
  • 暂存变更
  • 继续操作(worktree创建本身是安全的)

Verify Branch Does Not Exist in Another Worktree

校验分支未在其他Worktree中检出

bash
git worktree list
A branch cannot be checked out in two worktrees simultaneously. If the branch is already checked out, navigate to that existing worktree instead.
bash
git worktree list
同一个分支不能同时在两个worktree中检出,如果分支已经被其他worktree检出,直接进入该已有worktree即可。

Safety Check Decision Table

安全检查决策表

CheckResultAction
Path inside repo, not in
.gitignore
FAILAdd to
.gitignore
first
Branch already in another worktreeFAILUse existing worktree
Working tree dirtyWARNInform user, ask preference
Path already exists (not worktree)FAILChoose different path
All checks passPASSProceed to Phase 3
检查项结果操作
路径在仓库内,且未加入
.gitignore
不通过先将路径添加到
.gitignore
分支已在其他worktree中检出不通过使用已有worktree
工作树状态为脏警告告知用户,询问处理偏好
路径已存在(非worktree)不通过选择其他路径
所有检查通过通过进入阶段3

Phase 3: Create the Worktree

阶段3:创建Worktree

bash
undefined
bash
undefined

For a new branch

用于创建新分支的场景

git worktree add <path> -b <branch-name> <base-branch>
git worktree add <path> -b <branch-name> <base-branch>

For an existing branch

用于已有分支的场景

git worktree add <path> <existing-branch>

Always tell the user the full path where the worktree was created:
Worktree created at: /absolute/path/to/worktree Branch: feature/my-feature Base: main

**STOP — Confirm the worktree was created successfully before proceeding to setup.**
git worktree add <path> <existing-branch>

必须告知用户worktree创建的完整路径:
Worktree创建路径:/absolute/path/to/worktree 分支:feature/my-feature 基分支:main

**暂停 — 继续后续设置前需先确认worktree创建成功。**

Phase 4: Project Setup and Auto-Detection

阶段4:项目设置与自动检测

After creating the worktree, detect and run the project's setup commands.
创建worktree后,检测并运行项目的初始化设置命令。

Setup Detection Decision Table

初始化检测决策表

Indicator FileEcosystemSetup Command
pnpm-lock.yaml
Node.js (pnpm)
pnpm install
yarn.lock
Node.js (yarn)
yarn install
package-lock.json
Node.js (npm)
npm install
package.json
(no lock)
Node.js (npm)
npm install
pyproject.toml
+
tool.poetry
Python (poetry)
poetry install
pyproject.toml
(no poetry)
Python (pip)
pip install -e .
setup.py
Python (pip)
pip install -e .
requirements.txt
Python (pip)
pip install -r requirements.txt
go.mod
Go
go mod download
Cargo.toml
Rust
cargo build
Gemfile
Ruby
bundle install
composer.json
PHP
composer install
标识文件技术栈初始化命令
pnpm-lock.yaml
Node.js (pnpm)
pnpm install
yarn.lock
Node.js (yarn)
yarn install
package-lock.json
Node.js (npm)
npm install
package.json
(无锁文件)
Node.js (npm)
npm install
pyproject.toml
+
tool.poetry
Python (poetry)
poetry install
pyproject.toml
(无poetry配置)
Python (pip)
pip install -e .
setup.py
Python (pip)
pip install -e .
requirements.txt
Python (pip)
pip install -r requirements.txt
go.mod
Go
go mod download
Cargo.toml
Rust
cargo build
Gemfile
Ruby
bundle install
composer.json
PHP
composer install

Multiple Ecosystems

多技术栈场景

If the project uses multiple ecosystems (e.g., a Go backend with a Node.js frontend), run setup for each detected ecosystem in the appropriate subdirectories.
如果项目使用多技术栈(比如Go后端搭配Node.js前端),在对应的子目录下为每个检测到的技术栈分别运行初始化命令。

Environment Files

环境变量文件

If the project has
.env.example
or
.env.template
:
bash
undefined
如果项目存在
.env.example
.env.template
bash
undefined

Copy environment template if .env does not exist in worktree

如果worktree中不存在.env文件,复制环境变量模板

cp .env.example .env # then inform user to update values
undefined
cp .env.example .env # 之后告知用户更新配置值
undefined

Phase 5: Clean Baseline Test Verification

阶段5:干净基准测试校验

[HARD-GATE] Do NOT proceed with any work until baseline tests pass or failures are acknowledged.
Run the project's test suite to establish a clean baseline BEFORE starting any work:
bash
undefined
[强制门槛] 基准测试通过或失败原因确认前,不得开展任何开发工作。
开始工作前先运行项目测试套件,确认基准环境正常:
bash
undefined

Use the project's test command

使用项目对应的测试命令

Node.js: npm test / yarn test / pnpm test

Node.js: npm test / yarn test / pnpm test

Python: pytest / python -m pytest

Python: pytest / python -m pytest

Go: go test ./...

Go: go test ./...

Rust: cargo test

Rust: cargo test


Purpose:
- Confirms the worktree is set up correctly
- Establishes that all tests pass before changes are made
- Any test failures after this point are caused by your changes, not pre-existing issues

If baseline tests fail:
- Report the failures to the user
- Do NOT proceed with work until the baseline is understood
- The base branch may have broken tests that need addressing first

目的:
- 确认worktree配置正确
- 确认修改前所有测试均能通过
- 后续出现的测试失败均由你的修改导致,而非预存问题

如果基准测试失败:
- 向用户上报失败情况
- 基准问题确认前不得继续开发
- 可能是基分支本身存在损坏的测试,需要先修复

Phase 6: Location Reporting

阶段6:位置上报

Always report the worktree location clearly to the user:
Worktree ready:
  Path:    /Users/dev/worktrees/myproject/feature-auth
  Branch:  feature/auth-refactor
  Base:    main
  Setup:   npm install (completed)
  Tests:   24 passed, 0 failed
必须清晰向用户告知worktree的位置信息:
Worktree已就绪:
  路径:    /Users/dev/worktrees/myproject/feature-auth
  分支:  feature/auth-refactor
  基分支:    main
  初始化:   npm install (已完成)
  测试:   24 passed, 0 failed

Cleanup Patterns

清理规则

After Merging or Completing Work

合并或完成工作后

bash
undefined
bash
undefined

Remove the worktree

移除worktree

git worktree remove <path>
git worktree remove <path>

If files remain (dirty worktree), force removal

如果有残留文件(脏worktree),强制移除

git worktree remove --force <path>
git worktree remove --force <path>

Prune stale worktree references

清理失效的worktree引用

git worktree prune
undefined
git worktree prune
undefined

List All Worktrees

列出所有Worktree

bash
git worktree list
bash
git worktree list

Handling Locked Worktrees

处理被锁定的Worktree

If a worktree is locked (to prevent accidental removal):
bash
undefined
如果worktree被锁定(防止误删):
bash
undefined

Unlock before removing

移除前先解锁

git worktree unlock <path> git worktree remove <path>
undefined
git worktree unlock <path> git worktree remove <path>
undefined

Anti-Patterns / Common Mistakes

反模式/常见错误

Anti-PatternWhy It Is WrongWhat to Do Instead
Creating duplicate worktree for same branchGit does not allow it; wastes timeCheck
git worktree list
first
Worktree inside repo without
.gitignore
Worktree files show as untrackedAdd path to
.gitignore
Skipping dependency install in worktreeBuild/test failures from missing depsAlways run project setup
Skipping baseline test runCannot distinguish pre-existing vs new failuresRun tests before starting work
Assuming worktree has same env vars
.env
files are not shared between worktrees
Copy and configure
.env
Leaving stale worktrees after mergeDisk waste, confusing
git worktree list
Remove worktrees after branch completion
Force-removing worktree with uncommitted workPermanent data lossCommit or stash first
反模式错误原因正确做法
为同一个分支创建重复的worktreeGit不支持该操作,浪费时间先执行
git worktree list
检查
Worktree在仓库内但未加入
.gitignore
Worktree文件会被识别为未追踪文件将路径添加到
.gitignore
跳过worktree的依赖安装步骤缺少依赖会引发构建/测试失败始终运行项目初始化命令
跳过基准测试运行无法区分是预存问题还是新修改导致的失败开始工作前先运行测试
假设worktree共享相同的环境变量
.env
文件不会在worktree之间共享
复制并配置
.env
文件
合并后残留过时的worktree浪费磁盘空间,
git worktree list
输出混乱
分支处理完成后移除对应worktree
强制移除存在未提交工作的worktree永久丢失数据先提交或暂存修改

Integration Points

集成点

SkillIntegration
finishing-a-development-branch
After completing work in a worktree, use this to merge or create a PR
dispatching-parallel-agents
Run agents in separate worktrees for true isolation
verification-before-completion
Validate work before leaving the worktree
self-learning
Check CLAUDE.md for worktree directory preferences
planning
Worktree creation is often the first step of plan execution
技能集成逻辑
finishing-a-development-branch
完成worktree内的工作后,使用该技能合并代码或创建PR
dispatching-parallel-agents
在独立的worktree中运行Agent实现真正的隔离
verification-before-completion
退出worktree前校验工作成果
self-learning
检查CLAUDE.md获取worktree目录偏好配置
planning
创建worktree通常是计划执行的第一步

Skill Type

技能类型

RIGID — Follow this process exactly. Every phase must be completed in order. Do NOT skip safety checks. Do NOT skip baseline test verification. Do NOT create worktrees without confirming the directory.
严格执行型 — 必须严格遵循本流程,所有阶段必须按顺序完成。不得跳过安全检查,不得跳过基准测试校验,未确认目录前不得创建worktree。