"git worktree" 分支的长期使用

Long-term usage of branches with "git worktree"

我正在研究 git 的 "new" worktree 功能,因为它似乎非常适合我经常遇到的问题:需要同时在多个分支中工作(其中一些寿命很短,而另一些寿命很长)。

我通常需要在 release_a branch 上工作几个小时,然后在 release_x branch 上修复一些东西,然后在 release_h branch 上修复一些东西。由于我很懒惰,我最终做的是使用 Intellij 设置我的 git 存储库的多个副本,因此我不需要不断地在这里和那里切换分支。

当我听说 git 的 worktree 命令时,我认为这正是我正在寻找的——一种使单个存储库具有多个工作目录的方法。作为一个很大的优势,这意味着我实际上不再需要每次在分支上更改某些东西时仅仅为了让另一个人拉它(例如,为了一个修补程序)而推送东西。我可以在本地合并它们。

我对 git 的 worktree 的理解正确吗?

我一直在玩它,但我无法真正理解它是如何为我的目的工作的。似乎默认情况下它会在其根文件夹中创建工作树,但如果我执行 git add . 那些相同的文件夹将包含在提交中。

这就是我为现有分支 my_branch 创建工作树的方式(假设我目前在@ master):

git worktree add my_branch my_branch

所以我的问题是双重的:

  1. 为长期分支应用多个工作树是否可能/正确,还是只是暂时有意义的事情?
  2. 然后我应该如何正确删除不需要的工作树?
  3. 我应该让这些工作树存在于我的主 git 存储库内部还是外部?

谢谢

And as a big plus, that would mean that I no longer would actually have to push stuff every time I changed something on a branch just for the sake of having another one pull it (as for instance, for an hotfix). I could just locally merge them.

您已经可以在本地合并分支:您只需先签出目标分支。
如果您有多个本地签出的同一回购文件夹,是的,您需要在它们之间 push/pull。

使用 git worktree,而不是检出目标分支(进行合并),或者不是推送到同一存储库的另一个检出文件夹,您需要 cd /path/to/destination/branch已经签出)。

想法是:

  • /path/to/your/repo(有一个像master这样的分支checked out)
  • /path/to/your/Branch1在回购之外,但通过git worktree文本符号链接机制链接回回购)
  • /path/to/your/Branch2, ...等等。

那么文档就清楚了:

When you are done with a linked working tree you can simply delete it.

The working tree’s administrative files in the repository (see "DETAILS" below) will eventually be removed automatically (see gc.worktreePruneExpire in git-config).
Or you can run git worktree prune in the main or any linked working tree to clean up any stale administrative files.