在日常开发中,我们经常遇到这样的场景:
- 当前分支正在开发功能 A,但突然要修紧急 bug
- 需要同时对比两个分支的代码
- 想在不切换当前工作目录的情况下并行开发
- build / test 需要在不同分支同时进行
第一想法就是git stash + git checkout 来回切分支,或者clone 一个目录,但 Git 早就提供了一个更优雅的能力:git worktree
一、Git Worktree 是什么?
Git Worktree 是 Git 提供的一种能力:允许一个 Git 仓库(.git)关联多个工作目录(working tree)。
project-main/ (main branch)
project-feature/ (feature branch)
project-hotfix/ (hotfix branch)
它们:
- 共享同一个
.git - 但每个目录可以 checkout 不同分支
- 互不影响
二、核心价值
1. 不再频繁 stash / checkout
避免:
- git stash
- git checkout
- git stash pop
worktree方式:
shell
git worktree add ../hotfix hotfix
2. 并行开发
多个 IDE 同时打开不同分支:
- IntelliJ:feature 分支
- VSCode:hotfix 分支
- Terminal:release 分支
互不干扰。
3. 避免重复 clone
不用多次 git clone,一个仓库即可。
4. CI/CD 友好
例如:
- 一个目录跑 build
- 一个目录跑 test
- 一个目录跑 benchmark
避免 checkout 互相污染。
三、原理
- .git 是唯一的
- worktree 是多个工作目录
- Git 通过
gitdir关联
shell
repo/
.git (主仓库)
../feature/
.git -> repo/.git/worktrees/feature
四、常用命令
1. 查看
shell
git worktree list
2. 创建
shell
git worktree add <path> <branch>
# 1、在 ../feature 创建工作目录
# 2、checkout feature 分支
git worktree add ../feature feature
3. 创建新分支
shell
git worktree add -b new-feature ../new-feature main
#1、从 main 创建新分支 new-feature
#2、在新目录 checkout
4. 删除
shell
git worktree remove <path>
#1、目录必须没有未提交修改
#2、否则需要 --force
5. 清理
shell
#用于清理 Git 内部残留记录。
git worktree prune
6. 锁定
shell
# 锁定
git worktree lock <path>
# 解锁
git worktree unlock ../feature
五、应用场景
1. 紧急修 bug
feature 开发中 → hotfix 并行处理
传统方式:
- stash
- 切分支
- 修 bug
- 再切回来
worktree:
shell
git worktree add ../hotfix hotfix
2. 多版本维护
v1 / v2 / v3 并行维护
shell
git worktree add ../v1 v1.0
git worktree add ../v2 v2.0
git worktree add ../v3 v3.0
3. 多环境对比
不同分支同时运行对比行为
shell
git worktree add ../main main
git worktree add ../feature feature
4. CI 构建
避免重复 clone,加速构建
六、注意事项
- 同一分支不能同时
checkout多个worktree - 删除必须
git worktree remove - 不要直接
rm -rf worktree不是独立仓库