关于 git-worktrees
面向需要同时检出多个分支的开发者的 Git worktree 实用指南,涵盖创建、维护、比较及并行任务工作流;多个目录共享同一仓库。
主要功能
- 01创建和管理关联 worktree
- 02列出、移动、锁定和移除 worktree
- 03清理过期元数据并修复链接
- 04比较文件并选择性转移更改
- 05并行开发与代码审查模式
适用场景
- 01开发功能时并行处理紧急修复
- 02在不影响当前目录的情况下审查 PR
- 03在隔离 worktree 中运行测试
- 04比较不同分支的实现
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ neolabhq/ context-engineering-kit --skill git-worktrees安装后在 Claude Code 中输入/git-worktrees确认已加载。
详细介绍
Git Worktrees
概述
Git worktrees 可在不同目录中同时检出多个分支,且这些目录共用同一个仓库。可以创建 worktree,而不必暂存更改或单独克隆仓库。
核心原则: 每个活动分支对应一个 worktree。通过切换目录而不是切换分支来切换工作上下文。
核心概念
| 概念 | 描述 |
|---|---|
| 主 worktree | 通过 git clone 或 git init 创建的原始工作目录 |
| 关联 worktree | 使用 git worktree add 创建的其他目录 |
共享的 .git | 所有 worktree 共用同一个 Git 对象数据库(不会重复存储) |
| 分支锁定 | 每个分支一次只能在一个 worktree 中检出 |
| Worktree 元数据 | .git/worktrees/ 中用于跟踪关联 worktree 的管理文件 |
快速参考
| 任务 | 命令 |
|---|---|
| 创建 worktree(现有分支) | git worktree add <path> <branch> |
| 创建 worktree(新分支) | git worktree add -b <branch> <path> |
| 创建 worktree(从引用创建新分支) | git worktree add -b <branch> <path> <start> |
| 创建分离头指针 worktree | git worktree add --detach <path> <commit> |
| 列出所有 worktree | git worktree list |
| 移除 worktree | git worktree remove <path> |
| 强制移除 worktree | git worktree remove --force <path> |
| 移动 worktree | git worktree move <old> <new> |
| 锁定 worktree | git worktree lock <path> |
| 解锁 worktree | git worktree unlock <path> |
| 清理过期 worktree | git worktree prune |
| 修复 worktree 链接 | git worktree repair |
| 比较不同 worktree 中的文件 | diff ../worktree-a/file ../worktree-b/file |
| 从其他分支获取一个文件 | git checkout <branch> -- <path> |
| 获取部分文件更改 | git checkout -p <branch> -- <path> |
| 挑选提交 | git cherry-pick <commit> |
| 挑选提交但不提交 | git cherry-pick --no-commit <commit> |
| 合并但不自动提交 | git merge --no-commit <branch> |
基本命令
创建 Worktree
# Create worktree with existing branch
git worktree add ../feature-x feature-x
# Create worktree with new branch from current HEAD
git worktree add -b new-feature ../new-feature
# Create worktree with new branch from specific commit
git worktree add -b hotfix-123 ../hotfix origin/main
# Create worktree tracking remote branch
git worktree add --track -b feature ../feature origin/feature
# Create worktree with detached HEAD (for experiments)
git worktree add --detach ../experiment HEAD~5
列出 Worktree
# Simple list
git worktree list
# Verbose output with additional details
git worktree list -v
# Machine-readable format (for scripting)
git worktree list --porcelain
输出示例:
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
移除 Worktree
# Remove worktree (working directory must be clean)
git worktree remove ../feature-x
# Force remove (discards uncommitted changes)
git worktree remove --force ../feature-x
移动 Worktree
# Relocate worktree to new path
git worktree move ../old-path ../new-path
锁定/解锁 Worktree
# Lock worktree (prevents pruning if on removable storage)
git worktree lock ../feature-x
git worktree lock --reason "On USB drive" ../feature-x
# Unlock worktree
git worktree unlock ../feature-x
清理过期 Worktree
# Remove stale worktree metadata (after manual directory deletion)
git worktree prune
# Dry-run to see what would be pruned
git worktree prune --dry-run
# Verbose output
git worktree prune -v
修复 Worktree
# Repair worktree links after moving directories manually
git worktree repair
# Repair specific worktree
git worktree repair ../feature-x
工作流模式
模式 1:并行处理功能开发和紧急修复
在进行功能开发时修复 Bug:
# Create worktree for hotfix from main
git worktree add -b hotfix-456 ../project-hotfix origin/main
# Switch to hotfix directory, fix, commit, push
cd ../project-hotfix
git add . && git commit -m "fix: resolve critical bug #456"
git push origin hotfix-456
# Return to feature work
cd ../project
# Clean up when done
git worktree remove ../project-hotfix
模式 2:工作期间审查 PR
在不影响当前工作的情况下审查 PR:
# Fetch PR branch and create worktree
git fetch origin pull/123/head:pr-123
git worktree add ../project-review pr-123
# Review: run tests, inspect code
cd ../project-review
# Return to work, then clean up
cd ../project
git worktree remove ../project-review
git branch -d pr-123
模式 3:比较实现
并排比较不同分支中的代码:
# Create worktrees for different versions
git worktree add ../project-v1 v1.0.0
git worktree add ../project-v2 v2.0.0
# Diff, compare, or run both simultaneously
diff ../project-v1/src/module.js ../project-v2/src/module.js
# Clean up
git worktree remove ../project-v1
git worktree remove ../project-v2
模式 4:长时间运行的任务
继续开发的同时,隔离运行测试/构建:
# Create worktree for CI-like testing
git worktree add ../project-test main
# Start long-running tests in background
cd ../project-test && npm test &
# Continue development in main worktree
cd ../project
模式 5:稳定的参考版本
保持干净的主检出目录以供参考:
# Create permanent worktree for main branch
git worktree add ../project-main main
# Lock to prevent accidental removal
git worktree lock --reason "Reference checkout" ../project-main
模式 6:从多个功能分支选择性合并
合并来自多个功能分支的特定更改:
# Create worktrees for each feature to review
git worktree add ../project-feature-1 feature-1
git worktree add ../project-feature-2 feature-2
# Review changes in each worktree
diff ../project/src/module.js ../project-feature-1/src/module.js
diff ../project/src/module.js ../project-feature-2/src/module.js
# From main worktree, selectively take changes
cd ../project
git checkout feature-1 -- src/moduleA.js src/utils.js
git checkout feature-2 -- src/moduleB.js
git commit -m "feat: combine selected changes from feature branches"
# Or cherry-pick specific commits
git cherry-pick abc1234 # from feature-1
git cherry-pick def5678 # from feature-2
# Clean up
git worktree remove ../project-feature-1
git worktree remove ../project-feature-2
比较并合并不同 Worktree 中的更改
由于所有 worktree 共用同一个 Git 仓库,你可以比较文件、挑选提交,并在 worktree 之间选择性地合并更改。
比较并审查文件更改
由于 worktree 只是目录,你可以直接比较文件:
# Compare specific file between worktrees
diff ../project-main/src/app.js ../project-feature/src/app.js
# Use git diff to compare branches (works from any worktree)
git diff main..feature-branch -- src/app.js
# Visual diff with your preferred tool
code --diff ../project-main/src/app.js ../project-feature/src/app.js
# Compare entire directories
diff -r ../project-v1/src ../project-v2/src
从 Worktree 合并单个文件
你可以使用 git checkout 从其他分支中选择性地获取单个文件:
# In your current branch, get a specific file from another branch
git checkout feature-branch -- path/to/file.js
# Or get it from a specific commit
git checkout abc1234 -- path/to/file.js
# Get multiple specific files
git checkout feature-branch -- src/module.js src/utils.js
对于部分文件更改(仅选择特定代码块/行):
# Interactive patch mode - select which changes to take
git checkout -p feature-branch -- path/to/file.js
此操作会提示你逐个接受或拒绝每个更改代码块,选项如下:
y- 应用此代码块n- 跳过此代码块s- 拆分为更小的代码块e- 手动编辑此代码块
从 Worktree 挑选提交
挑选提交以提交为单位。由于所有 worktree 共用同一个仓库,你可以挑选任意提交:
# Find the commit hash (from any worktree or git log)
git log feature-branch --oneline
# Cherry-pick specific commit into your current branch
git cherry-pick abc1234
# Cherry-pick multiple commits
git cherry-pick abc1234 def5678
# Cherry-pick a range of commits
git cherry-pick abc1234^..def5678
# Cherry-pick without committing (stage changes only)
git cherry-pick --no-commit abc1234
合并来自多个 Worktree 的更改
你可以从多个分支进行合并或挑选提交:
# Merge multiple branches sequentially
git merge feature-1
git merge feature-2
# Or use octopus merge for multiple branches at once
git merge feature-1 feature-2 feature-3
# Cherry-pick commits from multiple branches
git cherry-pick abc1234 # from feature-1
git cherry-pick def5678 # from feature-2
选择性合并 - 选择要包含的更改
选项 1:选择性检出文件
# Get specific files from different branches
git checkout feature-1 -- src/moduleA.js
git checkout feature-2 -- src/moduleB.js
git commit -m "Merge selected files from feature branches"
选项 2:交互式补丁选择
# Select specific hunks from a file
git checkout -p feature-1 -- src/shared.js
选项 3:使用选择性暂存进行 Cherry-pick
# Apply changes without committing
git cherry-pick --no-commit abc1234
# Unstage what you don't want
git reset HEAD -- unwanted-file.js
git checkout -- unwanted-file.js
# Commit only what you kept
git commit -m "Selected changes from feature-1"
选项 4:手动选择合并内容
# Start merge but don't auto-commit
git merge --no-commit feature-1
# Review and modify staged changes
git status
git reset HEAD -- file-to-exclude.js
git checkout -- file-to-exclude.js
# Commit your selection
git commit -m "Merge selected changes from feature-1"
选项 5:使用 git restore(Git 2.23+)
# Restore specific file from another branch
git restore --source=feature-branch -- path/to/file.js
# Interactive restore with patch selection
git restore -p --source=feature-branch -- path/to/file.js
目录结构约定
以可预测的方式组织工作树:
~/projects/
myproject/ # Main worktree (main/master branch)
myproject-feature-x/ # Feature branch worktree
myproject-hotfix/ # Hotfix worktree
myproject-review/ # Temporary PR review worktree
命名约定:<project>-<purpose> 或 <project>-<branch>
最佳实践
| 实践 | 原因 |
|---|---|
| 使用同级目录 | 将工作树放在与主项目相同的层级,方便导航 |
| 按用途命名 | project-review 比 project-pr-123 更清晰 |
| 及时清理 | 完成后移除工作树,避免混淆 |
| 锁定远程工作树 | 如果工作树位于网络/USB 存储设备上,可防止其被清理 |
对实验使用 --detach | 避免创建一次性分支 |
| 移除前先提交 | 执行 git worktree remove 前,务必提交或暂存更改 |
常见问题与解决方案
问题:“Branch is already checked out”
**原因:**尝试检出已在另一个工作树中处于活动状态的分支。
解决方案:
# Find where the branch is checked out
git worktree list
# Either work in that worktree or remove it first
git worktree remove ../other-worktree
问题:手动删除后工作树仍然残留
**原因:**未使用 git worktree remove 就删除了工作树目录。
解决方案:
# Clean up stale metadata
git worktree prune
问题:手动移动了工作树
**原因:**未使用 git worktree move 就移动了工作树目录。
解决方案:
# Repair the worktree links
git worktree repair
# Or specify the new path
git worktree repair /new/path/to/worktree
问题:工作树所在的驱动器已被移除
**原因:**工作树位于可移动存储设备上,而该设备已断开连接。
解决方案:
# If temporary, lock it to prevent pruning
git worktree lock ../usb-worktree
# If permanent, prune it
git worktree prune
常见错误
| 错误 | 修正方法 |
|---|---|
使用 rm -rf 删除工作树 | 始终使用 git worktree remove,必要时再执行 git worktree prune |
| 忘记分支已被工作树锁定 | 遇到检出错误前,先运行 git worktree list |
| 未清理临时工作树 | 任务完成后立即移除工作树 |
| 在嵌套位置创建工作树 | 使用同级目录(../project-feature),而不是子目录 |
| 手动移动工作树目录 | 使用 git worktree move,或之后运行 git worktree repair |
与 Agent 工作流集成
隔离并行 Agent 任务:
# Create worktree for isolated task
git worktree add -b task-123 ../project-task-123
cd ../project-task-123
# Make changes, run tests, return
cd ../project
使用分离的 HEAD 安全地进行实验:
# Create detached worktree (no branch to clean up)
git worktree add --detach ../project-experiment
cd ../project-experiment
# Experiment, then discard or commit to new branch
git worktree remove --force ../project-experiment
验证清单
使用工作树前:
- 了解一个分支只能在一个工作树中检出
- 确定工作树的创建位置(使用同级目录)
- 为临时工作树规划清理策略
创建工作树时:
- 使用描述性目录名称
- 确认该分支尚未在其他位置检出
- 考虑对实验使用
--detach
移除工作树时:
- 提交或暂存所有未提交的更改
- 使用
git worktree remove,而不是rm -rf - 如果目录是手动删除的,运行
git worktree prune
如何比较工作树
用于比较不同 Git 工作树之间的文件和目录的工作流,帮助用户了解不同分支或工作树中的代码差异。
说明
重要:请严格按照以下步骤操作:
-
检查当前状态:运行
git worktree list,显示所有现有工作树及其位置 -
解析用户输入:对提供的每个参数进行分类:
- 无参数:交互模式——询问用户要比较什么
--stat:显示差异统计摘要(更改的文件、插入数、删除数)- 工作树路径:与
git worktree list中某个工作树根目录匹配的路径 - 分支名称:与某个工作树中的分支匹配的名称
- 文件/目录路径:当前工作树中要进行比较的路径
-
确定比较目标(要比较的工作树): a. 如果用户提供了工作树路径:将这些路径作为比较目标 b. 如果用户指定了分支名称:从
git worktree list中查找这些分支对应的工作树 c. 如果除当前工作树外只有一个工作树:将当前工作树和该工作树作为比较目标 d. 如果存在多个工作树且用户未指定:列出工作树并询问用户要比较哪些 e. 如果没有其他工作树:提供使用git diff与某个分支进行比较的选项 -
确定比较内容(工作树中的文件/目录): a. 如果用户指定了文件或目录路径:比较所有这些路径 b. 如果未指定具体路径:询问用户:
- “比较整个工作树?”或
- “比较特定文件/目录?(输入路径)”
-
执行比较:
比较工作树中的特定文件:
diff <worktree1>/<path> <worktree2>/<path> # Or for unified diff format: diff -u <worktree1>/<path> <worktree2>/<path>比较工作树中的目录:
diff -r <worktree1>/<directory> <worktree2>/<directory> # Or for summary only: diff -rq <worktree1>/<directory> <worktree2>/<directory>比较分支级别(使用 git diff):
git diff <branch1>..<branch2> -- <path> # Or for stat summary: git diff --stat <branch1>..<branch2>与当前工作目录进行比较:
diff <current-file> <other-worktree>/<file> -
整理并呈现结果:
- 显示清晰的标题,说明比较内容
- 对于较大的差异,先询问是否显示摘要
- 标出重要更改(新增文件、已删除文件、重命名文件)
- 提供各工作树所含分支的相关信息
比较模式
| 模式 | 说明 | 命令模式 |
|---|---|---|
| 文件差异 | 比较工作树中的单个文件 | diff -u <wt1>/file <wt2>/file |
| 目录差异 | 递归比较目录 | diff -r <wt1>/dir <wt2>/dir |
| 仅显示摘要 | 显示存在差异的文件(不显示内容) | diff -rq <wt1>/ <wt2>/ |
| Git 差异 | 使用 git 的差异比较(基于分支) | git diff branch1..branch2 -- path |
| 统计视图 | 显示更改统计信息 | git diff --stat branch1..branch2 |
工作树检测
该命令使用 git worktree list 查找工作树:
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
命令会从此输出中提取:
- 路径:工作树目录的绝对路径
- 分支:方括号中的分支名称(用户指定分支名称时使用)
示例
比较工作树中的特定文件:
> /worktrees compare src/app.js
# Prompts to select which worktree to compare with
# Shows diff of src/app.js between current and selected worktree
比较两个指定的工作树:
> /worktrees compare ../project-main ../project-feature src/module.js
# Compares src/module.js between the two specified worktrees
比较多个文件/目录:
> /worktrees compare src/app.js src/utils/ package.json
# Shows diffs for all three paths between worktrees
比较整个目录:
> /worktrees compare src/
# Shows all differences in src/ directory between worktrees
获取统计摘要:
> /worktrees compare --stat
# Shows which files differ and line counts
交互模式:
> /worktrees compare
# Lists available worktrees
# Asks which to compare
# Asks for specific paths or entire worktree
按分支名称与分支工作树进行比较:
> /worktrees compare feature-x
# Finds worktree for feature-x branch and compares
比较分支工作树中的特定路径:
> /worktrees compare main feature-x src/ tests/
# Compares src/ and tests/ directories between main and feature-x worktrees
输出格式
文件比较标题:
Comparing: src/app.js
From: /home/user/project (main)
To: /home/user/project-feature (feature-x)
---
[diff output]
摘要输出:
Worktree Comparison Summary
===========================
From: /home/user/project (main)
To: /home/user/project-feature (feature-x)
Files only in main:
- src/deprecated.js
Files only in feature-x:
+ src/new-feature.js
+ src/new-feature.test.js
Files that differ:
~ src/app.js
~ src/utils/helpers.js
~ package.json
Statistics:
3 files changed
2 files added
1 file removed
常见工作流
检查功能更改
# See what changed in a feature branch
> /worktrees compare --stat
> /worktrees compare src/components/
比较实现
# Compare how two features implemented similar functionality
> /worktrees compare ../project-feature-1 ../project-feature-2 src/auth/
快速检查文件
# Check if a specific file differs
> /worktrees compare package.json
合并前审查
# Review all changes before merging (compare src and tests together)
> /worktrees compare --stat
> /worktrees compare src/ tests/
# Both src/ and tests/ directories will be compared
重要说明
-
参数检测:该命令会通过与
git worktree list输出进行比较,自动检测参数类型:- 与工作树根目录匹配的路径 → 视为要比较的工作树
- 与工作树中分支匹配的名称 → 视为要比较的工作树
- 其他路径 → 视为要在工作树中比较的文件/目录
-
多个路径:提供多个文件/目录路径时,会在选定的工作树之间比较所有路径(而不只是第一个)。
-
工作树路径:指定工作树时,请使用完整路径或相对于当前目录的路径(例如,
../project-feature) -
分支与工作树:如果指定分支名称,命令会查找已检出该分支的工作树。如果该分支没有对应的工作树,命令会建议改用
git diff。 -
大型差异:对于大型目录,命令会先提供摘要,然后再显示完整差异输出。
-
二进制文件:检测到二进制文件时,会报告“Binary files differ”,而不显示实际差异。
-
文件权限:如果文件权限存在差异,差异也会显示这些变更。
-
没有工作树:如果不存在其他工作树,命令会说明如何创建工作树,并提供使用
git diff比较分支的选项。
与创建工作树集成
先使用 /worktrees create 设置要比较的工作树:
# Create worktrees for comparison
> /worktrees create feature-x, main
# Created: ../project-feature-x and ../project-main
# Now compare
> /worktrees compare src/
故障排除
“No other worktrees found”
- 先使用
/worktrees create <branch>创建工作树 - 或使用
git diff,在没有工作树的情况下仅比较分支
“Worktree for branch not found”
- 该分支可能尚未创建工作树
- 运行
git worktree list查看可用工作树 - 使用
/worktrees create <branch>创建工作树
“Path does not exist in worktree”
- 指定的文件/目录可能在其中一个工作树中不存在
- 这可能表示该文件在某个分支中被添加或删除
- 命令会在比较输出中报告这一情况
如何创建工作树
用于创建和设置 git 工作树以进行并行开发的工作流,可自动检测并安装项目依赖项。
说明
重要:请严格按照以下步骤执行:
-
检查当前状态:运行
git worktree list,显示现有工作树;运行git status,确认仓库状态干净(没有可能造成问题的未提交更改) -
获取最新远程分支:运行
git fetch --all,确保本地已获取所有远程分支的信息 -
解析用户输入:确定用户想要创建什么:
<name>:使用自动检测的类型前缀创建工作树--list:仅显示现有工作树并退出- 无输入:交互式询问用户名称
-
根据名称自动检测分支类型:检查首个单词是否为已知分支类型。如果是,将其作为前缀,其余部分作为名称。如果不是,则默认使用
feature/。已知类型:
feature、feat、fix、bug、bugfix、hotfix、release、docs、test、refactor、chore、spike、experiment、review示例:
refactor auth system→refactor/auth-systemfix login bug→fix/login-bugauth system→feature/auth-system(默认)hotfix critical error→hotfix/critical-error
名称规范化: 将空格转换为连字符,转换为小写,并移除除连字符和下划线以外的特殊字符
-
为每个要创建的工作树: a. 构建分支名称:根据检测到的类型和规范化后的名称构建完整分支名称:
<prefix>/<normalized-name>(例如,feature/auth-system)
b. 解析分支:确定分支在本地或远程是否已存在,或是否需要创建:
- 如果分支在本地已存在:
git worktree add ../<project>-<name> <branch> - 如果分支在远程已存在(origin/):
git worktree add --track -b <branch> ../<project>-<name> origin/<branch> - 如果分支不存在:询问用户基准分支(默认:当前分支或 main/master),然后运行
git worktree add -b <branch> ../<project>-<name> <base>
c. 路径约定:使用同级目录,格式为
../<project-name>-<name>- 从当前目录提取项目名称
- 使用规范化后的名称(而不是包含前缀的完整分支名称)
- 示例:
feature/auth-system→../myproject-auth-system
d. 创建工作树:执行相应的 git worktree add 命令
e. 依赖检测:检查新工作树中的依赖文件,并判断是否需要进行设置:
package.json-> Node.js 项目(npm/yarn/pnpm/bun)requirements.txt或pyproject.toml或setup.py-> Python 项目Cargo.toml-> Rust 项目go.mod-> Go 项目Gemfile-> Ruby 项目composer.json-> PHP 项目
f. 检测包管理器(适用于 Node.js 项目):
bun.lockb-> 使用bun installpnpm-lock.yaml-> 使用pnpm installyarn.lock-> 使用yarn installpackage-lock.json或默认 -> 使用npm install
g. 自动设置:自动运行依赖安装:
- 切换到工作树目录并运行检测到的安装命令
- 报告进度:“正在使用 [package manager] 安装依赖……”
- 如果安装失败,报告错误,但继续显示工作树创建摘要
-
摘要:显示已创建工作树的摘要:
- 工作树路径
- 分支名称(包含前缀的完整名称)
- 设置状态(依赖已安装或安装失败)
- 快速导航命令:
cd <worktree-path>
工作树路径约定
工作树将创建为同级目录,以便保持结构清晰:
~/projects/
myproject/ # Main worktree (current directory)
myproject-add-auth/ # Feature branch worktree (feature/add-auth)
myproject-critical-bug/ # Hotfix worktree (hotfix/critical-bug)
myproject-pr-456/ # PR review worktree (review/pr-456)
命名规则:
- 格式:
<project-name>-<name>(使用名称部分,而不是完整分支名称) - 分支名称:
<type-prefix>/<name>(例如,feature/add-auth) - 为简洁起见,目录名称仅使用
<name>部分
示例
功能 worktree(默认):
> /worktrees create auth system
# Branch: feature/auth-system
# Creates: ../myproject-auth-system
修复 worktree:
> /worktrees create fix login error
# Branch: fix/login-error
# Creates: ../myproject-login-error
重构 worktree:
> /worktrees create refactor api layer
# Branch: refactor/api-layer
# Creates: ../myproject-api-layer
热修复 worktree:
> /worktrees create hotfix critical bug
# Branch: hotfix/critical-bug
# Creates: ../myproject-critical-bug
列出现有 worktree:
> /worktrees list
# Shows: git worktree list output
设置检测示例
使用 pnpm 的 Node.js 项目:
Detected Node.js project with pnpm-lock.yaml
Installing dependencies with pnpm...
✓ Dependencies installed successfully
Python 项目:
Detected Python project with requirements.txt
Installing dependencies with pip...
✓ Dependencies installed successfully
Rust 项目:
Detected Rust project with Cargo.toml
Building project with cargo...
✓ Project built successfully
常见工作流
快速创建功能分支
> /worktrees create new dashboard
# Branch: feature/new-dashboard
# Creates worktree, installs dependencies, ready to code
功能开发进行中时修复问题
# In main worktree, working on feature
> /worktrees create hotfix critical bug
# Branch: hotfix/critical-bug
# Creates separate worktree from main/master
# Fix bug in hotfix worktree
# Return to feature work when done
无需暂存即可审查 PR
> /worktrees create review pr 123
# Branch: review/pr-123
# Creates worktree for reviewing PR
# Can run tests, inspect code
# Delete when review complete
实验或预研
> /worktrees create spike new architecture
# Branch: spike/new-architecture
# Creates isolated worktree for experimentation
# Discard or merge based on results
重要说明
-
分支锁定:每个分支一次只能在一个 worktree 中检出。如果某个分支已检出,命令会告知你它所在的 worktree。
-
共享 .git:所有 worktree 共用同一个 Git 对象数据库。在任何 worktree 中提交的更改,其他 worktree 都能看到。
-
干净的工作目录:命令会检查是否有未提交的更改,并在存在时发出警告,因为在干净的状态下创建 worktree 最安全。
-
同级目录:worktree 始终创建为同级目录(使用
../),以保持工作区整洁。切勿在主仓库内创建 worktree。 -
自动安装依赖:命令会自动检测项目类型和包管理器,然后运行相应的安装命令,无需提示。
-
远程跟踪:对于远程分支,worktree 会通过正确的跟踪设置(
--track标志)创建,以确保拉取和推送正常工作。
清理
完成 worktree 的工作后,请使用正确的移除命令:
git worktree remove ../myproject-add-auth
如果 worktree 中有未提交的更改:
git worktree remove --force ../myproject-add-auth
切勿使用 rm -rf 删除 worktree——请始终使用 git worktree remove。
故障排除
“分支已检出”
- 运行
git worktree list查看该分支在哪个位置检出 - 可以在那个 worktree 中工作,或先将其移除
“无法创建 worktree——路径已存在”
- 目标目录已存在
- 可以将其移除,或选择其他 worktree 路径
“依赖安装失败”
- 手动进入 worktree:
cd ../myproject-<name> - 直接运行安装命令,以查看完整的错误输出
- 常见原因:缺少系统依赖、网络问题、锁文件损坏
“检测到的类型不正确”
- 如果第一个单词是已知类型,则会将其用作分支类型
- 若要指定类型,请以以下内容开头:
fix、hotfix、docs、test、refactor、chore、spike、review - 如果第一个单词不是已知类型,则默认类型为
feature/
如何合并 Worktree
帮助用户将 git worktree 中的更改合并到当前分支的工作流,支持从简单的文件检出到选择性 cherry-pick 的多种合并策略。
说明
关键:请严格按照以下步骤操作:
-
检查当前状态:运行
git worktree list,列出所有现有工作树;运行git status,确认工作目录状态 -
解析用户输入:确定用户希望执行的合并操作:
--interactive或不带参数:引导式交互模式- 文件/目录路径:从某个工作树合并指定文件或目录
- 提交名称:Cherry-pick 指定提交
- 分支名称:从该分支的工作树合并
--from <worktree>:明确指定来源工作树--patch或-p:使用交互式补丁选择模式
-
确定来源工作树/分支: a. 如果用户指定了
--from <worktree>:直接使用该工作树路径
b. 如果用户指定了分支名称:从git worktree list中查找该分支对应的工作树
c. 如果只有一个其他工作树:询问用户是否确认使用它作为来源
d. 如果存在多个工作树:列出这些工作树,并询问用户要从哪个工作树合并
e. 如果不存在其他工作树:说明情况,并提供改用基于分支的合并方式 -
确定合并策略:根据用户需求提供选项:
策略 A:选择性检出文件(用于特定文件/目录)
- 适用场景:从其他分支获取完整文件
- 命令:
git checkout <branch> -- <path>
策略 B:交互式补丁选择(用于部分文件更改)
- 适用场景:从文件中选择特定代码块/行
- 命令:
git checkout -p <branch> -- <path> - 对每个代码块询问用户:y(应用)、n(跳过)、s(拆分)、e(编辑)
策略 C:选择性暂存 Cherry-pick(用于特定提交)
- 适用场景:应用某个提交,但排除部分更改
- 步骤:
git cherry-pick --no-commit <commit>- 检查已暂存的更改
- 运行
git reset HEAD -- <unwanted-files>,取消暂存不需要的文件 - 运行
git checkout -- <unwanted-files>,丢弃这些更改 git commit -m "message"
策略 D:带冲突处理的手动合并(用于复杂合并)
- 适用场景:完整合并分支,同时控制冲突解决过程
- 步骤:
git merge --no-commit <branch>- 检查所有更改
- 有选择地暂存/取消暂存文件
- 如有冲突则解决
git commit -m "message"
策略 E:多工作树选择性合并(从多个来源合并内容)
- 适用场景:从不同工作树获取不同文件
- 步骤:
git checkout <branch1> -- <path1>git checkout <branch2> -- <path2>git commit -m "Merge selected files from multiple branches"
-
执行选定的策略:
- 如果用户想先审查,则在合并前进行比较(建议先运行
/worktrees compare) - 执行所选策略对应的 Git 命令
- 处理出现的冲突
- 在最终提交前确认更改
- 如果用户想先审查,则在合并前进行比较(建议先运行
-
合并后摘要:显示合并内容:
- 已更改/新增/删除的文件
- 来源工作树/分支
- 使用的合并策略
-
清理提示:成功合并后,询问:
- “是否要移除任何工作树以清理本地状态?”
- 如果是:列出工作树,并询问要移除哪些
- 对选定的工作树执行
git worktree remove <path> - 如有需要,提醒运行
git worktree prune
合并策略参考
| 策略 | 适用场景 | 命令模式 |
|---|---|---|
| 选择性检出文件 | 需要从其他分支获取完整文件 | git checkout <branch> -- <path> |
| 交互式补丁 | 需要文件中的特定更改 | git checkout -p <branch> -- <path> |
| 选择性 Cherry-pick | 需要某个提交,但不需要其中的所有更改 | git cherry-pick --no-commit + 选择性暂存 |
| 手动合并 | 完整合并分支并控制合并过程 | git merge --no-commit + 选择性暂存 |
| 多来源 | 合并来自多个分支的文件 | 多次运行 git checkout <branch> -- <path> |
示例
从工作树合并单个文件:
> /worktrees merge src/app.js --from ../project-feature
# Prompts for merge strategy
# Executes: git checkout feature-branch -- src/app.js
交互式选择补丁:
> /worktrees merge src/utils.js --patch
# Lists available worktrees to select from
# Runs: git checkout -p feature-branch -- src/utils.js
# User selects hunks interactively (y/n/s/e)
挑选特定提交:
> /worktrees merge abc1234
# Detects commit hash
# Asks: Apply entire commit or selective?
# If selective: git cherry-pick --no-commit abc1234
# Then guides through unstaging unwanted changes
完整引导模式:
> /worktrees merge
# Lists all worktrees
# Asks what to merge (files, commits, or branches)
# Guides through appropriate strategy
# Offers cleanup at end
带冲突的目录合并:
> /worktrees merge src/components/ --from ../project-refactor
# Strategy D: Manual merge with conflicts
# git merge --no-commit refactor-branch
# Helps resolve any conflicts
# Reviews and commits selected changes
交互式补丁模式指南
使用 --patch 或策略 B 时,用户会看到针对每个更改块的提示:
@@ -10,6 +10,8 @@ function processData(input) {
const result = transform(input);
+ // Added validation
+ if (!isValid(result)) throw new Error('Invalid');
return result;
}
Apply this hunk? [y,n,q,a,d,s,e,?]
| 按键 | 操作 |
|---|---|
y | 应用此更改块 |
n | 跳过此更改块 |
q | 退出(不应用此更改块及剩余更改块) |
a | 应用此更改块及所有剩余更改块 |
d | 不应用此文件中的此更改块及剩余更改块 |
s | 拆分为更小的更改块 |
e | 手动编辑此更改块 |
? | 显示帮助 |
挑选提交的选择性工作流
对于策略 C(挑选提交并选择性暂存):
# 1. Apply commit without committing
git cherry-pick --no-commit abc1234
# 2. Check what was staged
git status
# 3. Unstage files you don't want
git reset HEAD -- path/to/unwanted.js
# 4. Discard changes to those files
git checkout -- path/to/unwanted.js
# 5. Commit the remaining changes
git commit -m "Cherry-pick selected changes from abc1234"
多工作树合并工作流
对于策略 E(从多个工作树合并):
# Get files from different branches
git checkout feature-auth -- src/auth/login.js src/auth/session.js
git checkout feature-api -- src/api/endpoints.js
git checkout feature-ui -- src/components/Header.js
# Review all changes
git status
git diff --cached
# Commit combined changes
git commit -m "feat: combine auth, API, and UI improvements from feature branches"
常见工作流
不进行完整合并,仅获取功能文件
> /worktrees merge src/new-feature.js --from ../project-feature
# Gets just the file, not the entire branch
从热修复分支获取部分 Bug 修复
> /worktrees merge --patch src/utils.js --from ../project-hotfix
# Select only the specific bug fix hunks, not all changes
合并多个 PR 的更改
> /worktrees merge --interactive
# Select specific files from PR-1 worktree
# Select other files from PR-2 worktree
# Combine into single coherent commit
合并前审查
# First review what will be merged
> /worktrees compare src/module.js
# Then merge with confidence
> /worktrees merge src/module.js --from ../project-feature
重要说明
-
工作目录状态:合并前务必确保工作目录干净。未提交的更改可能导致冲突。
-
合并前审查:可以在合并前使用
/worktrees compare,了解将应用哪些更改。 -
冲突解决:如果合并期间发生冲突,该命令会帮助你在提交前识别并解决冲突。
-
不提交标志:大多数策略使用
--no-commit,以便你控制最终提交信息和包含的内容。 -
共享存储库:所有工作树共用同一个 Git 对象数据库,因此在任何工作树中创建的提交都能立即在其他工作树中被挑选。
-
分支锁定:请记住,分支一次只能在一个工作树中检出。合并操作时请使用分支名,而不要创建重复的工作树。
合并后清理
合并后,可以清理不再需要的工作树:
# List worktrees
git worktree list
# Remove specific worktree (clean state required)
git worktree remove ../project-feature
# Force remove (discards uncommitted changes)
git worktree remove --force ../project-feature
# Clean up stale worktree references
git worktree prune
每次成功合并后,该命令都会提示你是否进行清理,以帮助保持工作区整洁。
故障排查
“无法合并:工作目录中存在未提交的更改”
- 先提交或暂存当前更改
- 或在合并前运行
git stash,之后运行git stash pop
“<file> 中存在合并冲突”
- 该命令会显示存在冲突的文件
- 打开文件并解决冲突(查找
<<<<<<<标记) - 使用
git add <file>暂存已解决的文件 - 使用
git commit继续
挑选提交时提示“找不到提交”
- 确认提交哈希正确
- 在任意工作树中运行
git log <branch>查找提交 - 所有工作树共享提交
“无法检出:工作树中已存在该文件”
- 文件有本地修改
- 先提交、暂存或丢弃本地更改
- 然后重试合并操作
“找不到工作树对应的分支”
- 指定的工作树可能已被移除
- 运行
git worktree list查看当前工作树 - 使用
git worktree prune清理过期引用
与其他命令集成
合并前审查:
> /worktrees compare src/
> /worktrees merge src/specific-file.js
创建工作树、合并、清理:
> /worktrees create feature-branch
> /worktrees compare src/
> /worktrees merge src/module.js --from ../project-feature-branch
# After merge, cleanup is offered automatically