git-worktrees
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Worktrees
Git Worktree
Overview
概述
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。通过切换目录而非切换分支来切换上下文。
Core Concepts
核心概念
| Concept | Description |
|---|---|
| Main worktree | Original working directory from |
| 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 |
| 概念 | 描述 |
|---|---|
| 主worktree | 由 |
| 关联worktree | 使用 |
共享 | 所有worktree共享同一个Git对象数据库(无重复存储) |
| 分支锁定 | 每个分支同一时间只能在一个worktree中检出 |
| Worktree元数据 | |
Quick Reference
快速参考
| Task | Command |
|---|---|
| Create worktree (existing branch) | |
| Create worktree (new branch) | |
| Create worktree (new branch from ref) | |
| Create detached worktree | |
| List all worktrees | |
| Remove worktree | |
| Force remove worktree | |
| Move worktree | |
| Lock worktree | |
| Unlock worktree | |
| Prune stale worktrees | |
| Repair worktree links | |
| Compare files between worktrees | |
| Get one file from another branch | |
| Get partial file changes | |
| Cherry-pick a commit | |
| Cherry-pick without committing | |
| Merge without auto-commit | |
| 任务 | 命令 |
|---|---|
| 创建worktree(已有分支) | |
| 创建worktree(新分支) | |
| 基于引用创建worktree(新分支) | |
| 创建分离头指针的worktree | |
| 列出所有worktree | |
| 删除worktree | |
| 强制删除worktree | |
| 移动worktree | |
| 锁定worktree | |
| 解锁worktree | |
| 清理过期worktree | |
| 修复worktree链接 | |
| 对比不同worktree的文件 | |
| 从其他分支获取单个文件 | |
| 获取文件的部分变更 | |
| 拣选提交 | |
| 拣选提交但不自动提交 | |
| 合并但不自动提交 | |
Essential Commands
关键命令
Create a Worktree
创建Worktree
bash
undefinedbash
undefinedCreate 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
undefinedgit worktree add --detach ../experiment HEAD~5
undefinedList Worktrees
列出Worktree
bash
undefinedbash
undefinedSimple list
简洁列表
git worktree list
git worktree list
Verbose output with additional details
包含额外详情的 verbose 输出
git worktree list -v
git worktree list -v
Machine-readable format (for scripting)
机器可读格式(用于脚本)
git worktree list --porcelain
**Example output:**
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
undefinedgit worktree list --porcelain
**示例输出:**
/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]
undefinedRemove a Worktree
删除Worktree
bash
undefinedbash
undefinedRemove 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
undefinedgit worktree remove --force ../feature-x
undefinedMove a Worktree
移动Worktree
bash
undefinedbash
undefinedRelocate worktree to new path
将worktree迁移到新路径
git worktree move ../old-path ../new-path
undefinedgit worktree move ../old-path ../new-path
undefinedLock/Unlock Worktrees
锁定/解锁Worktree
bash
undefinedbash
undefinedLock 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
undefinedgit worktree unlock ../feature-x
undefinedPrune Stale Worktrees
清理过期Worktree
bash
undefinedbash
undefinedRemove stale worktree metadata (after manual directory deletion)
清理过期的worktree元数据(手动删除目录后)
git worktree prune
git worktree prune
Dry-run to see what would be pruned
试运行,查看会被清理的内容
git worktree prune --dry-run
git worktree prune --dry-run
Verbose output
verbose输出
git worktree prune -v
undefinedgit worktree prune -v
undefinedRepair Worktrees
修复Worktree
bash
undefinedbash
undefinedRepair worktree links after moving directories manually
手动移动目录后修复worktree链接
git worktree repair
git worktree repair
Repair specific worktree
修复指定的worktree
git worktree repair ../feature-x
undefinedgit worktree repair ../feature-x
undefinedWorkflow Patterns
工作流模式
Pattern 1: Feature + Hotfix in Parallel
模式1:功能开发与热修复并行
To fix a bug while feature work is in progress:
bash
undefined在开发功能时修复bug:
bash
undefinedCreate 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
返回功能开发目录
cd ../project
cd ../project
Clean up when done
完成后清理
git worktree remove ../project-hotfix
undefinedgit worktree remove ../project-hotfix
undefinedPattern 2: PR Review While Working
模式2:开发时审查PR
To review a PR without affecting current work:
bash
undefined在不影响当前工作的情况下审查PR:
bash
undefinedFetch 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
审查:运行测试、检查代码
cd ../project-review
cd ../project-review
Return to work, then clean up
返回工作目录,然后清理
cd ../project
git worktree remove ../project-review
git branch -d pr-123
undefinedcd ../project
git worktree remove ../project-review
git branch -d pr-123
undefinedPattern 3: Compare Implementations
模式3:对比不同实现
To compare code across branches side-by-side:
bash
undefined并排对比不同分支的代码:
bash
undefinedCreate 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
Clean up
清理
git worktree remove ../project-v1
git worktree remove ../project-v2
undefinedgit worktree remove ../project-v1
git worktree remove ../project-v2
undefinedPattern 4: Long-Running Tasks
模式4:长时间运行任务
To run tests/builds in isolation while continuing development:
bash
undefined在隔离环境中运行测试/构建,同时继续开发:
bash
undefinedCreate 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中继续开发
cd ../project
undefinedcd ../project
undefinedPattern 5: Stable Reference
模式5:稳定参考分支
To maintain a clean main checkout for reference:
bash
undefined维护一个干净的main分支检出作为参考:
bash
undefinedCreate 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
undefinedgit worktree lock --reason "Reference checkout" ../project-main
undefinedPattern 6: Selective Merging from Multiple Features
模式6:从多个功能分支选择性合并
To combine specific changes from multiple feature branches:
bash
undefined合并来自多个功能分支的特定变更:
bash
undefinedCreate 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
Clean up
清理
git worktree remove ../project-feature-1
git worktree remove ../project-feature-2
undefinedgit worktree remove ../project-feature-1
git worktree remove ../project-feature-2
undefinedComparing 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:
bash
undefinedworktree本质就是目录,你可以直接对比文件:
bash
undefinedCompare 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
undefineddiff -r ../project-v1/src ../project-v2/src
undefinedMerge Only One File from a Worktree
从Worktree合并单个文件
You can selectively bring a single file from another branch using :
git checkoutbash
undefined你可以使用从其他分支选择性获取单个文件:
git checkoutbash
undefinedIn 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):
```bashgit checkout feature-branch -- src/module.js src/utils.js
对于**部分文件变更**(仅特定代码块/行):
```bashInteractive 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 hunkgit 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:
bash
undefined拣选操作基于提交进行。由于所有worktree共享同一个仓库,你可以拣选任意提交:
bash
undefinedFind 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
将特定提交拣选到当前分支
git cherry-pick abc1234
git cherry-pick abc1234
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
undefinedgit cherry-pick --no-commit abc1234
undefinedMerge Changes from Multiple Worktrees
从多个Worktree合并变更
You can merge or cherry-pick from multiple branches:
bash
undefined你可以从多个分支合并或拣选变更:
bash
undefinedMerge 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
undefinedgit cherry-pick abc1234 # 来自feature-1
git cherry-pick def5678 # 来自feature-2
undefinedSelective Merging - Pick Which Changes to Include
选择性合并 - 选择要包含的变更
Option 1: Selective File Checkout
选项1:选择性文件检出
bash
undefinedbash
undefinedGet 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"
undefinedgit checkout feature-1 -- src/moduleA.js
git checkout feature-2 -- src/moduleB.js
git commit -m "Merge selected files from feature branches"
undefinedOption 2: Interactive Patch Selection
选项2:交互式补丁选择
bash
undefinedbash
undefinedSelect specific hunks from a file
选择文件中的特定代码块
git checkout -p feature-1 -- src/shared.js
undefinedgit checkout -p feature-1 -- src/shared.js
undefinedOption 3: Cherry-Pick with Selective Staging
选项3:带选择性暂存的拣选
bash
undefinedbash
undefinedApply 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"
undefinedgit commit -m "Selected changes from feature-1"
undefinedOption 4: Merge with Manual Selection
选项4:手动选择合并
bash
undefinedbash
undefinedStart 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"
undefinedgit commit -m "Merge selected changes from feature-1"
undefinedOption 5: Using git restore (Git 2.23+)
选项5:使用git restore(Git 2.23+)
bash
undefinedbash
undefinedRestore 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
undefinedgit restore -p --source=feature-branch -- path/to/file.js
undefinedDirectory 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 worktreeNaming convention: or
<project>-<purpose><project>-<branch>有规律地组织worktree:
~/projects/
myproject/ # 主worktree(main/master分支)
myproject-feature-x/ # 功能分支worktree
myproject-hotfix/ # 热修复worktree
myproject-review/ # 临时PR审查worktree命名规范: 或
<project>-<purpose><project>-<branch>Best Practices
最佳实践
| Practice | Rationale |
|---|---|
| Use sibling directories | Keep worktrees at same level as main project for easy navigation |
| Name by purpose | |
| Clean up promptly | Remove worktrees when done to avoid confusion |
| Lock remote worktrees | Prevent pruning if worktree is on network/USB storage |
Use | 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:
bash
undefined原因: 尝试检出已在另一个worktree中激活的分支。
解决方案:
bash
undefinedFind where the branch is checked out
查找分支被检出的位置
git worktree list
git worktree list
Either work in that worktree or remove it first
要么在对应的worktree中操作,要么先删除它
git worktree remove ../other-worktree
undefinedgit worktree remove ../other-worktree
undefinedIssue: Stale worktree after manual deletion
问题:手动删除后worktree过期
Cause: Deleted worktree directory without using .
git worktree removeSolution:
bash
undefined原因: 未使用就删除了worktree目录。
git worktree remove解决方案:
bash
undefinedClean up stale metadata
清理过期的元数据
git worktree prune
undefinedgit worktree prune
undefinedIssue: Worktree moved manually
问题:手动移动了worktree
Cause: Moved worktree directory without using .
git worktree moveSolution:
bash
undefined原因: 未使用就移动了worktree目录。
git worktree move解决方案:
bash
undefinedRepair the worktree links
修复worktree链接
git worktree repair
git worktree repair
Or specify the new path
或者指定新路径
git worktree repair /new/path/to/worktree
undefinedgit worktree repair /new/path/to/worktree
undefinedIssue: Worktree on removed drive
问题:worktree所在驱动器已移除
Cause: Worktree was on removable storage that's no longer connected.
Solution:
bash
undefined原因: worktree所在的可移动存储已断开连接。
解决方案:
bash
undefinedIf temporary, lock it to prevent pruning
如果是临时情况,锁定以防止被清理
git worktree lock ../usb-worktree
git worktree lock ../usb-worktree
If permanent, prune it
如果是永久移除,清理它
git worktree prune
undefinedgit worktree prune
undefinedCommon Mistakes
常见错误
| Mistake | Fix |
|---|---|
Using | Always use |
| Forgetting branch is locked to worktree | Run |
| Not cleaning up temporary worktrees | Remove worktrees immediately after task completion |
| Creating worktrees in nested locations | Use sibling directories ( |
| Moving worktree directory manually | Use |
| 错误 | 修复方法 |
|---|---|
使用 | 始终使用 |
| 忘记分支已被worktree锁定 | 在出现检出错误前,先运行 |
| 未清理临时worktree | 任务完成后立即删除worktree |
| 在嵌套位置创建worktree | 使用同级目录( |
| 手动移动worktree目录 | 使用 |
Agent Workflow Integration
Agent工作流集成
To isolate parallel agent tasks:
bash
undefined隔离并行Agent任务:
bash
undefinedCreate 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:
```bashcd ../project
使用分离头指针安全实验:
```bashCreate 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
undefinedgit worktree remove --force ../project-experiment
undefinedVerification Checklist
验证清单
Before using worktrees:
- Understand that branches can only be checked out in one worktree
- Know where worktrees will be created (use sibling directories)
- Plan cleanup strategy for temporary worktrees
When creating worktrees:
- Use descriptive directory names
- Verify branch is not already checked out elsewhere
- Consider using for experiments
--detach
When removing worktrees:
- Commit or stash any uncommitted changes
- Use , not
git worktree removerm -rf - Run if directory was deleted manually
git worktree prune
使用worktree前:
- 理解分支同一时间只能在一个worktree中检出
- 确定worktree的创建位置(使用同级目录)
- 规划临时worktree的清理策略
创建worktree时:
- 使用描述性目录名称
- 验证分支未在其他位置检出
- 考虑为实验使用
--detach
删除worktree时:
- 提交或暂存所有未提交变更
- 使用而非
git worktree removerm -rf - 如果手动删除了目录,运行
git worktree prune
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的代码差异。
Instructions
步骤说明
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Runto show all existing worktrees and their locations
git worktree list -
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)
--stat - Worktree path: A path that matches one of the worktree roots from
git worktree list - 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 fromc. 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
git worktree listgit diff -
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:bashdiff -r <worktree1>/<directory> <worktree2>/<directory> # Or for summary only: diff -rq <worktree1>/<directory> <worktree2>/<directory>For branch-level comparison (using git diff):bashgit diff <branch1>..<branch2> -- <path> # Or for stat summary: git diff --stat <branch1>..<branch2>For comparing with current working directory:bashdiff <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及其位置
git worktree list -
解析用户输入:对每个提供的参数进行分类:
- 无参数:交互式模式 - 询问用户要对比的内容
- :显示差异的汇总统计信息(变更文件数、插入行数、删除行数)
--stat - Worktree路径:与输出中某个worktree根目录匹配的路径
git worktree list - 分支名称:与某个worktree中分支匹配的名称
- 文件/目录路径:当前worktree中要对比的路径
-
确定对比目标(要对比的worktree): a. 如果用户提供了worktree路径:将这些作为对比目标 b. 如果用户指定了分支名称:从中找到对应分支的worktree c. 如果除当前外仅存在一个worktree:将当前和该worktree作为对比目标 d. 如果存在多个worktree且未指定:列出所有选项并询问用户要对比哪些 e. 如果不存在其他worktree:建议使用
git worktree list对比分支git diff -
确定对比内容(worktree内的文件/目录): a. 如果用户指定了文件/目录路径:对比所有指定路径 b. 如果未指定具体路径:询问用户:
- "是否对比整个worktree?" 或
- "是否对比特定文件/目录?(输入路径)"
-
执行对比:对比不同worktree的特定文件:bash
diff <worktree1>/<path> <worktree2>/<path> # 或者使用统一差异格式: diff -u <worktree1>/<path> <worktree2>/<path>对比不同worktree的目录:bashdiff -r <worktree1>/<directory> <worktree2>/<directory> # 或者仅显示摘要: diff -rq <worktree1>/<directory> <worktree2>/<directory>基于分支的对比(使用git diff):bashgit diff <branch1>..<branch2> -- <path> # 或者显示统计摘要: git diff --stat <branch1>..<branch2>与当前工作目录对比:bashdiff <current-file> <other-worktree>/<file> -
格式化并展示结果:
- 显示清晰的标题,说明正在对比的内容
- 对于大型差异,先提供摘要选项
- 突出重要变更(新增文件、删除文件、重命名文件)
- 提供每个worktree对应分支的上下文信息
Comparison Modes
对比模式
| Mode | Description | Command Pattern |
|---|---|---|
| File diff | Compare single file between worktrees | |
| Directory diff | Compare directories recursively | |
| Summary only | Show which files differ (no content) | |
| Git diff | Use git's diff (branch-based) | |
| Stat view | Show change statistics | |
| 模式 | 描述 | 命令模板 |
|---|---|---|
| 文件差异 | 对比不同worktree的单个文件 | |
| 目录差异 | 递归对比目录 | |
| 仅摘要 | 显示哪些文件不同(不显示内容) | |
| Git差异 | 使用Git的diff功能(基于分支) | |
| 统计视图 | 显示变更统计信息 | |
Worktree Detection
Worktree检测
The command finds worktrees using :
git worktree list/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)
命令通过查找worktree:
git worktree list/home/user/project abc1234 [main]
/home/user/project-feature def5678 [feature-x]
/home/user/project-hotfix ghi9012 [hotfix-123]从该输出中,命令提取:
- 路径:worktree目录的绝对路径
- 分支:括号中的分支名称(当用户指定分支名称时使用)
Examples
示例
Compare specific file between worktrees:
bash
> /worktrees compare src/app.js对比不同worktree的特定文件:
bash
> /worktrees compare src/app.jsPrompts 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.jsCompares 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.jsonShows 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 --statShows which files differ and line counts
显示哪些文件不同以及行数统计
**Interactive mode:**
```bash
> /worktrees compare
**交互式模式:**
```bash
> /worktrees compareLists 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-xFinds 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/目录
undefinedundefinedOutput Format
输出格式
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个文件删除Common Workflows
常见工作流
Review Feature Changes
审查功能变更
bash
undefinedbash
undefinedSee what changed in a feature branch
查看功能分支的变更
/worktrees compare --stat /worktrees compare src/components/
undefined/worktrees compare --stat /worktrees compare src/components/
undefinedCompare Implementations
对比不同实现
bash
undefinedbash
undefinedCompare how two features implemented similar functionality
对比两个功能分支对相似功能的实现
/worktrees compare ../project-feature-1 ../project-feature-2 src/auth/
undefined/worktrees compare ../project-feature-1 ../project-feature-2 src/auth/
undefinedQuick File Check
快速文件检查
bash
undefinedbash
undefinedCheck if a specific file differs
检查特定文件是否存在差异
/worktrees compare package.json
undefined/worktrees compare package.json
undefinedPre-Merge Review
合并前审查
bash
undefinedbash
undefinedReview 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/目录都会被对比
undefinedundefinedImportant Notes
重要说明
-
Argument detection: The command auto-detects argument types by comparing them againstoutput:
git worktree list- 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.,)
../project-feature -
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 usinginstead.
git diff -
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 usefor branch comparison instead.
git diff
-
参数检测:命令通过与输出对比,自动检测参数类型:
git worktree list- 匹配worktree根目录的路径 → 作为要对比的worktree
- 匹配worktree中分支的名称 → 作为要对比的worktree
- 其他路径 → 作为要在worktree间对比的文件/目录
-
多路径支持:当提供多个文件/目录路径时,所有路径都会在所选worktree间进行对比(而非仅第一个)。
-
Worktree路径:指定worktree时,使用完整路径或相对于当前目录的路径(例如)
../project-feature -
分支与Worktree:如果指定分支名称,命令会查找检出该分支的worktree。如果该分支没有对应的worktree,会建议使用。
git diff -
大型差异:对于大型目录,命令会先提供摘要选项,再显示完整差异输出。
-
二进制文件:会自动检测二进制文件,并提示"Binary files differ",不显示实际差异内容。
-
文件权限:如果文件权限不同,差异结果中也会显示。
-
无worktree:如果不存在其他worktree,命令会说明如何创建worktree,并建议使用进行分支对比。
git diff
Integration with Create Worktree
与创建Worktree集成
Use first to set up worktrees for comparison:
/worktrees createbash
undefined先使用创建worktree,再进行对比:
/worktrees createbash
undefinedCreate 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
Now compare
现在进行对比
/worktrees compare src/
undefined/worktrees compare src/
undefinedTroubleshooting
故障排除
"No other worktrees found"
- Create a worktree first with
/worktrees create <branch> - Or use for branch-only comparison without worktrees
git diff
"Worktree for branch not found"
- The branch may not have a worktree created
- Run to see available worktrees
git worktree list - 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"
- 先使用创建worktree
/worktrees create <branch> - 或者使用进行仅分支的对比,无需worktree
git diff
"未找到分支对应的worktree"
- 该分支可能没有创建对应的worktree
- 运行查看可用worktree
git worktree list - 使用创建worktree
/worktrees create <branch>
"路径在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以支持并行开发的工作流,可自动检测并安装项目依赖。
Instructions
步骤说明
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Runto show existing worktrees and
git worktree listto verify the repository state is clean (no uncommitted changes that might cause issues)git status -
Fetch latest remote branches: Runto ensure local has knowledge of all remote branches
git fetch --all -
Parse user input: Determine what the user wants to create:
- : Create worktree with auto-detected type prefix
<name> - : Just show existing worktrees and exit
--list - 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.
feature/Known types:,feature,feat,fix,bug,bugfix,hotfix,release,docs,test,refactor,chore,spike,experimentreviewExamples:- →
refactor auth systemrefactor/auth-system - →
fix login bugfix/login-bug - →
auth system(default)feature/auth-system - →
hotfix critical errorhotfix/critical-error
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:
- (e.g.,
<prefix>/<normalized-name>)feature/auth-system
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../<project-name>-<name>- Extract project name from current directory
- Use the normalized name (NOT the full branch with prefix)
- Example: →
feature/auth-system../myproject-auth-system
d. Create the worktree: Execute the appropriate git worktree add commande. Dependency detection: Check the new worktree for dependency files and determine if setup is needed:- -> Node.js project (npm/yarn/pnpm/bun)
package.json - or
requirements.txtorpyproject.toml-> Python projectsetup.py - -> Rust project
Cargo.toml - -> Go project
go.mod - -> Ruby project
Gemfile - -> PHP project
composer.json
f. Package manager detection (for Node.js projects):- -> Use
bun.lockbbun install - -> Use
pnpm-lock.yamlpnpm install - -> Use
yarn.lockyarn install - or default -> Use
package-lock.jsonnpm install
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:
cd <worktree-path>
重要:严格按照以下步骤执行:
-
当前状态检查:运行查看现有worktree,运行
git worktree list验证仓库状态干净(无未提交变更,避免出现问题)git status -
获取最新远程分支:运行确保本地知晓所有远程分支
git fetch --all -
解析用户输入:确定用户要创建的内容:
- :创建带有自动检测类型前缀的worktree
<name> - :仅显示现有worktree并退出
--list - 无输入:交互式询问用户名称
-
从名称自动检测分支类型:检查第一个单词是否为已知分支类型。如果是,将其作为前缀,剩余部分作为名称。如果不是,默认使用。
feature/已知类型:,feature,feat,fix,bug,bugfix,hotfix,release,docs,test,refactor,chore,spike,experimentreview示例:- →
refactor auth systemrefactor/auth-system - →
fix login bugfix/login-bug - →
auth system(默认)feature/auth-system - →
hotfix critical errorhotfix/critical-error
名称规范化: 将空格转换为连字符,转为小写,移除除连字符/下划线外的特殊字符 -
创建每个worktree: a. 分支名称构建:从检测到的类型和规范化名称构建完整分支名称:
- (例如
<prefix>/<normalized-name>)feature/auth-system
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>
c. 路径规范:使用同级目录,模式为../<project-name>-<name>- 从当前目录提取项目名称
- 使用规范化名称(而非带前缀的完整分支名)
- 示例:→
feature/auth-system../myproject-auth-system
d. 创建worktree:执行对应的git worktree add命令e. 依赖检测:检查新worktree的依赖文件,确定是否需要配置:- → Node.js项目(npm/yarn/pnpm/bun)
package.json - 或
requirements.txt或pyproject.toml→ Python项目setup.py - → Rust项目
Cargo.toml - → Go项目
go.mod - → Ruby项目
Gemfile - → PHP项目
composer.json
f. 包管理器检测(针对Node.js项目):- → 使用
bun.lockbbun install - → 使用
pnpm-lock.yamlpnpm install - → 使用
yarn.lockyarn install - 或默认 → 使用
package-lock.jsonnpm install
g. 自动配置:自动运行依赖安装:- 切换到worktree目录并运行检测到的安装命令
- 报告进度:"正在使用[包管理器]安装依赖..."
- 如果安装失败,报告错误但继续显示worktree创建摘要
-
摘要:显示已创建worktree的摘要:
- Worktree路径
- 分支名称(带前缀的完整名称)
- 配置状态(依赖安装成功或失败)
- 快速导航命令:
cd <worktree-path>
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)
<project-name>-<name> - Branch name: (e.g.,
<type-prefix>/<name>)feature/add-auth - Directory name uses only the portion for brevity
<name>
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)命名规则:
- 模式:(使用名称部分,而非完整分支名)
<project-name>-<name> - 分支名称:(例如
<type-prefix>/<name>)feature/add-auth - 目录名称仅使用部分以保持简洁
<name>
Examples
示例
Feature worktree (default):
bash
> /worktrees create auth system功能worktree(默认):
bash
> /worktrees create auth systemBranch: 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 errorBranch: 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 layerBranch: 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 bugBranch: hotfix/critical-bug
分支:hotfix/critical-bug
Creates: ../myproject-critical-bug
创建:../myproject-critical-bug
**List existing worktrees:**
```bash
> /worktrees list
**列出现有worktree:**
```bash
> /worktrees listShows: git worktree list output
显示:git worktree list 输出
undefinedundefinedSetup Detection Examples
配置检测示例
Node.js project with pnpm:
Detected Node.js project with pnpm-lock.yaml
Installing dependencies with pnpm...
✓ Dependencies installed successfullyPython project:
Detected Python project with requirements.txt
Installing dependencies with pip...
✓ Dependencies installed successfullyRust 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构建项目...
✓ 项目构建成功Common Workflows
常见工作流
Quick Feature Branch
快速创建功能分支
bash
> /worktrees create new dashboardbash
> /worktrees create new dashboardBranch: feature/new-dashboard
分支:feature/new-dashboard
Creates worktree, installs dependencies, ready to code
创建worktree、安装依赖,准备就绪可开始编码
undefinedundefinedHotfix While Feature In Progress
功能开发时创建热修复
bash
undefinedbash
undefinedIn 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
完成后返回功能开发
undefinedundefinedPR Review Without Stashing
无需暂存即可审查PR
bash
> /worktrees create review pr 123bash
> /worktrees create review pr 123Branch: review/pr-123
分支:review/pr-123
Creates worktree for reviewing PR
创建用于审查PR的worktree
Can run tests, inspect code
可运行测试、检查代码
Delete when review complete
审查完成后删除
undefinedundefinedExperiment or Spike
实验或探索性开发
bash
> /worktrees create spike new architecturebash
> /worktrees create spike new architectureBranch: spike/new-architecture
分支:spike/new-architecture
Creates isolated worktree for experimentation
创建隔离的worktree用于实验
Discard or merge based on results
根据结果决定丢弃或合并
undefinedundefinedImportant Notes
重要说明
-
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.
--track
-
分支锁定:每个分支同一时间只能在一个worktree中检出。如果分支已被检出,命令会告知用户该分支所在的worktree。
-
共享.git:所有worktree共享同一个Git对象数据库。在任意worktree中提交的变更,对其他所有worktree可见。
-
干净的工作目录:命令会检查未提交变更并发出警告,因为在干净状态下创建worktree最安全。
-
同级目录:worktree始终创建为同级目录(使用),以保持工作区整洁。切勿在主仓库内创建worktree。
../ -
自动依赖安装:命令自动检测项目类型和包管理器,无需提示即可运行对应的安装命令。
-
远程跟踪:对于远程分支,创建worktree时会配置正确的跟踪(标志),以便拉取/推送正常工作。
--track
Cleanup
清理
When done with a worktree, use the proper removal command:
bash
git worktree remove ../myproject-add-authOr for a worktree with uncommitted changes:
bash
git worktree remove --force ../myproject-add-authNever use to delete worktrees - always use .
rm -rfgit worktree remove完成worktree使用后,使用正确的删除命令:
bash
git worktree remove ../myproject-add-auth或者对于包含未提交变更的worktree:
bash
git worktree remove --force ../myproject-add-auth切勿使用删除worktree - 始终使用。
rm -rfgit worktree removeTroubleshooting
故障排除
"Branch is already checked out"
- Run to see where the branch is checked out
git worktree list - 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:
cd ../myproject-<name> - 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: ,
fix,hotfix,docs,test,refactor,chore,spikereview - Default type is when first word isn't a known type
feature/
"Branch is already checked out"
- 运行查看分支被检出的位置
git worktree list - 要么在对应的worktree中操作,要么先删除它
"无法创建worktree - 路径已存在"
- 目标目录已存在
- 删除该目录或选择不同的worktree路径
"依赖安装失败"
- 手动导航到worktree:
cd ../myproject-<name> - 直接运行安装命令查看完整错误输出
- 常见原因:缺失系统依赖、网络问题、锁定文件损坏
"检测到错误的类型"
- 如果第一个单词是已知类型,会被用作分支类型
- 要强制指定类型,以以下前缀开头:,
fix,hotfix,docs,test,refactor,chore,spikereview - 当第一个单词不是已知类型时,默认类型为
feature/
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中的变更合并到当前分支的工作流,支持从简单文件检出到选择性拣选的多种合并策略。
Instructions
步骤说明
CRITICAL: Perform the following steps exactly as described:
-
Current state check: Runto show all existing worktrees and
git worktree listto verify working directory stategit status -
Parse user input: Determine what merge operation the user wants:
- or no arguments: Guided interactive mode
--interactive - 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
--from <worktree> - or
--patch: Use interactive patch selection mode-p
-
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
--from <worktree>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 insteadgit worktree list -
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
- to unstage
git reset HEAD -- <unwanted-files> - to discard
git checkout -- <unwanted-files> git commit -m "message"
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
git commit -m "message"
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)
/worktrees compare - Execute git commands for the chosen strategy
- Handle any conflicts that arise
- Confirm changes before final commit
- Run pre-merge comparison if user wants to review (suggest
-
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 for selected worktrees
git worktree remove <path> - Remind about if needed
git worktree prune
重要:严格按照以下步骤执行:
-
当前状态检查:运行查看所有现有worktree,运行
git worktree list验证工作目录状态git status -
解析用户输入:确定用户想要的合并操作:
- 或无参数:引导式交互式模式
--interactive - 文件/目录路径:从worktree合并特定文件/目录
- 提交名称:拣选特定提交
- 分支名称:从该分支的worktree合并
- :显式指定源worktree
--from <worktree> - 或
--patch:使用交互式补丁选择模式-p
-
确定源worktree/分支: a. 如果用户指定:直接使用该worktree路径 b. 如果用户指定分支名称:从
--from <worktree>中找到该分支对应的worktree c. 如果仅存在一个其他worktree:询问用户确认将其作为源 d. 如果存在多个worktree:列出所有选项并询问用户要从哪个合并 e. 如果不存在其他worktree:说明情况并建议使用基于分支的合并git worktree list -
确定合并策略:根据用户需求提供选项:策略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> git commit -m "message"
策略D:带冲突处理的手动合并(针对复杂合并)- 适用场景:完整分支合并并控制解决过程
- 步骤:
git merge --no-commit <branch>- 审查所有变更
- 选择性暂存/取消暂存文件
- 解决冲突(如果有)
git commit -m "message"
策略E:多Worktree选择性合并(从多个源合并)- 适用场景:从不同worktree获取不同文件
- 步骤:
git checkout <branch1> -- <path1>git checkout <branch2> -- <path2>git commit -m "Merge selected files from multiple branches"
-
执行所选策略:
- 如果用户需要审查,先运行合并前对比(建议先使用)
/worktrees compare - 执行所选策略对应的Git命令
- 处理出现的任何冲突
- 提交前确认变更
- 如果用户需要审查,先运行合并前对比(建议先使用
-
合并后摘要:显示合并内容:
- 变更/新增/删除的文件
- 源worktree/分支
- 使用的合并策略
-
清理提示:合并成功后询问:
- "是否要删除一些worktree以清理本地状态?"
- 如果是:列出worktree并询问要删除哪些
- 对所选worktree执行
git worktree remove <path> - 提醒必要时使用
git worktree prune
Merge Strategies Reference
合并策略参考
| Strategy | Use When | Command Pattern |
|---|---|---|
| Selective File | Need complete file(s) from another branch | |
| Interactive Patch | Need specific changes within a file | |
| Cherry-Pick Selective | Need a commit but not all its changes | |
| Manual Merge | Full branch merge with control | |
| Multi-Source | Combining files from multiple branches | Multiple |
| 策略 | 适用场景 | 命令模板 |
|---|---|---|
| 选择性文件 | 需要从其他分支获取完整文件 | |
| 交互式补丁 | 需要文件中的特定变更 | |
| 选择性拣选 | 需要提交但不需要其所有变更 | |
| 手动合并 | 完整分支合并并需要控制过程 | |
| 多源合并 | 从多个分支合并文件 | 多次执行 |
Examples
示例
Merge single file from worktree:
bash
> /worktrees merge src/app.js --from ../project-feature从worktree合并单个文件:
bash
> /worktrees merge src/app.js --from ../project-featurePrompts 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 --patchLists 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 abc1234Detects 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 mergeLists 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-refactorStrategy 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
审查并提交所选变更
undefinedundefinedInteractive Patch Mode Guide
交互式补丁模式指南
When using or Strategy B, the user sees prompts for each change hunk:
--patch@@ -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 |
使用或策略B时,用户会看到每个变更代码块的提示:
--patch@@ -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):
bash
undefined对于策略C(带选择性暂存的拣选):
bash
undefined1. Apply commit without committing
1. 应用提交但不提交
git cherry-pick --no-commit abc1234
git cherry-pick --no-commit abc1234
2. Check what was staged
2. 查看暂存的变更
git status
git status
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"
undefinedgit commit -m "Cherry-pick selected changes from abc1234"
undefinedMulti-Worktree Merge Workflow
多Worktree合并工作流
For Strategy E (merging from multiple worktrees):
bash
undefined对于策略E(从多个worktree合并):
bash
undefinedGet 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
Review all changes
审查所有变更
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"
undefinedgit commit -m "feat: combine auth, API, and UI improvements from feature branches"
undefinedCommon Workflows
常见工作流
Take a Feature File Without Full Merge
不完整合并仅获取功能文件
bash
> /worktrees merge src/new-feature.js --from ../project-featurebash
> /worktrees merge src/new-feature.js --from ../project-featureGets just the file, not the entire branch
仅获取该文件,而非整个分支
undefinedundefinedPartial Bugfix from Hotfix Branch
从热修复分支获取部分bug修复
bash
> /worktrees merge --patch src/utils.js --from ../project-hotfixbash
> /worktrees merge --patch src/utils.js --from ../project-hotfixSelect only the specific bug fix hunks, not all changes
仅选择特定的bug修复代码块,而非所有变更
undefinedundefinedCombine Multiple PRs' Changes
合并多个PR的变更
bash
> /worktrees merge --interactivebash
> /worktrees merge --interactiveSelect specific files from PR-1 worktree
从PR-1 worktree选择特定文件
Select other files from PR-2 worktree
从PR-2 worktree选择其他文件
Combine into single coherent commit
合并为单个连贯提交
undefinedundefinedPre-Merge Review
合并前审查
bash
undefinedbash
undefinedFirst 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
undefined/worktrees merge src/module.js --from ../project-feature
undefinedImportant Notes
重要说明
-
Working directory state: Always ensure your working directory is clean before merging. Uncommitted changes can cause conflicts.
-
Pre-merge review: Consider usingbefore merging to understand what changes will be applied.
/worktrees compare -
Conflict resolution: If conflicts occur during merge, the command will help identify and resolve them before committing.
-
No-commit flag: Most strategies useto give you control over the final commit message and what gets included.
--no-commit -
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.
-
工作目录状态:合并前始终确保工作目录干净。未提交变更可能导致冲突。
-
合并前审查:合并前考虑使用了解将要应用的变更。
/worktrees compare -
冲突解决:如果合并过程中出现冲突,命令会帮助识别并在提交前解决。
-
无提交标志:大多数策略使用,让你控制最终的提交消息和要包含的内容。
--no-commit -
共享仓库:所有worktree共享同一个Git对象数据库,因此在任意worktree中提交的变更,可立即在其他worktree中拣选。
-
分支锁定:记住分支同一时间只能在一个worktree中检出。合并操作使用分支名称,而非创建重复的worktree。
Cleanup After Merge
合并后清理
After merging, consider cleaning up worktrees that are no longer needed:
bash
undefined合并完成后,考虑清理不再需要的worktree:
bash
undefinedList worktrees
列出worktree
git worktree list
git worktree list
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
每次成功合并后,命令会提示你进行清理,以帮助保持工作区整洁。Troubleshooting
故障排除
"Cannot merge: working directory has uncommitted changes"
- Commit or stash your current changes first
- Or use before merge,
git stashaftergit stash pop
"Merge conflict in <file>"
- The command will show conflicted files
- Open files and resolve conflicts (look for markers)
<<<<<<< - Stage resolved files with
git add <file> - Continue with
git commit
"Commit not found" when cherry-picking
- Ensure the commit hash is correct
- Run in any worktree to find commits
git log <branch> - 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
git worktree list - Use to clean up stale references
git worktree prune
"无法合并:工作目录存在未提交变更"
- 先提交或暂存当前变更
- 或者合并前使用,合并后使用
git stashgit stash pop
"Merge conflict in <file>"
- 命令会显示冲突文件
- 打开文件并解决冲突(查找标记)
<<<<<<< - 使用暂存已解决的文件
git add <file> - 使用继续
git commit
"拣选时提示Commit not found"
- 确保提交哈希正确
- 在任意worktree中运行查找提交
git log <branch> - 提交在所有worktree中共享
"Cannot checkout: file exists in working tree"
- 文件存在本地修改
- 先提交、暂存或丢弃本地变更
- 然后重试合并操作
"Branch not found for worktree"
- 指定的worktree可能已被删除
- 运行查看当前worktree
git worktree list - 使用清理过期引用
git worktree prune
Integration with Other Commands
与其他命令集成
Pre-merge review:
bash
> /worktrees compare src/
> /worktrees merge src/specific-file.jsCreate 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-branchAfter merge, cleanup is offered automatically
合并后会自动提示清理
undefinedundefined