Git Worktree 简易使用指南

4 阅读1分钟

1. 为什么我们需要 git worktree

Git Worktree 能够为当前的代码仓库创建多个“仓库分身”

  • 从而达成:打开 N 个代码编辑器,在 N 个仓库分身中同时操作 N 个分支
  • 而非:打开 1 个代码编辑器,在 1 个仓库中分时操作 N 个分支

这个功能特别适合于使用多路 AI Coding Agent 进行多个 feature 的同时开发

Cursor 内置了自动在 Worktree 中本地编辑的功能,但其会把仓库分身(Worktree)建立在 ~/.cursor/worktrees/

2. Git Worktree 简单用法

# 查看所有的 worktree
git worktree list

# 在路径 `../name-of-repo` 下,新建一个仓库分身 worktree
# 并在其中以 branch `main` 为基础,创建新的 branch `featA`
git worktree add -b featA ../name-of-repo main

# 删除已有的 worktree
git worktree remove ../name-of-repo

# 也可以直接 `rm -rf ../name-of-repo`
# 然后再运行 prune 进行修剪
git worktree prune

3. Git Worktree 的 Branch 说明

所有的 worktree 共享同一套 branch,因为所有的 worktree 本质上归属于同一个 git repo(使用同一个 .git 目录)。在 worktree A 中新建的 branch,在 worktree B 中同样可以看到(一并共享的也包括 tags、remote tracking branches、stash 等)。

但 worktree 有一个重要限制:同一个 branch 不能同时被多个 worktree checkout
即,每个 branch 同一时间只能被一个 worktree 所占用

References