一、什么是worktree?

Manage multiple working trees attached to the same repository. A git repository can support multiple working trees, allowing you to check out more than one branch at a time.

管理连接到同一存储库的多个工作树。一个git仓库可以支持多个工作树,允许一次迁出多个分支。

二、为什么要用worktree?

场景:正在开发新的需求,这时候还需要对已提测功能的bug fixes

方法1:先stash正在开发的代码,再check out到原分支进行bug fixes 缺点:分支切换后需要重新pod install,然后xcode重建索引并重新编译,耗时耗力

方法2:clone两个仓库 缺点:.git目录会占空间,且两个仓库之间毫无关联,无法相互查看本地提交

方法3:git worktree

三、worktree的相关命令

➜  worktree_test git:(develop) git worktree -h
usage: git worktree add [<options>] <path> [<commit-ish>]
   or: git worktree list [<options>]
   or: git worktree lock [<options>] <path>
   or: git worktree move <worktree> <new-path>
   or: git worktree prune [<options>]
   or: git worktree remove [<options>] <worktree>
   or: git worktree unlock <path>

四、常用操作

1、添加一个worktree
git worktree add ../live_protocol_isolation team_live/live_protocol_isolation

20298fd5dd1613e9ecfa2a8f2c5a8e2f 289af9dbfe6df4e4e62253452a7d3408

2、移除一个worktree
git worktree remove /Users/oudushu/WorkSpace/live_protocol_isolation
3、查看工作区
git worktree list

65d5798b1495fff9e6f2db2a7d7eb767

4、查看本地提交
git show team_live/live_protocol_isolation

因为是同一个repo,所以切到dev分支后,可以马上查看到worktree分支的提交。

五、注意点

1、无法checkout到同一个分支

a85f01f21b2d5e4a2b349a1da5077eab

2、通过git worktree add出来的分支,没有.git文件夹

0d81eac276ce0016fcd09bdbe236adaf

原Podfile文件要处理:

#避免在使用git worktree的时候编译报错
#git worktree中.git是一个文件而不是目录
if File.directory?(".git") == true then
    FileUtils.cp_r("scripts/git-hooks/commit-msg", ".git/hooks/commit-msg")
end

https://git-scm.com/docs/git-worktree