Git Worktrees
Git Worktree
Git worktrees enable checking out multiple branches simultaneously in separate directories, all sharing the same repository. Create a worktree instead of stashing changes or cloning separately.
Core principle: One worktree per active branch. Switch contexts by changing directories, not branches.
Git worktree 允许在独立目录中同时检出多个分支,所有分支共享同一个仓库。无需暂存变更或单独克隆仓库,直接创建worktree即可。
核心原则: 每个活跃分支对应一个worktree。通过切换目录而非切换分支来切换上下文。
| Concept | Description |
|---|
| Main worktree | Original working directory from or |
| Linked worktree | Additional directories created with |
| Shared | All worktrees share same Git object database (no duplication) |
| Branch lock | Each branch can only be checked out in ONE worktree at a time |
| Worktree metadata | Administrative files in tracking linked worktrees |
| 概念 | 描述 |
|---|
| 主worktree | 由或创建的原始工作目录 |
| 关联worktree | 使用创建的额外目录 |
| 共享 | 所有worktree共享同一个Git对象数据库(无重复存储) |
| 分支锁定 | 每个分支同一时间只能在一个worktree中检出 |
| Worktree元数据 | 中的管理文件,用于跟踪关联的worktree |
| Task | Command |
|---|
| Create worktree (existing branch) | git worktree add <path> <branch>
|
| Create worktree (new branch) | git worktree add -b <branch> <path>
|
| Create worktree (new branch from ref) | git worktree add -b <branch> <path> <start>
|
| Create detached worktree | git worktree add --detach <path> <commit>
|
| List all worktrees | |
| Remove worktree | git worktree remove <path>
|
| Force remove worktree | git worktree remove --force <path>
|
| Move worktree | git worktree move <old> <new>
|
| Lock worktree | |
| Unlock worktree | git worktree unlock <path>
|
| Prune stale worktrees | |
| Repair worktree links | |
| Compare files between worktrees | diff ../worktree-a/file ../worktree-b/file
|
| Get one file from another branch | git checkout <branch> -- <path>
|
| Get partial file changes | git checkout -p <branch> -- <path>
|
| Cherry-pick a commit | |
| Cherry-pick without committing | git cherry-pick --no-commit <commit>
|
| Merge without auto-commit | git merge --no-commit <branch>
|
| 任务 | 命令 |
|---|
| 创建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 | |
| 删除worktree | git worktree remove <path>
|
| 强制删除worktree | git worktree remove --force <path>
|
| 移动worktree | git worktree move <old> <new>
|
| 锁定worktree | |
| 解锁worktree | git worktree unlock <path>
|
| 清理过期worktree | |
| 修复worktree链接 | |
| 对比不同worktree的文件 | diff ../worktree-a/file ../worktree-b/file
|
| 从其他分支获取单个文件 | git checkout <branch> -- <path>
|
| 获取文件的部分变更 | git checkout -p <branch> -- <path>
|
| 拣选提交 | |
| 拣选提交但不自动提交 | git cherry-pick --no-commit <commit>
|
| 合并但不自动提交 | git merge --no-commit <branch>
|
Create a Worktree
创建Worktree
Create worktree with existing branch
基于已有分支创建worktree
git worktree add ../feature-x feature-x
git worktree add ../feature-x feature-x
Create worktree with new branch from current HEAD
基于当前HEAD创建新分支的worktree
git worktree add -b new-feature ../new-feature
git worktree add -b new-feature ../new-feature
Create worktree with new branch from specific commit
基于指定提交创建新分支的worktree
git worktree add -b hotfix-123 ../hotfix origin/main
git worktree add -b hotfix-123 ../hotfix origin/main
Create worktree tracking remote branch
创建跟踪远程分支的worktree
git worktree add --track -b feature ../feature origin/feature
git worktree add --track -b feature ../feature origin/feature
Create worktree with detached HEAD (for experiments)
创建分离头指针的worktree(用于实验)
git worktree add --detach ../experiment HEAD~5
git worktree add --detach ../experiment HEAD~5
Verbose output with additional details
包含额外详情的 verbose 输出
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]
git worktree list --porcelain
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
Remove a Worktree
删除Worktree
Remove worktree (working directory must be clean)
删除worktree(工作目录必须干净)
git worktree remove ../feature-x
git worktree remove ../feature-x
Force remove (discards uncommitted changes)
强制删除(丢弃未提交变更)
git worktree remove --force ../feature-x
git worktree remove --force ../feature-x
Move a Worktree
移动Worktree
Relocate worktree to new path
将worktree迁移到新路径
git worktree move ../old-path ../new-path
git worktree move ../old-path ../new-path
Lock/Unlock Worktrees
锁定/解锁Worktree
Lock worktree (prevents pruning if on removable storage)
锁定worktree(防止在可移动存储上被清理)
git worktree lock ../feature-x
git worktree lock --reason "On USB drive" ../feature-x
git worktree lock ../feature-x
git worktree lock --reason "On USB drive" ../feature-x
Unlock worktree
解锁worktree
git worktree unlock ../feature-x
git worktree unlock ../feature-x
Prune Stale Worktrees
清理过期Worktree
Remove stale worktree metadata (after manual directory deletion)
清理过期的worktree元数据(手动删除目录后)
Dry-run to see what would be pruned
试运行,查看会被清理的内容
git worktree prune --dry-run
git worktree prune --dry-run
Repair Worktrees
修复Worktree
Repair worktree links after moving directories manually
手动移动目录后修复worktree链接
Repair specific worktree
修复指定的worktree
git worktree repair ../feature-x
git worktree repair ../feature-x
Pattern 1: Feature + Hotfix in Parallel
模式1:功能开发与热修复并行
To fix a bug while feature work is in progress:
Create worktree for hotfix from main
基于main分支创建热修复worktree
git worktree add -b hotfix-456 ../project-hotfix origin/main
git worktree add -b hotfix-456 ../project-hotfix origin/main
Switch to hotfix directory, fix, commit, push
切换到热修复目录,修复bug、提交、推送
cd ../project-hotfix
git add . && git commit -m "fix: resolve critical bug #456"
git push origin hotfix-456
cd ../project-hotfix
git add . && git commit -m "fix: resolve critical bug #456"
git push origin hotfix-456
Return to feature work
返回功能开发目录
git worktree remove ../project-hotfix
git worktree remove ../project-hotfix
Pattern 2: PR Review While Working
模式2:开发时审查PR
To review a PR without affecting current work:
Fetch PR branch and create worktree
获取PR分支并创建worktree
git fetch origin pull/123/head:pr-123
git worktree add ../project-review pr-123
git fetch origin pull/123/head:pr-123
git worktree add ../project-review pr-123
Review: run tests, inspect code
审查:运行测试、检查代码
Return to work, then clean up
返回工作目录,然后清理
cd ../project
git worktree remove ../project-review
git branch -d pr-123
cd ../project
git worktree remove ../project-review
git branch -d pr-123
Pattern 3: Compare Implementations
模式3:对比不同实现
To compare code across branches side-by-side:
Create worktrees for different versions
为不同版本创建worktree
git worktree add ../project-v1 v1.0.0
git worktree add ../project-v2 v2.0.0
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
diff ../project-v1/src/module.js ../project-v2/src/module.js
git worktree remove ../project-v1
git worktree remove ../project-v2
git worktree remove ../project-v1
git worktree remove ../project-v2
Pattern 4: Long-Running Tasks
模式4:长时间运行任务
To run tests/builds in isolation while continuing development:
Create worktree for CI-like testing
为类CI测试创建worktree
git worktree add ../project-test main
git worktree add ../project-test main
Start long-running tests in background
在后台启动长时间运行的测试
cd ../project-test && npm test &
cd ../project-test && npm test &
Continue development in main worktree
在主worktree中继续开发
Pattern 5: Stable Reference
模式5:稳定参考分支
To maintain a clean main checkout for reference:
Create permanent worktree for main branch
为main分支创建永久worktree
git worktree add ../project-main main
git worktree add ../project-main main
Lock to prevent accidental removal
锁定以防止意外删除
git worktree lock --reason "Reference checkout" ../project-main
git worktree lock --reason "Reference checkout" ../project-main
Pattern 6: Selective Merging from Multiple Features
模式6:从多个功能分支选择性合并
To combine specific changes from multiple feature branches:
Create worktrees for each feature to review
为每个功能分支创建worktree以便审查
git worktree add ../project-feature-1 feature-1
git worktree add ../project-feature-2 feature-2
git worktree add ../project-feature-1 feature-1
git worktree add ../project-feature-2 feature-2
Review changes in each worktree
审查每个worktree中的变更
diff ../project/src/module.js ../project-feature-1/src/module.js
diff ../project/src/module.js ../project-feature-2/src/module.js
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
在主worktree中选择性获取变更
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"
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
git cherry-pick abc1234 # 来自feature-1
git cherry-pick def5678 # 来自feature-2
git worktree remove ../project-feature-1
git worktree remove ../project-feature-2
git worktree remove ../project-feature-1
git worktree remove ../project-feature-2
Comparing and Merging Changes Between Worktrees
Worktree间的对比与合并
Since all worktrees share the same Git repository, you can compare files, cherry-pick commits, and selectively merge changes between them.
由于所有worktree共享同一个Git仓库,你可以在它们之间对比文件、拣选提交以及选择性合并变更。
Compare and Review File Changes
对比与审查文件变更
Since worktrees are just directories, you can compare files directly:
worktree本质就是目录,你可以直接对比文件:
Compare specific file between worktrees
对比不同worktree中的特定文件
diff ../project-main/src/app.js ../project-feature/src/app.js
diff ../project-main/src/app.js ../project-feature/src/app.js
Use git diff to compare branches (works from any worktree)
使用git diff对比分支(在任意worktree中都可运行)
git diff main..feature-branch -- src/app.js
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
code --diff ../project-main/src/app.js ../project-feature/src/app.js
Compare entire directories
对比整个目录
diff -r ../project-v1/src ../project-v2/src
diff -r ../project-v1/src ../project-v2/src
Merge Only One File from a Worktree
从Worktree合并单个文件
You can selectively bring a single file from another branch using
:
In your current branch, get a specific file from another branch
在当前分支中,从其他分支获取特定文件
git checkout feature-branch -- path/to/file.js
git checkout feature-branch -- path/to/file.js
Or get it from a specific commit
或者从特定提交获取
git checkout abc1234 -- path/to/file.js
git checkout abc1234 -- path/to/file.js
Get multiple specific files
获取多个特定文件
git checkout feature-branch -- src/module.js src/utils.js
For **partial file changes** (specific hunks/lines only):
```bash
git checkout feature-branch -- src/module.js src/utils.js
对于**部分文件变更**(仅特定代码块/行):
```bash
Interactive patch mode - select which changes to take
交互式补丁模式 - 选择要应用的变更
git checkout -p feature-branch -- path/to/file.js
This prompts you to accept/reject each change hunk individually with options:
- `y` - apply this hunk
- `n` - skip this hunk
- `s` - split into smaller hunks
- `e` - manually edit the hunk
git checkout -p feature-branch -- path/to/file.js
这会提示你逐个接受/拒绝每个代码块,选项包括:
- `y` - 应用此代码块
- `n` - 跳过此代码块
- `s` - 拆分为更小的代码块
- `e` - 手动编辑代码块
Cherry-Pick Commits from Worktrees
从Worktree拣选提交
Cherry-picking works at the commit level. Since all worktrees share the same repository, you can cherry-pick any commit:
拣选操作基于提交进行。由于所有worktree共享同一个仓库,你可以拣选任意提交:
Find the commit hash (from any worktree or git log)
查找提交哈希(在任意worktree或git log中)
git log feature-branch --oneline
git log feature-branch --oneline
Cherry-pick specific commit into your current branch
将特定提交拣选到当前分支
Cherry-pick multiple commits
拣选多个提交
git cherry-pick abc1234 def5678
git cherry-pick abc1234 def5678
Cherry-pick a range of commits
拣选一个提交范围
git cherry-pick abc1234^..def5678
git cherry-pick abc1234^..def5678
Cherry-pick without committing (stage changes only)
拣选提交但不自动提交(仅暂存变更)
git cherry-pick --no-commit abc1234
git cherry-pick --no-commit abc1234
Merge Changes from Multiple Worktrees
从多个Worktree合并变更
You can merge or cherry-pick from multiple branches:
Merge multiple branches sequentially
依次合并多个分支
git merge feature-1
git merge feature-2
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
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
git cherry-pick abc1234 # 来自feature-1
git cherry-pick def5678 # 来自feature-2
Selective Merging - Pick Which Changes to Include
选择性合并 - 选择要包含的变更
Option 1: Selective File Checkout
选项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"
git checkout feature-1 -- src/moduleA.js
git checkout feature-2 -- src/moduleB.js
git commit -m "Merge selected files from feature branches"
Option 2: Interactive Patch Selection
选项2:交互式补丁选择
Select specific hunks from a file
选择文件中的特定代码块
git checkout -p feature-1 -- src/shared.js
git checkout -p feature-1 -- src/shared.js
Option 3: Cherry-Pick with Selective Staging
选项3:带选择性暂存的拣选
Apply changes without committing
应用变更但不提交
git cherry-pick --no-commit abc1234
git cherry-pick --no-commit abc1234
Unstage what you don't want
取消暂存不需要的内容
git reset HEAD -- unwanted-file.js
git checkout -- unwanted-file.js
git reset HEAD -- unwanted-file.js
git checkout -- unwanted-file.js
Commit only what you kept
仅提交保留的内容
git commit -m "Selected changes from feature-1"
git commit -m "Selected changes from feature-1"
Option 4: Merge with Manual Selection
选项4:手动选择合并
Start merge but don't auto-commit
开始合并但不自动提交
git merge --no-commit feature-1
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
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"
git commit -m "Merge selected changes from feature-1"
Option 5: Using git restore (Git 2.23+)
选项5:使用git restore(Git 2.23+)
Restore specific file from another branch
从其他分支恢复特定文件
git restore --source=feature-branch -- path/to/file.js
git restore --source=feature-branch -- path/to/file.js
Interactive restore with patch selection
交互式恢复并选择补丁
git restore -p --source=feature-branch -- path/to/file.js
git restore -p --source=feature-branch -- path/to/file.js
Directory Structure Conventions
目录结构规范
Organize worktrees predictably:
~/projects/
myproject/ # Main worktree (main/master branch)
myproject-feature-x/ # Feature branch worktree
myproject-hotfix/ # Hotfix worktree
myproject-review/ # Temporary PR review worktree
有规律地组织worktree:
~/projects/
myproject/ # 主worktree(main/master分支)
myproject-feature-x/ # 功能分支worktree
myproject-hotfix/ # 热修复worktree
myproject-review/ # 临时PR审查worktree
| Practice | Rationale |
|---|
| Use sibling directories | Keep worktrees at same level as main project for easy navigation |
| Name by purpose | is clearer than |
| Clean up promptly | Remove worktrees when done to avoid confusion |
| Lock remote worktrees | Prevent pruning if worktree is on network/USB storage |
| Use for experiments | Avoid creating throwaway branches |
| Commit before removing | Always commit or stash before |
| 实践 | 理由 |
|---|
| 使用同级目录 | 将worktree与主项目放在同一层级,便于导航 |
| 按用途命名 | 比 更清晰 |
| 及时清理 | 完成任务后删除worktree,避免混淆 |
| 锁定远程worktree | 如果worktree在网络/USB存储上,锁定以防止被清理 |
| 实验时使用 | 避免创建临时分支 |
| 删除前提交 | 在执行前,务必提交或暂存变更 |
Common Issues and Solutions
常见问题与解决方案
Issue: "Branch is already checked out"
问题:"Branch is already checked out"
Cause: Attempting to checkout a branch that's active in another worktree.
Solution:
原因: 尝试检出已在另一个worktree中激活的分支。
解决方案:
Find where the branch is checked out
查找分支被检出的位置
Either work in that worktree or remove it first
要么在对应的worktree中操作,要么先删除它
git worktree remove ../other-worktree
git worktree remove ../other-worktree
Issue: Stale worktree after manual deletion
问题:手动删除后worktree过期
Cause: Deleted worktree directory without using
.
Solution:
Clean up stale metadata
清理过期的元数据
Issue: Worktree moved manually
问题:手动移动了worktree
Cause: Moved worktree directory without using
.
Solution:
Repair the worktree links
修复worktree链接
Or specify the new path
或者指定新路径
git worktree repair /new/path/to/worktree
git worktree repair /new/path/to/worktree
Issue: Worktree on removed drive
问题:worktree所在驱动器已移除
Cause: Worktree was on removable storage that's no longer connected.
Solution:
原因: worktree所在的可移动存储已断开连接。
解决方案:
If temporary, lock it to prevent pruning
如果是临时情况,锁定以防止被清理
git worktree lock ../usb-worktree
git worktree lock ../usb-worktree
If permanent, prune it
如果是永久移除,清理它
| Mistake | Fix |
|---|
| Using to delete worktree | Always use , then if needed |
| Forgetting branch is locked to worktree | Run before checkout errors |
| Not cleaning up temporary worktrees | Remove worktrees immediately after task completion |
| Creating worktrees in nested locations | Use sibling directories () not subdirs |
| Moving worktree directory manually | Use or run after |
| 错误 | 修复方法 |
|---|
| 使用删除worktree | 始终使用,必要时再执行 |
| 忘记分支已被worktree锁定 | 在出现检出错误前,先运行 |
| 未清理临时worktree | 任务完成后立即删除worktree |
| 在嵌套位置创建worktree | 使用同级目录()而非子目录 |
| 手动移动worktree目录 | 使用,或移动后运行 |
Agent Workflow Integration
Agent工作流集成
To isolate parallel agent tasks:
Create worktree for isolated task
为隔离任务创建worktree
git worktree add -b task-123 ../project-task-123
cd ../project-task-123
git worktree add -b task-123 ../project-task-123
cd ../project-task-123
Make changes, run tests, return
进行变更、运行测试,返回主目录
cd ../project
To experiment safely with detached HEAD:
```bash
Create detached worktree (no branch to clean up)
创建分离头指针的worktree(无需清理分支)
git worktree add --detach ../project-experiment
cd ../project-experiment
git worktree add --detach ../project-experiment
cd ../project-experiment
Experiment, then discard or commit to new branch
实验完成后,丢弃或提交到新分支
git worktree remove --force ../project-experiment
git worktree remove --force ../project-experiment
Verification Checklist
验证清单
Before using worktrees:
When creating worktrees:
When removing worktrees:
使用worktree前:
创建worktree时:
删除worktree时:
How to Compare Worktrees
如何对比Worktree
Workflow to compare files and directories between git worktrees, helping users understand differences in code across branches or worktrees.
用于对比Git worktree间文件和目录的工作流,帮助用户理解不同分支或worktree的代码差异。
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Run
to show all existing worktrees and their locations
-
Parse user input: Classify each provided argument:
- No arguments: Interactive mode - ask user what to compare
- : Show summary statistics of differences (files changed, insertions, deletions)
- Worktree path: A path that matches one of the worktree roots from
- Branch name: A name that matches a branch in one of the worktrees
- File/directory path: A path within the current worktree to compare
-
Determine comparison targets (worktrees to compare):
a. If user provided worktree paths: Use those as comparison targets
b. If user specified branch names: Find the worktrees for those branches from
c. If only one worktree exists besides current: Use current and that one as comparison targets
d. If multiple worktrees exist and none specified: Present list and ask user which to compare
e. If no other worktrees exist: Offer to compare with a branch using
-
Determine what to compare (files/directories within worktrees):
a. If user specified file(s) or directory(ies) paths: Compare ALL of them
b. If no specific paths given: Ask user:
- "Compare entire worktree?" or
- "Compare specific files/directories? (enter paths)"
-
Execute comparison:
For specific files between worktrees:
bash
diff <worktree1>/<path> <worktree2>/<path>
# Or for unified diff format:
diff -u <worktree1>/<path> <worktree2>/<path>
For directories between worktrees:
bash
diff -r <worktree1>/<directory> <worktree2>/<directory>
# Or for summary only:
diff -rq <worktree1>/<directory> <worktree2>/<directory>
For branch-level comparison (using git diff):
bash
git diff <branch1>..<branch2> -- <path>
# Or for stat summary:
git diff --stat <branch1>..<branch2>
For comparing with current working directory:
bash
diff <current-file> <other-worktree>/<file>
-
Format and present results:
- Show clear header indicating what's being compared
- For large diffs, offer to show summary first
- Highlight significant changes (new files, deleted files, renamed files)
- Provide context about the branches each worktree contains
重要:严格按照以下步骤执行:
-
当前状态检查:运行
查看所有现有worktree及其位置
-
解析用户输入:对每个提供的参数进行分类:
- 无参数:交互式模式 - 询问用户要对比的内容
- :显示差异的汇总统计信息(变更文件数、插入行数、删除行数)
- Worktree路径:与输出中某个worktree根目录匹配的路径
- 分支名称:与某个worktree中分支匹配的名称
- 文件/目录路径:当前worktree中要对比的路径
-
确定对比目标(要对比的worktree):
a. 如果用户提供了worktree路径:将这些作为对比目标
b. 如果用户指定了分支名称:从
中找到对应分支的worktree
c. 如果除当前外仅存在一个worktree:将当前和该worktree作为对比目标
d. 如果存在多个worktree且未指定:列出所有选项并询问用户要对比哪些
e. 如果不存在其他worktree:建议使用
对比分支
-
确定对比内容(worktree内的文件/目录):
a. 如果用户指定了文件/目录路径:对比所有指定路径
b. 如果未指定具体路径:询问用户:
- "是否对比整个worktree?" 或
- "是否对比特定文件/目录?(输入路径)"
-
执行对比:
对比不同worktree的特定文件:
bash
diff <worktree1>/<path> <worktree2>/<path>
# 或者使用统一差异格式:
diff -u <worktree1>/<path> <worktree2>/<path>
对比不同worktree的目录:
bash
diff -r <worktree1>/<directory> <worktree2>/<directory>
# 或者仅显示摘要:
diff -rq <worktree1>/<directory> <worktree2>/<directory>
基于分支的对比(使用git diff):
bash
git diff <branch1>..<branch2> -- <path>
# 或者显示统计摘要:
git diff --stat <branch1>..<branch2>
与当前工作目录对比:
bash
diff <current-file> <other-worktree>/<file>
-
格式化并展示结果:
- 显示清晰的标题,说明正在对比的内容
- 对于大型差异,先提供摘要选项
- 突出重要变更(新增文件、删除文件、重命名文件)
- 提供每个worktree对应分支的上下文信息
| Mode | Description | Command Pattern |
|---|
| File diff | Compare single file between worktrees | diff -u <wt1>/file <wt2>/file
|
| Directory diff | Compare directories recursively | diff -r <wt1>/dir <wt2>/dir
|
| Summary only | Show which files differ (no content) | |
| Git diff | Use git's diff (branch-based) | git diff branch1..branch2 -- path
|
| Stat view | Show change statistics | git diff --stat branch1..branch2
|
| 模式 | 描述 | 命令模板 |
|---|
| 文件差异 | 对比不同worktree的单个文件 | diff -u <wt1>/file <wt2>/file
|
| 目录差异 | 递归对比目录 | diff -r <wt1>/dir <wt2>/dir
|
| 仅摘要 | 显示哪些文件不同(不显示内容) | |
| Git差异 | 使用Git的diff功能(基于分支) | git diff branch1..branch2 -- path
|
| 统计视图 | 显示变更统计信息 | git diff --stat branch1..branch2
|
Worktree Detection
Worktree检测
The command finds worktrees using
:
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
From this output, the command extracts:
- Path: The absolute path to the worktree directory
- Branch: The branch name in brackets (used when user specifies branch name)
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
从该输出中,命令提取:
- 路径:worktree目录的绝对路径
- 分支:括号中的分支名称(当用户指定分支名称时使用)
Compare specific file between worktrees:
bash
> /worktrees compare src/app.js
对比不同worktree的特定文件:
bash
> /worktrees compare src/app.js
Prompts to select which worktree to compare with
提示用户选择要对比的worktree
Shows diff of src/app.js between current and selected worktree
显示当前worktree与所选worktree的src/app.js差异
**Compare between two specific worktrees:**
```bash
> /worktrees compare ../project-main ../project-feature src/module.js
**对比两个特定worktree:**
```bash
> /worktrees compare ../project-main ../project-feature src/module.js
Compares src/module.js between the two specified worktrees
对比两个指定worktree的src/module.js
**Compare multiple files/directories:**
```bash
> /worktrees compare src/app.js src/utils/ package.json
**对比多个文件/目录:**
```bash
> /worktrees compare src/app.js src/utils/ package.json
Shows diffs for all three paths between worktrees
显示所有三个路径在worktree间的差异
**Compare entire directories:**
```bash
> /worktrees compare src/
**对比整个目录:**
```bash
> /worktrees compare src/
Shows all differences in src/ directory between worktrees
显示src/目录在worktree间的所有差异
**Get summary statistics:**
```bash
> /worktrees compare --stat
**获取统计摘要:**
```bash
> /worktrees compare --stat
Shows which files differ and line counts
显示哪些文件不同以及行数统计
**Interactive mode:**
```bash
> /worktrees compare
**交互式模式:**
```bash
> /worktrees compare
Lists available worktrees
列出可用worktree
Asks which to compare
询问用户要对比哪些
Asks for specific paths or entire worktree
询问用户要对比特定路径还是整个worktree
**Compare with branch worktree by branch name:**
```bash
> /worktrees compare feature-x
**通过分支名称对比worktree:**
```bash
> /worktrees compare feature-x
Finds worktree for feature-x branch and compares
找到feature-x分支对应的worktree并进行对比
**Compare specific paths between branch worktrees:**
```bash
> /worktrees compare main feature-x src/ tests/
**对比分支worktree的特定路径:**
```bash
> /worktrees compare main feature-x src/ tests/
Compares src/ and tests/ directories between main and feature-x worktrees
对比main和feature-x worktree的src/和tests/目录
File Comparison Header:
Comparing: src/app.js
From: /home/user/project (main)
To: /home/user/project-feature (feature-x)
---
[diff output]
Summary 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
文件对比标题:
对比内容:src/app.js
来源:/home/user/project (main)
目标:/home/user/project-feature (feature-x)
---
[差异输出]
摘要输出:
Worktree对比摘要
===========================
来源:/home/user/project (main)
目标:/home/user/project-feature (feature-x)
仅在main中存在的文件:
- src/deprecated.js
仅在feature-x中存在的文件:
+ src/new-feature.js
+ src/new-feature.test.js
存在差异的文件:
~ src/app.js
~ src/utils/helpers.js
~ package.json
统计信息:
3个文件变更
2个文件新增
1个文件删除
Review Feature Changes
审查功能变更
See what changed in a feature branch
查看功能分支的变更
/worktrees compare --stat
/worktrees compare src/components/
/worktrees compare --stat
/worktrees compare src/components/
Compare Implementations
对比不同实现
Compare how two features implemented similar functionality
对比两个功能分支对相似功能的实现
/worktrees compare ../project-feature-1 ../project-feature-2 src/auth/
/worktrees compare ../project-feature-1 ../project-feature-2 src/auth/
Check if a specific file differs
检查特定文件是否存在差异
/worktrees compare package.json
/worktrees compare package.json
Review all changes before merging (compare src and tests together)
合并前审查所有变更(同时对比src和tests目录)
/worktrees compare --stat
/worktrees compare src/ tests/
/worktrees compare --stat
/worktrees compare src/ tests/
Both src/ and tests/ directories will be compared
src/和tests/目录都会被对比
-
Argument detection: The command auto-detects argument types by comparing them against
output:
- Paths matching worktree roots → treated as worktrees to compare
- Names matching branches in worktrees → treated as worktrees to compare
- Other paths → treated as files/directories to compare within worktrees
-
Multiple paths: When multiple file/directory paths are provided, ALL of them are compared between the selected worktrees (not just the first one).
-
Worktree paths: When specifying worktrees, use the full path or relative path from current directory (e.g.,
)
-
Branch vs Worktree: If you specify a branch name, the command looks for a worktree with that branch checked out. If no worktree exists for that branch, it suggests using
instead.
-
Large diffs: For large directories, the command will offer to show a summary first before displaying full diff output.
-
Binary files: Binary files are detected and reported as "Binary files differ" without showing actual diff.
-
File permissions: The diff will also show changes in file permissions if they differ.
-
No worktrees: If no other worktrees exist, the command will explain how to create one and offer to use
for branch comparison instead.
-
- 匹配worktree根目录的路径 → 作为要对比的worktree
- 匹配worktree中分支的名称 → 作为要对比的worktree
- 其他路径 → 作为要在worktree间对比的文件/目录
-
多路径支持:当提供多个文件/目录路径时,所有路径都会在所选worktree间进行对比(而非仅第一个)。
-
Worktree路径:指定worktree时,使用完整路径或相对于当前目录的路径(例如
)
-
分支与Worktree:如果指定分支名称,命令会查找检出该分支的worktree。如果该分支没有对应的worktree,会建议使用
。
-
大型差异:对于大型目录,命令会先提供摘要选项,再显示完整差异输出。
-
二进制文件:会自动检测二进制文件,并提示"Binary files differ",不显示实际差异内容。
-
文件权限:如果文件权限不同,差异结果中也会显示。
-
无worktree:如果不存在其他worktree,命令会说明如何创建worktree,并建议使用
进行分支对比。
Integration with Create Worktree
与创建Worktree集成
Use
first to set up worktrees for comparison:
Create worktrees for comparison
创建用于对比的worktree
/worktrees create feature-x, main
/worktrees create feature-x, main
Created: ../project-feature-x and ../project-main
创建完成:../project-feature-x 和 ../project-main
"No other worktrees found"
- Create a worktree first with
/worktrees create <branch>
- Or use for branch-only comparison without worktrees
"Worktree for branch not found"
- The branch may not have a worktree created
- Run to see available worktrees
- Create the worktree with
/worktrees create <branch>
"Path does not exist in worktree"
- The specified file/directory may not exist in one of the worktrees
- This could indicate the file was added/deleted in one branch
- The command will report this in the comparison output
"未找到其他worktree"
- 先使用
/worktrees create <branch>
创建worktree
- 或者使用进行仅分支的对比,无需worktree
"未找到分支对应的worktree"
- 该分支可能没有创建对应的worktree
- 运行查看可用worktree
- 使用
/worktrees create <branch>
创建worktree
"路径在worktree中不存在"
- 指定的文件/目录可能在其中一个worktree中不存在
- 这可能意味着该文件在某个分支中被添加/删除
- 命令会在对比输出中报告此情况
How to Create Worktree
如何创建Worktree
Workflow to create and setup git worktrees for parallel development, with automatic detection and installation of project dependencies.
用于创建和配置Git worktree以支持并行开发的工作流,可自动检测并安装项目依赖。
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Run
to show existing worktrees and
to verify the repository state is clean (no uncommitted changes that might cause issues)
-
Fetch latest remote branches: Run
to ensure local has knowledge of all remote branches
-
Parse user input: Determine what the user wants to create:
- : Create worktree with auto-detected type prefix
- : Just show existing worktrees and exit
- No input: Ask user interactively for the name
-
Auto-detect branch type from name: Check if the first word is a known branch type. If yes, use it as the prefix and the rest as the name. If no, default to
.
Known types: ,
,
,
,
,
,
,
,
,
,
,
,
,
Examples:
Name normalization: Convert spaces to dashes, lowercase, remove special characters except dashes/underscores
-
For each worktree to create:
a. Branch name construction: Build full branch name from detected type and normalized name:
<prefix>/<normalized-name>
(e.g., )
b. Branch resolution: Determine if the branch exists locally, remotely, or needs to be created:
- If branch exists locally:
git worktree add ../<project>-<name> <branch>
- If branch exists remotely (origin/<branch>):
git worktree add --track -b <branch> ../<project>-<name> origin/<branch>
- If branch doesn't exist: Ask user for base branch (default: current branch or main/master), then
git worktree add -b <branch> ../<project>-<name> <base>
c.
Path convention: Use sibling directory with pattern
- Extract project name from current directory
- Use the normalized name (NOT the full branch with prefix)
- Example: →
d. Create the worktree: Execute the appropriate git worktree add command
e. Dependency detection: Check the new worktree for dependency files and determine if setup is needed:
- -> Node.js project (npm/yarn/pnpm/bun)
- or or -> Python project
- -> Rust project
- -> Go project
- -> Ruby project
- -> PHP project
f. Package manager detection (for Node.js projects):
- -> Use
- -> Use
- -> Use
- or default -> Use
g. Automatic setup: Automatically run dependency installation:
- cd to worktree and run the detected install command
- Report progress: "Installing dependencies with [package manager]..."
- If installation fails, report the error but continue with worktree creation summary
-
Summary: Display summary of created worktrees:
- Worktree path
- Branch name (full name with prefix)
- Setup status (dependencies installed or failed)
- Quick navigation command:
重要:严格按照以下步骤执行:
-
当前状态检查:运行
查看现有worktree,运行
验证仓库状态干净(无未提交变更,避免出现问题)
-
-
解析用户输入:确定用户要创建的内容:
- :创建带有自动检测类型前缀的worktree
- :仅显示现有worktree并退出
- 无输入:交互式询问用户名称
-
从名称自动检测分支类型:检查第一个单词是否为已知分支类型。如果是,将其作为前缀,剩余部分作为名称。如果不是,默认使用
。
已知类型: ,
,
,
,
,
,
,
,
,
,
,
,
,
示例:
名称规范化: 将空格转换为连字符,转为小写,移除除连字符/下划线外的特殊字符
-
创建每个worktree:
a. 分支名称构建:从检测到的类型和规范化名称构建完整分支名称:
<prefix>/<normalized-name>
(例如)
b. 分支解析:确定分支是否在本地存在、远程存在,或者需要创建:
- 如果分支在本地存在:
git worktree add ../<project>-<name> <branch>
- 如果分支在远程存在(origin/<branch>):
git worktree add --track -b <branch> ../<project>-<name> origin/<branch>
- 如果分支不存在:询问用户基准分支(默认:当前分支或main/master),然后执行
git worktree add -b <branch> ../<project>-<name> <base>
- 从当前目录提取项目名称
- 使用规范化名称(而非带前缀的完整分支名)
- 示例: →
d. 创建worktree:执行对应的git worktree add命令
e. 依赖检测:检查新worktree的依赖文件,确定是否需要配置:
- → Node.js项目(npm/yarn/pnpm/bun)
- 或或 → Python项目
- → Rust项目
- → Go项目
- → Ruby项目
- → PHP项目
f. 包管理器检测(针对Node.js项目):
g. 自动配置:自动运行依赖安装:
- 切换到worktree目录并运行检测到的安装命令
- 报告进度:"正在使用[包管理器]安装依赖..."
- 如果安装失败,报告错误但继续显示worktree创建摘要
-
摘要:显示已创建worktree的摘要:
- Worktree路径
- 分支名称(带前缀的完整名称)
- 配置状态(依赖安装成功或失败)
- 快速导航命令:
Worktree Path Convention
Worktree路径规范
Worktrees are created as sibling directories to maintain organization:
~/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)
Naming rules:
- Pattern: (uses the name part, NOT the full branch)
- Branch name: (e.g., )
- Directory name uses only the portion for brevity
Worktree创建为同级目录,以保持组织性:
~/projects/
myproject/ # 主worktree(当前目录)
myproject-add-auth/ # 功能分支worktree(feature/add-auth)
myproject-critical-bug/ # 热修复worktree(hotfix/critical-bug)
myproject-pr-456/ # PR审查worktree(review/pr-456)
命名规则:
- 模式:(使用名称部分,而非完整分支名)
- 分支名称:(例如)
- 目录名称仅使用部分以保持简洁
Feature worktree (default):
bash
> /worktrees create auth system
功能worktree(默认):
bash
> /worktrees create auth system
Branch: feature/auth-system
分支:feature/auth-system
Creates: ../myproject-auth-system
创建:../myproject-auth-system
**Fix worktree:**
```bash
> /worktrees create fix login error
**修复worktree:**
```bash
> /worktrees create fix login error
Branch: fix/login-error
分支:fix/login-error
Creates: ../myproject-login-error
创建:../myproject-login-error
**Refactor worktree:**
```bash
> /worktrees create refactor api layer
**重构worktree:**
```bash
> /worktrees create refactor api layer
Branch: refactor/api-layer
分支:refactor/api-layer
Creates: ../myproject-api-layer
创建:../myproject-api-layer
**Hotfix worktree:**
```bash
> /worktrees create hotfix critical bug
**热修复worktree:**
```bash
> /worktrees create hotfix critical bug
Branch: hotfix/critical-bug
分支:hotfix/critical-bug
Creates: ../myproject-critical-bug
创建:../myproject-critical-bug
**List existing worktrees:**
```bash
> /worktrees list
**列出现有worktree:**
```bash
> /worktrees list
Shows: git worktree list output
显示:git worktree list 输出
Setup Detection Examples
配置检测示例
Node.js project with pnpm:
Detected Node.js project with pnpm-lock.yaml
Installing dependencies with pnpm...
✓ Dependencies installed successfully
Python project:
Detected Python project with requirements.txt
Installing dependencies with pip...
✓ Dependencies installed successfully
Rust project:
Detected Rust project with Cargo.toml
Building project with cargo...
✓ Project built successfully
使用pnpm的Node.js项目:
检测到Node.js项目,存在pnpm-lock.yaml
正在使用pnpm安装依赖...
✓ 依赖安装成功
Python项目:
检测到Python项目,存在requirements.txt
正在使用pip安装依赖...
✓ 依赖安装成功
Rust项目:
检测到Rust项目,存在Cargo.toml
正在使用cargo构建项目...
✓ 项目构建成功
Quick Feature Branch
快速创建功能分支
bash
> /worktrees create new dashboard
bash
> /worktrees create new dashboard
Branch: feature/new-dashboard
分支:feature/new-dashboard
Creates worktree, installs dependencies, ready to code
创建worktree、安装依赖,准备就绪可开始编码
Hotfix While Feature In Progress
功能开发时创建热修复
In main worktree, working on feature
在主worktree中开发功能
/worktrees create hotfix critical bug
/worktrees create hotfix critical bug
Branch: hotfix/critical-bug
分支:hotfix/critical-bug
Creates separate worktree from main/master
基于main/master创建独立worktree
Fix bug in hotfix worktree
在热修复worktree中修复bug
Return to feature work when done
完成后返回功能开发
PR Review Without Stashing
无需暂存即可审查PR
bash
> /worktrees create review pr 123
bash
> /worktrees create review pr 123
Branch: review/pr-123
分支:review/pr-123
Creates worktree for reviewing PR
创建用于审查PR的worktree
Can run tests, inspect code
可运行测试、检查代码
Delete when review complete
审查完成后删除
Experiment or Spike
实验或探索性开发
bash
> /worktrees create spike new architecture
bash
> /worktrees create spike new architecture
Branch: spike/new-architecture
分支:spike/new-architecture
Creates isolated worktree for experimentation
创建隔离的worktree用于实验
Discard or merge based on results
根据结果决定丢弃或合并
-
Branch lock: Each branch can only be checked out in one worktree at a time. If a branch is already checked out, the command will inform you which worktree has it.
-
Shared .git: All worktrees share the same Git object database. Changes committed in any worktree are visible to all others.
-
Clean working directory: The command checks for uncommitted changes and warns if present, as creating worktrees is safest with a clean state.
-
Sibling directories: Worktrees are always created as sibling directories (using
) to keep the workspace organized. Never create worktrees inside the main repository.
-
Automatic dependency installation: The command automatically detects the project type and package manager, then runs the appropriate install command without prompting.
-
Remote tracking: For remote branches, worktrees are created with proper tracking setup (
flag) so pulls/pushes work correctly.
-
分支锁定:每个分支同一时间只能在一个worktree中检出。如果分支已被检出,命令会告知用户该分支所在的worktree。
-
共享.git:所有worktree共享同一个Git对象数据库。在任意worktree中提交的变更,对其他所有worktree可见。
-
干净的工作目录:命令会检查未提交变更并发出警告,因为在干净状态下创建worktree最安全。
-
同级目录:worktree始终创建为同级目录(使用
),以保持工作区整洁。切勿在主仓库内创建worktree。
-
自动依赖安装:命令自动检测项目类型和包管理器,无需提示即可运行对应的安装命令。
-
远程跟踪:对于远程分支,创建worktree时会配置正确的跟踪(
标志),以便拉取/推送正常工作。
When done with a worktree, use the proper removal command:
bash
git worktree remove ../myproject-add-auth
Or for a worktree with uncommitted changes:
bash
git worktree remove --force ../myproject-add-auth
Never use
to delete worktrees - always use
.
完成worktree使用后,使用正确的删除命令:
bash
git worktree remove ../myproject-add-auth
或者对于包含未提交变更的worktree:
bash
git worktree remove --force ../myproject-add-auth
"Branch is already checked out"
- Run to see where the branch is checked out
- Either work in that worktree or remove it first
"Cannot create worktree - path already exists"
- The target directory already exists
- Either remove it or choose a different worktree path
"Dependency installation failed"
- Navigate to the worktree manually:
- Run the install command directly to see full error output
- Common causes: missing system dependencies, network issues, corrupted lockfile
"Wrong type detected"
- The first word is used as the branch type if it's a known type
- To force a specific type, start with: , , , , , , ,
- Default type is when first word isn't a known type
"Branch is already checked out"
- 运行查看分支被检出的位置
- 要么在对应的worktree中操作,要么先删除它
"无法创建worktree - 路径已存在"
- 目标目录已存在
- 删除该目录或选择不同的worktree路径
"依赖安装失败"
- 手动导航到worktree:
- 直接运行安装命令查看完整错误输出
- 常见原因:缺失系统依赖、网络问题、锁定文件损坏
"检测到错误的类型"
- 如果第一个单词是已知类型,会被用作分支类型
- 要强制指定类型,以以下前缀开头:, , , , , , ,
- 当第一个单词不是已知类型时,默认类型为
How to Merge Worktree
如何合并Worktree
Workflow to help users merge changes from git worktrees into their current branch, supporting multiple merge strategies from simple file checkout to selective cherry-picking.
帮助用户将Git worktree中的变更合并到当前分支的工作流,支持从简单文件检出到选择性拣选的多种合并策略。
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Run
to show all existing worktrees and
to verify working directory state
-
Parse user input: Determine what merge operation the user wants:
- or no arguments: Guided interactive mode
- File/directory path: Merge specific file(s) or directory from a worktree
- Commit name: Cherry-pick a specific commit
- Branch name: Merge from that branch's worktree
- : Specify source worktree explicitly
- or : Use interactive patch selection mode
-
Determine source worktree/branch:
a. If user specified
: Use that worktree path directly
b. If user specified a branch name: Find worktree for that branch from
c. If only one other worktree exists: Ask to confirm using it as source
d. If multiple worktrees exist: Present list and ask user which to merge from
e. If no other worktrees exist: Explain and offer to use branch-based merge instead
-
Determine merge strategy: Present options based on user's needs:
Strategy A: Selective File Checkout (for specific files/directories)
- Best for: Getting complete file(s) from another branch
- Command:
git checkout <branch> -- <path>
Strategy B: Interactive Patch Selection (for partial file changes)
- Best for: Selecting specific hunks/lines from a file
- Command:
git checkout -p <branch> -- <path>
- Prompts user for each hunk: y (apply), n (skip), s (split), e (edit)
Strategy C: Cherry-Pick with Selective Staging (for specific commits)
- Best for: Applying a commit but excluding some changes
- Steps:
git cherry-pick --no-commit <commit>
- Review staged changes
git reset HEAD -- <unwanted-files>
to unstage
git checkout -- <unwanted-files>
to discard
Strategy D: Manual Merge with Conflicts (for complex merges)
- Best for: Full branch merge with control over resolution
- Steps:
git merge --no-commit <branch>
- Review all changes
- Selectively stage/unstage files
- Resolve conflicts if any
Strategy E: Multi-Worktree Selective Merge (combining from multiple sources)
- Best for: Taking different files from different worktrees
- Steps:
git checkout <branch1> -- <path1>
git checkout <branch2> -- <path2>
git commit -m "Merge selected files from multiple branches"
-
Execute the selected strategy:
- Run pre-merge comparison if user wants to review (suggest first)
- Execute git commands for the chosen strategy
- Handle any conflicts that arise
- Confirm changes before final commit
-
Post-merge summary: Display what was merged:
- Files changed/added/removed
- Source worktree/branch
- Merge strategy used
-
Cleanup prompt: After successful merge, ask:
- "Would you like to remove any worktrees to clean up local state?"
- If yes: List worktrees and ask which to remove
- Execute
git worktree remove <path>
for selected worktrees
- Remind about if needed
重要:严格按照以下步骤执行:
-
当前状态检查:运行
查看所有现有worktree,运行
验证工作目录状态
-
解析用户输入:确定用户想要的合并操作:
- 或无参数:引导式交互式模式
- 文件/目录路径:从worktree合并特定文件/目录
- 提交名称:拣选特定提交
- 分支名称:从该分支的worktree合并
- :显式指定源worktree
- 或:使用交互式补丁选择模式
-
确定源worktree/分支:
a. 如果用户指定
:直接使用该worktree路径
b. 如果用户指定分支名称:从
中找到该分支对应的worktree
c. 如果仅存在一个其他worktree:询问用户确认将其作为源
d. 如果存在多个worktree:列出所有选项并询问用户要从哪个合并
e. 如果不存在其他worktree:说明情况并建议使用基于分支的合并
-
确定合并策略:根据用户需求提供选项:
策略A:选择性文件检出(针对特定文件/目录)
- 适用场景:从其他分支获取完整文件
- 命令:
git checkout <branch> -- <path>
策略B:交互式补丁选择(针对文件的部分变更)
- 适用场景:从文件中选择特定代码块/行
- 命令:
git checkout -p <branch> -- <path>
- 提示用户对每个代码块进行选择:y(应用)、n(跳过)、s(拆分)、e(编辑)
策略C:带选择性暂存的拣选(针对特定提交)
- 适用场景:应用提交但排除部分变更
- 步骤:
git cherry-pick --no-commit <commit>
- 审查暂存的变更
git reset HEAD -- <unwanted-files>
取消暂存不需要的文件
git checkout -- <unwanted-files>
丢弃不需要的变更
策略D:带冲突处理的手动合并(针对复杂合并)
- 适用场景:完整分支合并并控制解决过程
- 步骤:
git merge --no-commit <branch>
- 审查所有变更
- 选择性暂存/取消暂存文件
- 解决冲突(如果有)
策略E:多Worktree选择性合并(从多个源合并)
- 适用场景:从不同worktree获取不同文件
- 步骤:
git checkout <branch1> -- <path1>
git checkout <branch2> -- <path2>
git commit -m "Merge selected files from multiple branches"
-
执行所选策略:
- 如果用户需要审查,先运行合并前对比(建议先使用)
- 执行所选策略对应的Git命令
- 处理出现的任何冲突
- 提交前确认变更
-
合并后摘要:显示合并内容:
- 变更/新增/删除的文件
- 源worktree/分支
- 使用的合并策略
-
清理提示:合并成功后询问:
- "是否要删除一些worktree以清理本地状态?"
- 如果是:列出worktree并询问要删除哪些
- 对所选worktree执行
git worktree remove <path>
- 提醒必要时使用
Merge Strategies Reference
合并策略参考
| Strategy | Use When | Command Pattern |
|---|
| Selective File | Need complete file(s) from another branch | git checkout <branch> -- <path>
|
| Interactive Patch | Need specific changes within a file | git checkout -p <branch> -- <path>
|
| Cherry-Pick Selective | Need a commit but not all its changes | git cherry-pick --no-commit
+ selective staging |
| Manual Merge | Full branch merge with control | + selective staging |
| Multi-Source | Combining files from multiple branches | Multiple git checkout <branch> -- <path>
|
| 策略 | 适用场景 | 命令模板 |
|---|
| 选择性文件 | 需要从其他分支获取完整文件 | git checkout <branch> -- <path>
|
| 交互式补丁 | 需要文件中的特定变更 | git checkout -p <branch> -- <path>
|
| 选择性拣选 | 需要提交但不需要其所有变更 | git cherry-pick --no-commit
+ 选择性暂存 |
| 手动合并 | 完整分支合并并需要控制过程 | + 选择性暂存 |
| 多源合并 | 从多个分支合并文件 | 多次执行git checkout <branch> -- <path>
|
Merge single file from worktree:
bash
> /worktrees merge src/app.js --from ../project-feature
从worktree合并单个文件:
bash
> /worktrees merge src/app.js --from ../project-feature
Prompts for merge strategy
提示选择合并策略
Executes: git checkout feature-branch -- src/app.js
执行:git checkout feature-branch -- src/app.js
**Interactive patch selection:**
```bash
> /worktrees merge src/utils.js --patch
**交互式补丁选择:**
```bash
> /worktrees merge src/utils.js --patch
Lists available worktrees to select from
列出可用worktree供选择
Runs: git checkout -p feature-branch -- src/utils.js
运行:git checkout -p feature-branch -- src/utils.js
User selects hunks interactively (y/n/s/e)
用户交互式选择代码块(y/n/s/e)
**Cherry-pick specific commit:**
```bash
> /worktrees merge abc1234
**拣选特定提交:**
```bash
> /worktrees merge abc1234
Detects commit hash
检测提交哈希
Asks: Apply entire commit or selective?
询问:应用完整提交还是选择性应用?
If selective: git cherry-pick --no-commit abc1234
如果选择选择性:git cherry-pick --no-commit abc1234
Then guides through unstaging unwanted changes
然后引导取消暂存不需要的变更
**Full guided mode:**
```bash
> /worktrees merge
**完整引导模式:**
```bash
> /worktrees merge
Lists all worktrees
列出所有worktree
Asks what to merge (files, commits, or branches)
询问要合并的内容(文件、提交或分支)
Guides through appropriate strategy
引导选择合适的策略
Offers cleanup at end
最后提供清理选项
**Directory merge with conflicts:**
```bash
> /worktrees merge src/components/ --from ../project-refactor
**带冲突的目录合并:**
```bash
> /worktrees merge src/components/ --from ../project-refactor
Strategy D: Manual merge with conflicts
策略D:带冲突处理的手动合并
git merge --no-commit refactor-branch
git merge --no-commit refactor-branch
Helps resolve any conflicts
帮助解决冲突
Reviews and commits selected changes
审查并提交所选变更
Interactive Patch Mode Guide
交互式补丁模式指南
When using
or Strategy B, the user sees prompts for each change hunk:
@@ -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,?]
| Key | Action |
|---|
| Apply this hunk |
| Skip this hunk |
| Quit (don't apply this or remaining hunks) |
| Apply this and all remaining hunks |
| Don't apply this or remaining hunks in this file |
| Split into smaller hunks |
| Manually edit the hunk |
| Show help |
@@ -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,?]
| 按键 | 操作 |
|---|
| 应用此代码块 |
| 跳过此代码块 |
| 退出(不应用此代码块及剩余代码块) |
| 应用此代码块及所有剩余代码块 |
| 不应用此代码块及此文件中的剩余代码块 |
| 拆分为更小的代码块 |
| 手动编辑代码块 |
| 显示帮助 |
Cherry-Pick Selective Workflow
选择性拣选工作流
For Strategy C (cherry-picking with selective staging):
1. Apply commit without committing
1. 应用提交但不提交
git cherry-pick --no-commit abc1234
git cherry-pick --no-commit abc1234
2. Check what was staged
2. 查看暂存的变更
3. Unstage files you don't want
3. 取消暂存不需要的文件
git reset HEAD -- path/to/unwanted.js
git reset HEAD -- path/to/unwanted.js
4. Discard changes to those files
4. 丢弃这些文件的变更
git checkout -- path/to/unwanted.js
git checkout -- path/to/unwanted.js
5. Commit the remaining changes
5. 提交剩余变更
git commit -m "Cherry-pick selected changes from abc1234"
git commit -m "Cherry-pick selected changes from abc1234"
Multi-Worktree Merge Workflow
多Worktree合并工作流
For Strategy E (merging from multiple worktrees):
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
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
git status
git diff --cached
git status
git diff --cached
Commit combined changes
提交合并后的变更
git commit -m "feat: combine auth, API, and UI improvements from feature branches"
git commit -m "feat: combine auth, API, and UI improvements from feature branches"
Take a Feature File Without Full Merge
不完整合并仅获取功能文件
bash
> /worktrees merge src/new-feature.js --from ../project-feature
bash
> /worktrees merge src/new-feature.js --from ../project-feature
Gets just the file, not the entire branch
仅获取该文件,而非整个分支
Partial Bugfix from Hotfix Branch
从热修复分支获取部分bug修复
bash
> /worktrees merge --patch src/utils.js --from ../project-hotfix
bash
> /worktrees merge --patch src/utils.js --from ../project-hotfix
Select only the specific bug fix hunks, not all changes
仅选择特定的bug修复代码块,而非所有变更
Combine Multiple PRs' Changes
合并多个PR的变更
bash
> /worktrees merge --interactive
bash
> /worktrees merge --interactive
Select specific files from PR-1 worktree
从PR-1 worktree选择特定文件
Select other files from PR-2 worktree
从PR-2 worktree选择其他文件
Combine into single coherent commit
合并为单个连贯提交
First review what will be merged
先审查要合并的内容
/worktrees compare src/module.js
/worktrees compare src/module.js
Then merge with confidence
然后放心合并
/worktrees merge src/module.js --from ../project-feature
/worktrees merge src/module.js --from ../project-feature
-
Working directory state: Always ensure your working directory is clean before merging. Uncommitted changes can cause conflicts.
-
Pre-merge review: Consider using
before merging to understand what changes will be applied.
-
Conflict resolution: If conflicts occur during merge, the command will help identify and resolve them before committing.
-
No-commit flag: Most strategies use
to give you control over the final commit message and what gets included.
-
Shared repository: All worktrees share the same Git object database, so commits made in any worktree are immediately visible to cherry-pick from any other.
-
Branch locks: Remember that branches can only be checked out in one worktree at a time. Use branch names for merge operations rather than creating duplicate worktrees.
-
工作目录状态:合并前始终确保工作目录干净。未提交变更可能导致冲突。
-
-
冲突解决:如果合并过程中出现冲突,命令会帮助识别并在提交前解决。
-
无提交标志:大多数策略使用
,让你控制最终的提交消息和要包含的内容。
-
共享仓库:所有worktree共享同一个Git对象数据库,因此在任意worktree中提交的变更,可立即在其他worktree中拣选。
-
分支锁定:记住分支同一时间只能在一个worktree中检出。合并操作使用分支名称,而非创建重复的worktree。
After merging, consider cleaning up worktrees that are no longer needed:
Remove specific worktree (clean state required)
删除特定worktree(需要干净状态)
git worktree remove ../project-feature
git worktree remove ../project-feature
Force remove (discards uncommitted changes)
强制删除(丢弃未提交变更)
git worktree remove --force ../project-feature
git worktree remove --force ../project-feature
Clean up stale worktree references
清理过期的worktree引用
git worktree prune
The command will prompt you about cleanup after each successful merge to help maintain a tidy workspace.
git worktree prune
每次成功合并后,命令会提示你进行清理,以帮助保持工作区整洁。
"Cannot merge: working directory has uncommitted changes"
- Commit or stash your current changes first
- Or use before merge, after
"Merge conflict in <file>"
- The command will show conflicted files
- Open files and resolve conflicts (look for markers)
- Stage resolved files with
- Continue with
"Commit not found" when cherry-picking
- Ensure the commit hash is correct
- Run in any worktree to find commits
- Commits are shared across all worktrees
"Cannot checkout: file exists in working tree"
- File has local modifications
- Either commit, stash, or discard local changes first
- Then retry the merge operation
"Branch not found for worktree"
- The specified worktree may have been removed
- Run to see current worktrees
- Use to clean up stale references
"无法合并:工作目录存在未提交变更"
"Merge conflict in <file>"
- 命令会显示冲突文件
- 打开文件并解决冲突(查找标记)
- 使用暂存已解决的文件
- 使用继续
"拣选时提示Commit not found"
- 确保提交哈希正确
- 在任意worktree中运行查找提交
- 提交在所有worktree中共享
"Cannot checkout: file exists in working tree"
- 文件存在本地修改
- 先提交、暂存或丢弃本地变更
- 然后重试合并操作
"Branch not found for worktree"
- 指定的worktree可能已被删除
- 运行查看当前worktree
- 使用清理过期引用
Integration with Other Commands
与其他命令集成
Pre-merge review:
bash
> /worktrees compare src/
> /worktrees merge src/specific-file.js
Create worktree, merge, cleanup:
bash
> /worktrees create feature-branch
> /worktrees compare src/
> /worktrees merge src/module.js --from ../project-feature-branch
合并前审查:
bash
> /worktrees compare src/
> /worktrees merge src/specific-file.js
创建worktree、合并、清理:
bash
> /worktrees create feature-branch
> /worktrees compare src/
> /worktrees merge src/module.js --from ../project-feature-branch
After merge, cleanup is offered automatically
合并后会自动提示清理