这篇文章上次修改于 2233 天前,可能其部分内容已经发生变化,如有疑问可询问作者。 日常开发时经常会遇到在稳定分支发hotfix的情况,通常的解决办法是git stash暂存当前工作区内容,再checkout到需要发补丁的分支下工作,完了再切回来。大多数时候这么干没啥问题。不过如果类似node js项目或者其他有大量外部库依赖项目时就麻烦了。比如php或者golang,通常vendor目录都会git ignore。如果刚好工作分支升级了vendor下的依赖库,与即将发补丁的分支依赖库冲突,那就麻烦了,只能clone到别的目录下来做。好在git 2.5已经把这个需求内置实现。这就要介绍今天的主角:git worktree 命令: ``` git worktree add [-f] [--detach] [--checkout] [--lock] [-b ] [] git worktree list [--porcelain] git worktree lock [--reason ] git worktree move git worktree prune [-n] [-v] [--expire ] git worktree remove [-f] git worktree unlock ``` 比如当前工作分支下要给已提交的master打补丁,新开工作区到/tmp/nginx ``` renothing@desktop:~/myworks/dockerall/nginx[master]$ git worktree add -b hotfix /tmp/nginx origin/master Branch hotfix set up to track remote branch master from origin. Preparing /tmp/nginx (identifier nginx) HEAD is now at 0041a71 fix proxy header error for upstream ``` 此时查看分支情况如下: ``` renothing@desktop:~/myworks/dockerall/nginx[master]$ git branch -va hotfix 0041a71 fix proxy header error for upstream * master 58eb242 [ahead 1] add enviroment support for multiple sites and fastcgi support remotes/origin/HEAD -> origin/master remotes/origin/master 0041a71 fix proxy header error for upstream ``` 切换到/tmp/nginx下你会发现已经成功开辟新分支并切换到工作区 ``` renothing@desktop:/tmp/nginx[hotfix]$ git branch -va * hotfix 0041a71 fix proxy header error for upstream master 58eb242 [ahead 1] add enviroment support for multiple sites and fastcgi support remotes/origin/HEAD -> origin/master remotes/origin/master 0041a71 fix proxy header error for upstream ``` 此时有两个worktree ``` renothing@desktop:/tmp/nginx[hotfix]$ git worktree list /home/renothing/myworks/dockerall/nginx 58eb242 [master] /tmp/nginx 0041a71 [hotfix] ``` 现在可以在hotfix分支开发补丁并提交,丝毫不影响本地Master分支。提交补丁后,可以回主工作区删除临时worktree ``` renothing@desktop:~/myworks/dockerall/nginx[master]$ git branch -D hotfix Deleted branch hotfix (was 0041a71). renothing@desktop:~/myworks/dockerall/nginx[master]$ git branch -va * master 58eb242 [ahead 1] add enviroment support for multiple sites and fastcgi support remotes/origin/HEAD -> origin/master remotes/origin/master 0041a71 fix proxy header error for upstream renothing@desktop:~/myworks/dockerall/nginx[master]$ rm -rf /tmp/nginx/ renothing@desktop:~/myworks/dockerall/nginx[master]$ git worktree prune renothing@desktop:~/myworks/dockerall/nginx[master]$ git worktree list /home/renothing/myworks/dockerall/nginx 58eb242 [master] ``` 一切干干净净。利用worktree不但能实现真正0干扰多分支开发,还能同时在本地跑测试用于对比两个分支运行情况。
没有评论