git-worktrees

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git 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

核心概念

ConceptDescription
Main worktreeOriginal working directory from
git clone
or
git init
Linked worktreeAdditional directories created with
git worktree add
Shared
.git
All worktrees share same Git object database (no duplication)
Branch lockEach branch can only be checked out in ONE worktree at a time
Worktree metadataAdministrative files in
.git/worktrees/
tracking linked worktrees
概念描述
主worktree
git clone
git init
创建的原始工作目录
关联worktree使用
git worktree add
创建的额外目录
共享
.git
所有worktree共享同一个Git对象数据库(无重复存储)
分支锁定每个分支同一时间只能在一个worktree中检出
Worktree元数据
.git/worktrees/
中的管理文件,用于跟踪关联的worktree

Quick Reference

快速参考

TaskCommand
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
git worktree list
Remove worktree
git worktree remove <path>
Force remove worktree
git worktree remove --force <path>
Move worktree
git worktree move <old> <new>
Lock worktree
git worktree lock <path>
Unlock worktree
git worktree unlock <path>
Prune stale worktrees
git worktree prune
Repair worktree links
git worktree repair
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
git cherry-pick <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
git worktree list
删除worktree
git worktree remove <path>
强制删除worktree
git worktree remove --force <path>
移动worktree
git worktree move <old> <new>
锁定worktree
git worktree lock <path>
解锁worktree
git worktree unlock <path>
清理过期worktree
git worktree prune
修复worktree链接
git worktree repair
对比不同worktree的文件
diff ../worktree-a/file ../worktree-b/file
从其他分支获取单个文件
git checkout <branch> -- <path>
获取文件的部分变更
git checkout -p <branch> -- <path>
拣选提交
git cherry-pick <commit>
拣选提交但不自动提交
git cherry-pick --no-commit <commit>
合并但不自动提交
git merge --no-commit <branch>

Essential Commands

关键命令

Create a Worktree

创建Worktree

bash
undefined
bash
undefined

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
undefined
git worktree add --detach ../experiment HEAD~5
undefined

List Worktrees

列出Worktree

bash
undefined
bash
undefined

Simple 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]
undefined
git worktree list --porcelain

**示例输出:**
/home/user/project abc1234 [main] /home/user/project-feature def5678 [feature-x] /home/user/project-hotfix ghi9012 [hotfix-123]
undefined

Remove a Worktree

删除Worktree

bash
undefined
bash
undefined

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
undefined
git worktree remove --force ../feature-x
undefined

Move a Worktree

移动Worktree

bash
undefined
bash
undefined

Relocate worktree to new path

将worktree迁移到新路径

git worktree move ../old-path ../new-path
undefined
git worktree move ../old-path ../new-path
undefined

Lock/Unlock Worktrees

锁定/解锁Worktree

bash
undefined
bash
undefined

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
undefined
git worktree unlock ../feature-x
undefined

Prune Stale Worktrees

清理过期Worktree

bash
undefined
bash
undefined

Remove 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
undefined
git worktree prune -v
undefined

Repair Worktrees

修复Worktree

bash
undefined
bash
undefined

Repair worktree links after moving directories manually

手动移动目录后修复worktree链接

git worktree repair
git worktree repair

Repair specific worktree

修复指定的worktree

git worktree repair ../feature-x
undefined
git worktree repair ../feature-x
undefined

Workflow Patterns

工作流模式

Pattern 1: Feature + Hotfix in Parallel

模式1:功能开发与热修复并行

To fix a bug while feature work is in progress:
bash
undefined
在开发功能时修复bug:
bash
undefined

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

返回功能开发目录

cd ../project
cd ../project

Clean up when done

完成后清理

git worktree remove ../project-hotfix
undefined
git worktree remove ../project-hotfix
undefined

Pattern 2: PR Review While Working

模式2:开发时审查PR

To review a PR without affecting current work:
bash
undefined
在不影响当前工作的情况下审查PR:
bash
undefined

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

审查:运行测试、检查代码

cd ../project-review
cd ../project-review

Return to work, then clean up

返回工作目录,然后清理

cd ../project git worktree remove ../project-review git branch -d pr-123
undefined
cd ../project git worktree remove ../project-review git branch -d pr-123
undefined

Pattern 3: Compare Implementations

模式3:对比不同实现

To compare code across branches side-by-side:
bash
undefined
并排对比不同分支的代码:
bash
undefined

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

Clean up

清理

git worktree remove ../project-v1 git worktree remove ../project-v2
undefined
git worktree remove ../project-v1 git worktree remove ../project-v2
undefined

Pattern 4: Long-Running Tasks

模式4:长时间运行任务

To run tests/builds in isolation while continuing development:
bash
undefined
在隔离环境中运行测试/构建,同时继续开发:
bash
undefined

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中继续开发

cd ../project
undefined
cd ../project
undefined

Pattern 5: Stable Reference

模式5:稳定参考分支

To maintain a clean main checkout for reference:
bash
undefined
维护一个干净的main分支检出作为参考:
bash
undefined

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
undefined
git worktree lock --reason "Reference checkout" ../project-main
undefined

Pattern 6: Selective Merging from Multiple Features

模式6:从多个功能分支选择性合并

To combine specific changes from multiple feature branches:
bash
undefined
合并来自多个功能分支的特定变更:
bash
undefined

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

Clean up

清理

git worktree remove ../project-feature-1 git worktree remove ../project-feature-2
undefined
git worktree remove ../project-feature-1 git worktree remove ../project-feature-2
undefined

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:
bash
undefined
worktree本质就是目录,你可以直接对比文件:
bash
undefined

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
undefined
diff -r ../project-v1/src ../project-v2/src
undefined

Merge Only One File from a Worktree

从Worktree合并单个文件

You can selectively bring a single file from another branch using
git checkout
:
bash
undefined
你可以使用
git checkout
从其他分支选择性获取单个文件:
bash
undefined

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:
bash
undefined
拣选操作基于提交进行。由于所有worktree共享同一个仓库,你可以拣选任意提交:
bash
undefined

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

将特定提交拣选到当前分支

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
undefined
git cherry-pick --no-commit abc1234
undefined

Merge Changes from Multiple Worktrees

从多个Worktree合并变更

You can merge or cherry-pick from multiple branches:
bash
undefined
你可以从多个分支合并或拣选变更:
bash
undefined

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
undefined
git cherry-pick abc1234 # 来自feature-1 git cherry-pick def5678 # 来自feature-2
undefined

Selective Merging - Pick Which Changes to Include

选择性合并 - 选择要包含的变更

Option 1: Selective File Checkout

选项1:选择性文件检出

bash
undefined
bash
undefined

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"
undefined
git checkout feature-1 -- src/moduleA.js git checkout feature-2 -- src/moduleB.js git commit -m "Merge selected files from feature branches"
undefined

Option 2: Interactive Patch Selection

选项2:交互式补丁选择

bash
undefined
bash
undefined

Select specific hunks from a file

选择文件中的特定代码块

git checkout -p feature-1 -- src/shared.js
undefined
git checkout -p feature-1 -- src/shared.js
undefined

Option 3: Cherry-Pick with Selective Staging

选项3:带选择性暂存的拣选

bash
undefined
bash
undefined

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"
undefined
git commit -m "Selected changes from feature-1"
undefined

Option 4: Merge with Manual Selection

选项4:手动选择合并

bash
undefined
bash
undefined

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"
undefined
git commit -m "Merge selected changes from feature-1"
undefined

Option 5: Using git restore (Git 2.23+)

选项5:使用git restore(Git 2.23+)

bash
undefined
bash
undefined

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
undefined
git restore -p --source=feature-branch -- path/to/file.js
undefined

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
Naming convention:
<project>-<purpose>
or
<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

最佳实践

PracticeRationale
Use sibling directoriesKeep worktrees at same level as main project for easy navigation
Name by purpose
project-review
is clearer than
project-pr-123
Clean up promptlyRemove worktrees when done to avoid confusion
Lock remote worktreesPrevent pruning if worktree is on network/USB storage
Use
--detach
for experiments
Avoid creating throwaway branches
Commit before removingAlways commit or stash before
git worktree remove
实践理由
使用同级目录将worktree与主项目放在同一层级,便于导航
按用途命名
project-review
project-pr-123
更清晰
及时清理完成任务后删除worktree,避免混淆
锁定远程worktree如果worktree在网络/USB存储上,锁定以防止被清理
实验时使用
--detach
避免创建临时分支
删除前提交在执行
git worktree remove
前,务必提交或暂存变更

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
undefined

Find 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
undefined
git worktree remove ../other-worktree
undefined

Issue: Stale worktree after manual deletion

问题:手动删除后worktree过期

Cause: Deleted worktree directory without using
git worktree remove
.
Solution:
bash
undefined
原因: 未使用
git worktree remove
就删除了worktree目录。
解决方案:
bash
undefined

Clean up stale metadata

清理过期的元数据

git worktree prune
undefined
git worktree prune
undefined

Issue: Worktree moved manually

问题:手动移动了worktree

Cause: Moved worktree directory without using
git worktree move
.
Solution:
bash
undefined
原因: 未使用
git worktree move
就移动了worktree目录。
解决方案:
bash
undefined

Repair the worktree links

修复worktree链接

git worktree repair
git worktree repair

Or specify the new path

或者指定新路径

git worktree repair /new/path/to/worktree
undefined
git worktree repair /new/path/to/worktree
undefined

Issue: Worktree on removed drive

问题:worktree所在驱动器已移除

Cause: Worktree was on removable storage that's no longer connected.
Solution:
bash
undefined
原因: worktree所在的可移动存储已断开连接。
解决方案:
bash
undefined

If temporary, lock it to prevent pruning

如果是临时情况,锁定以防止被清理

git worktree lock ../usb-worktree
git worktree lock ../usb-worktree

If permanent, prune it

如果是永久移除,清理它

git worktree prune
undefined
git worktree prune
undefined

Common Mistakes

常见错误

MistakeFix
Using
rm -rf
to delete worktree
Always use
git worktree remove
, then
git worktree prune
if needed
Forgetting branch is locked to worktreeRun
git worktree list
before checkout errors
Not cleaning up temporary worktreesRemove worktrees immediately after task completion
Creating worktrees in nested locationsUse sibling directories (
../project-feature
) not subdirs
Moving worktree directory manuallyUse
git worktree move
or run
git worktree repair
after
错误修复方法
使用
rm -rf
删除worktree
始终使用
git worktree remove
,必要时再执行
git worktree prune
忘记分支已被worktree锁定在出现检出错误前,先运行
git worktree list
未清理临时worktree任务完成后立即删除worktree
在嵌套位置创建worktree使用同级目录(
../project-feature
)而非子目录
手动移动worktree目录使用
git worktree move
,或移动后运行
git worktree repair

Agent Workflow Integration

Agent工作流集成

To isolate parallel agent tasks:
bash
undefined
隔离并行Agent任务:
bash
undefined

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
cd ../project

使用分离头指针安全实验:

```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
undefined
git worktree remove --force ../project-experiment
undefined

Verification 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
    --detach
    for experiments
When removing worktrees:
  • Commit or stash any uncommitted changes
  • Use
    git worktree remove
    , not
    rm -rf
  • Run
    git worktree prune
    if directory was deleted manually

使用worktree前:
  • 理解分支同一时间只能在一个worktree中检出
  • 确定worktree的创建位置(使用同级目录)
  • 规划临时worktree的清理策略
创建worktree时:
  • 使用描述性目录名称
  • 验证分支未在其他位置检出
  • 考虑为实验使用
    --detach
删除worktree时:
  • 提交或暂存所有未提交变更
  • 使用
    git worktree remove
    而非
    rm -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:
  1. Current state check: Run
    git worktree list
    to show all existing worktrees and their locations
  2. Parse user input: Classify each provided argument:
    • No arguments: Interactive mode - ask user what to compare
    • --stat
      : Show summary statistics of differences (files changed, insertions, deletions)
    • 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
  3. 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
    git worktree list
    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
    git diff
  4. 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)"
  5. 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>
  6. 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
重要:严格按照以下步骤执行:
  1. 当前状态检查:运行
    git worktree list
    查看所有现有worktree及其位置
  2. 解析用户输入:对每个提供的参数进行分类:
    • 无参数:交互式模式 - 询问用户要对比的内容
    • --stat
      :显示差异的汇总统计信息(变更文件数、插入行数、删除行数)
    • Worktree路径:与
      git worktree list
      输出中某个worktree根目录匹配的路径
    • 分支名称:与某个worktree中分支匹配的名称
    • 文件/目录路径:当前worktree中要对比的路径
  3. 确定对比目标(要对比的worktree): a. 如果用户提供了worktree路径:将这些作为对比目标 b. 如果用户指定了分支名称:从
    git worktree list
    中找到对应分支的worktree c. 如果除当前外仅存在一个worktree:将当前和该worktree作为对比目标 d. 如果存在多个worktree且未指定:列出所有选项并询问用户要对比哪些 e. 如果不存在其他worktree:建议使用
    git diff
    对比分支
  4. 确定对比内容(worktree内的文件/目录): a. 如果用户指定了文件/目录路径:对比所有指定路径 b. 如果未指定具体路径:询问用户:
    • "是否对比整个worktree?" 或
    • "是否对比特定文件/目录?(输入路径)"
  5. 执行对比
    对比不同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>
  6. 格式化并展示结果
    • 显示清晰的标题,说明正在对比的内容
    • 对于大型差异,先提供摘要选项
    • 突出重要变更(新增文件、删除文件、重命名文件)
    • 提供每个worktree对应分支的上下文信息

Comparison Modes

对比模式

ModeDescriptionCommand Pattern
File diffCompare single file between worktrees
diff -u <wt1>/file <wt2>/file
Directory diffCompare directories recursively
diff -r <wt1>/dir <wt2>/dir
Summary onlyShow which files differ (no content)
diff -rq <wt1>/ <wt2>/
Git diffUse git's diff (branch-based)
git diff branch1..branch2 -- path
Stat viewShow change statistics
git diff --stat branch1..branch2
模式描述命令模板
文件差异对比不同worktree的单个文件
diff -u <wt1>/file <wt2>/file
目录差异递归对比目录
diff -r <wt1>/dir <wt2>/dir
仅摘要显示哪些文件不同(不显示内容)
diff -rq <wt1>/ <wt2>/
Git差异使用Git的diff功能(基于分支)
git diff branch1..branch2 -- path
统计视图显示变更统计信息
git diff --stat branch1..branch2

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)
命令通过
git worktree list
查找worktree:
/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.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/目录

undefined
undefined

Output 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
undefined
bash
undefined

See what changed in a feature branch

查看功能分支的变更

/worktrees compare --stat /worktrees compare src/components/
undefined
/worktrees compare --stat /worktrees compare src/components/
undefined

Compare Implementations

对比不同实现

bash
undefined
bash
undefined

Compare 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/
undefined

Quick File Check

快速文件检查

bash
undefined
bash
undefined

Check if a specific file differs

检查特定文件是否存在差异

/worktrees compare package.json
undefined
/worktrees compare package.json
undefined

Pre-Merge Review

合并前审查

bash
undefined
bash
undefined

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/目录都会被对比

undefined
undefined

Important Notes

重要说明

  • Argument detection: The command auto-detects argument types by comparing them against
    git worktree list
    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.,
    ../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 using
    git diff
    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
    git diff
    for branch comparison instead.
  • 参数检测:命令通过与
    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
/worktrees create
first to set up worktrees for comparison:
bash
undefined
先使用
/worktrees create
创建worktree,再进行对比:
bash
undefined

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

Now compare

现在进行对比

/worktrees compare src/
undefined
/worktrees compare src/
undefined

Troubleshooting

故障排除

"No other worktrees found"
  • Create a worktree first with
    /worktrees create <branch>
  • Or use
    git diff
    for branch-only comparison without worktrees
"Worktree for branch not found"
  • The branch may not have a worktree created
  • Run
    git worktree list
    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
  • 或者使用
    git diff
    进行仅分支的对比,无需worktree
"未找到分支对应的worktree"
  • 该分支可能没有创建对应的worktree
  • 运行
    git worktree list
    查看可用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以支持并行开发的工作流,可自动检测并安装项目依赖。

Instructions

步骤说明

CRITICAL: Perform the following steps exactly as described:
  1. Current state check: Run
    git worktree list
    to show existing worktrees and
    git status
    to verify the repository state is clean (no uncommitted changes that might cause issues)
  2. Fetch latest remote branches: Run
    git fetch --all
    to ensure local has knowledge of all remote branches
  3. Parse user input: Determine what the user wants to create:
    • <name>
      : Create worktree with auto-detected type prefix
    • --list
      : Just show existing worktrees and exit
    • No input: Ask user interactively for the name
  4. 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
    ,
    experiment
    ,
    review
    Examples:
    • refactor auth system
      refactor/auth-system
    • fix login bug
      fix/login-bug
    • auth system
      feature/auth-system
      (default)
    • hotfix critical error
      hotfix/critical-error
    Name normalization: Convert spaces to dashes, lowercase, remove special characters except dashes/underscores
  5. For each worktree to create: a. Branch name construction: Build full branch name from detected type and normalized name:
    • <prefix>/<normalized-name>
      (e.g.,
      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 command
    e. Dependency detection: Check the new worktree for dependency files and determine if setup is needed:
    • package.json
      -> Node.js project (npm/yarn/pnpm/bun)
    • requirements.txt
      or
      pyproject.toml
      or
      setup.py
      -> Python project
    • Cargo.toml
      -> Rust project
    • go.mod
      -> Go project
    • Gemfile
      -> Ruby project
    • composer.json
      -> PHP project
    f. Package manager detection (for Node.js projects):
    • bun.lockb
      -> Use
      bun install
    • pnpm-lock.yaml
      -> Use
      pnpm install
    • yarn.lock
      -> Use
      yarn install
    • package-lock.json
      or default -> Use
      npm 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
  6. 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>
重要:严格按照以下步骤执行:
  1. 当前状态检查:运行
    git worktree list
    查看现有worktree,运行
    git status
    验证仓库状态干净(无未提交变更,避免出现问题)
  2. 获取最新远程分支:运行
    git fetch --all
    确保本地知晓所有远程分支
  3. 解析用户输入:确定用户要创建的内容:
    • <name>
      :创建带有自动检测类型前缀的worktree
    • --list
      :仅显示现有worktree并退出
    • 无输入:交互式询问用户名称
  4. 从名称自动检测分支类型:检查第一个单词是否为已知分支类型。如果是,将其作为前缀,剩余部分作为名称。如果不是,默认使用
    feature/
    已知类型:
    feature
    ,
    feat
    ,
    fix
    ,
    bug
    ,
    bugfix
    ,
    hotfix
    ,
    release
    ,
    docs
    ,
    test
    ,
    refactor
    ,
    chore
    ,
    spike
    ,
    experiment
    ,
    review
    示例:
    • refactor auth system
      refactor/auth-system
    • fix login bug
      fix/login-bug
    • auth system
      feature/auth-system
      (默认)
    • hotfix critical error
      hotfix/critical-error
    名称规范化: 将空格转换为连字符,转为小写,移除除连字符/下划线外的特殊字符
  5. 创建每个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的依赖文件,确定是否需要配置:
    • package.json
      → Node.js项目(npm/yarn/pnpm/bun)
    • requirements.txt
      pyproject.toml
      setup.py
      → Python项目
    • Cargo.toml
      → Rust项目
    • go.mod
      → Go项目
    • Gemfile
      → Ruby项目
    • composer.json
      → PHP项目
    f. 包管理器检测(针对Node.js项目):
    • bun.lockb
      → 使用
      bun install
    • pnpm-lock.yaml
      → 使用
      pnpm install
    • yarn.lock
      → 使用
      yarn install
    • package-lock.json
      或默认 → 使用
      npm install
    g. 自动配置:自动运行依赖安装:
    • 切换到worktree目录并运行检测到的安装命令
    • 报告进度:"正在使用[包管理器]安装依赖..."
    • 如果安装失败,报告错误但继续显示worktree创建摘要
  6. 摘要:显示已创建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:
    <project-name>-<name>
    (uses the name part, NOT the full branch)
  • Branch name:
    <type-prefix>/<name>
    (e.g.,
    feature/add-auth
    )
  • Directory name uses only the
    <name>
    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)
命名规则:
  • 模式:
    <project-name>-<name>
    (使用名称部分,而非完整分支名)
  • 分支名称:
    <type-prefix>/<name>
    (例如
    feature/add-auth
  • 目录名称仅使用
    <name>
    部分以保持简洁

Examples

示例

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 输出

undefined
undefined

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构建项目...
✓ 项目构建成功

Common Workflows

常见工作流

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、安装依赖,准备就绪可开始编码

undefined
undefined

Hotfix While Feature In Progress

功能开发时创建热修复

bash
undefined
bash
undefined

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

完成后返回功能开发

undefined
undefined

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

审查完成后删除

undefined
undefined

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

根据结果决定丢弃或合并

undefined
undefined

Important 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 (
    --track
    flag) so pulls/pushes work correctly.
  • 分支锁定:每个分支同一时间只能在一个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-auth
Or for a worktree with uncommitted changes:
bash
git worktree remove --force ../myproject-add-auth
Never use
rm -rf
to delete worktrees - always use
git worktree remove
.
完成worktree使用后,使用正确的删除命令:
bash
git worktree remove ../myproject-add-auth
或者对于包含未提交变更的worktree:
bash
git worktree remove --force ../myproject-add-auth
切勿使用
rm -rf
删除worktree - 始终使用
git worktree remove

Troubleshooting

故障排除

"Branch is already checked out"
  • Run
    git worktree list
    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:
    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
    ,
    spike
    ,
    review
  • Default type is
    feature/
    when first word isn't a known type

"Branch is already checked out"
  • 运行
    git worktree list
    查看分支被检出的位置
  • 要么在对应的worktree中操作,要么先删除它
"无法创建worktree - 路径已存在"
  • 目标目录已存在
  • 删除该目录或选择不同的worktree路径
"依赖安装失败"
  • 手动导航到worktree:
    cd ../myproject-<name>
  • 直接运行安装命令查看完整错误输出
  • 常见原因:缺失系统依赖、网络问题、锁定文件损坏
"检测到错误的类型"
  • 如果第一个单词是已知类型,会被用作分支类型
  • 要强制指定类型,以以下前缀开头:
    fix
    ,
    hotfix
    ,
    docs
    ,
    test
    ,
    refactor
    ,
    chore
    ,
    spike
    ,
    review
  • 当第一个单词不是已知类型时,默认类型为
    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:
  1. Current state check: Run
    git worktree list
    to show all existing worktrees and
    git status
    to verify working directory state
  2. Parse user input: Determine what merge operation the user wants:
    • --interactive
      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
    • --from <worktree>
      : Specify source worktree explicitly
    • --patch
      or
      -p
      : Use interactive patch selection mode
  3. Determine source worktree/branch: a. If user specified
    --from <worktree>
    : Use that worktree path directly b. If user specified a branch name: Find worktree for that branch from
    git worktree list
    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
  4. 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:
      1. git cherry-pick --no-commit <commit>
      2. Review staged changes
      3. git reset HEAD -- <unwanted-files>
        to unstage
      4. git checkout -- <unwanted-files>
        to discard
      5. git commit -m "message"
    Strategy D: Manual Merge with Conflicts (for complex merges)
    • Best for: Full branch merge with control over resolution
    • Steps:
      1. git merge --no-commit <branch>
      2. Review all changes
      3. Selectively stage/unstage files
      4. Resolve conflicts if any
      5. git commit -m "message"
    Strategy E: Multi-Worktree Selective Merge (combining from multiple sources)
    • Best for: Taking different files from different worktrees
    • Steps:
      1. git checkout <branch1> -- <path1>
      2. git checkout <branch2> -- <path2>
      3. git commit -m "Merge selected files from multiple branches"
  5. Execute the selected strategy:
    • Run pre-merge comparison if user wants to review (suggest
      /worktrees compare
      first)
    • Execute git commands for the chosen strategy
    • Handle any conflicts that arise
    • Confirm changes before final commit
  6. Post-merge summary: Display what was merged:
    • Files changed/added/removed
    • Source worktree/branch
    • Merge strategy used
  7. 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
      git worktree prune
      if needed
重要:严格按照以下步骤执行:
  1. 当前状态检查:运行
    git worktree list
    查看所有现有worktree,运行
    git status
    验证工作目录状态
  2. 解析用户输入:确定用户想要的合并操作:
    • --interactive
      或无参数
      :引导式交互式模式
    • 文件/目录路径:从worktree合并特定文件/目录
    • 提交名称:拣选特定提交
    • 分支名称:从该分支的worktree合并
    • --from <worktree>
      :显式指定源worktree
    • --patch
      -p
      :使用交互式补丁选择模式
  3. 确定源worktree/分支: a. 如果用户指定
    --from <worktree>
    :直接使用该worktree路径 b. 如果用户指定分支名称:从
    git worktree list
    中找到该分支对应的worktree c. 如果仅存在一个其他worktree:询问用户确认将其作为源 d. 如果存在多个worktree:列出所有选项并询问用户要从哪个合并 e. 如果不存在其他worktree:说明情况并建议使用基于分支的合并
  4. 确定合并策略:根据用户需求提供选项:
    策略A:选择性文件检出(针对特定文件/目录)
    • 适用场景:从其他分支获取完整文件
    • 命令:
      git checkout <branch> -- <path>
    策略B:交互式补丁选择(针对文件的部分变更)
    • 适用场景:从文件中选择特定代码块/行
    • 命令:
      git checkout -p <branch> -- <path>
    • 提示用户对每个代码块进行选择:y(应用)、n(跳过)、s(拆分)、e(编辑)
    策略C:带选择性暂存的拣选(针对特定提交)
    • 适用场景:应用提交但排除部分变更
    • 步骤:
      1. git cherry-pick --no-commit <commit>
      2. 审查暂存的变更
      3. git reset HEAD -- <unwanted-files>
        取消暂存不需要的文件
      4. git checkout -- <unwanted-files>
        丢弃不需要的变更
      5. git commit -m "message"
    策略D:带冲突处理的手动合并(针对复杂合并)
    • 适用场景:完整分支合并并控制解决过程
    • 步骤:
      1. git merge --no-commit <branch>
      2. 审查所有变更
      3. 选择性暂存/取消暂存文件
      4. 解决冲突(如果有)
      5. git commit -m "message"
    策略E:多Worktree选择性合并(从多个源合并)
    • 适用场景:从不同worktree获取不同文件
    • 步骤:
      1. git checkout <branch1> -- <path1>
      2. git checkout <branch2> -- <path2>
      3. git commit -m "Merge selected files from multiple branches"
  5. 执行所选策略
    • 如果用户需要审查,先运行合并前对比(建议先使用
      /worktrees compare
    • 执行所选策略对应的Git命令
    • 处理出现的任何冲突
    • 提交前确认变更
  6. 合并后摘要:显示合并内容:
    • 变更/新增/删除的文件
    • 源worktree/分支
    • 使用的合并策略
  7. 清理提示:合并成功后询问:
    • "是否要删除一些worktree以清理本地状态?"
    • 如果是:列出worktree并询问要删除哪些
    • 对所选worktree执行
      git worktree remove <path>
    • 提醒必要时使用
      git worktree prune

Merge Strategies Reference

合并策略参考

StrategyUse WhenCommand Pattern
Selective FileNeed complete file(s) from another branch
git checkout <branch> -- <path>
Interactive PatchNeed specific changes within a file
git checkout -p <branch> -- <path>
Cherry-Pick SelectiveNeed a commit but not all its changes
git cherry-pick --no-commit
+ selective staging
Manual MergeFull branch merge with control
git merge --no-commit
+ selective staging
Multi-SourceCombining files from multiple branchesMultiple
git checkout <branch> -- <path>
策略适用场景命令模板
选择性文件需要从其他分支获取完整文件
git checkout <branch> -- <path>
交互式补丁需要文件中的特定变更
git checkout -p <branch> -- <path>
选择性拣选需要提交但不需要其所有变更
git cherry-pick --no-commit
+ 选择性暂存
手动合并完整分支合并并需要控制过程
git merge --no-commit
+ 选择性暂存
多源合并从多个分支合并文件多次执行
git checkout <branch> -- <path>

Examples

示例

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

审查并提交所选变更

undefined
undefined

Interactive Patch Mode Guide

交互式补丁模式指南

When using
--patch
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,?]
KeyAction
y
Apply this hunk
n
Skip this hunk
q
Quit (don't apply this or remaining hunks)
a
Apply this and all remaining hunks
d
Don't apply this or remaining hunks in this file
s
Split into smaller hunks
e
Manually edit the hunk
?
Show help
使用
--patch
或策略B时,用户会看到每个变更代码块的提示:
@@ -10,6 +10,8 @@ function processData(input) {
   const result = transform(input);
+  // Added validation
+  if (!isValid(result)) throw new Error('Invalid');
   return result;
 }
Apply this hunk? [y,n,q,a,d,s,e,?]
按键操作
y
应用此代码块
n
跳过此代码块
q
退出(不应用此代码块及剩余代码块)
a
应用此代码块及所有剩余代码块
d
不应用此代码块及此文件中的剩余代码块
s
拆分为更小的代码块
e
手动编辑代码块
?
显示帮助

Cherry-Pick Selective Workflow

选择性拣选工作流

For Strategy C (cherry-picking with selective staging):
bash
undefined
对于策略C(带选择性暂存的拣选):
bash
undefined

1. 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"
undefined
git commit -m "Cherry-pick selected changes from abc1234"
undefined

Multi-Worktree Merge Workflow

多Worktree合并工作流

For Strategy E (merging from multiple worktrees):
bash
undefined
对于策略E(从多个worktree合并):
bash
undefined

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

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"
undefined
git commit -m "feat: combine auth, API, and UI improvements from feature branches"
undefined

Common Workflows

常见工作流

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

仅获取该文件,而非整个分支

undefined
undefined

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修复代码块,而非所有变更

undefined
undefined

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

合并为单个连贯提交

undefined
undefined

Pre-Merge Review

合并前审查

bash
undefined
bash
undefined

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
undefined
/worktrees merge src/module.js --from ../project-feature
undefined

Important Notes

重要说明

  • Working directory state: Always ensure your working directory is clean before merging. Uncommitted changes can cause conflicts.
  • Pre-merge review: Consider using
    /worktrees compare
    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
    --no-commit
    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.
  • 工作目录状态:合并前始终确保工作目录干净。未提交变更可能导致冲突。
  • 合并前审查:合并前考虑使用
    /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
undefined

List 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
    git stash
    before merge,
    git stash pop
    after
"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
    git log <branch>
    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
    git worktree list
    to see current worktrees
  • Use
    git worktree prune
    to clean up stale references
"无法合并:工作目录存在未提交变更"
  • 先提交或暂存当前变更
  • 或者合并前使用
    git stash
    ,合并后使用
    git 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可能已被删除
  • 运行
    git worktree list
    查看当前worktree
  • 使用
    git worktree prune
    清理过期引用

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

合并后会自动提示清理

undefined
undefined