为什么 git worktree add 创建一个分支,我可以删除它吗?

Why does git worktree add create a branch, and can I delete it?

我使用 git worktree add 创建了一个新的工作树。我注意到它在 repo 中创建了一个与工作树同名的新分支。这个分支是做什么用的?

我已经检查了第二个工作树中另一个预先存在的分支。我可以随意删除 git worktree add 创建的分支吗?

git worktree --help 清楚地提到了这一点,如下所示。

COMMANDS
       add <path> [<branch>]
           Create <path> and checkout <branch> into it. The new working directory is linked to the current repository, sharing everything
           except working directory specific files such as HEAD, index, etc.

           If <branch> is omitted and neither -b nor -B is used, then, as a convenience, a new branch based at HEAD is created automatically,
           as if -b $(basename <path>) was specified.

       prune
           Prune working tree information in $GIT_DIR/worktrees.

该分支是必需的,因为您不能同时在不同的工作树中签出相同的分支。

因此,如果您在添加工作树时没有指定分支,那么 git 将根据您当前的分支和工作树目录的名称自动添加一个。

您可能会问,为什么同一个分行不能结账两次?想想当你提交给 B 时工作树 A 会发生什么,如果他们都共享分支......工作树 A 会将 B 中的提交视为本地差异,但相反!就像你那样做 git reset --soft HEAD^...那会很危险。

顺便说一句,这就是为什么你不能推送到已签出的非裸存储库的分支的原因。

关于你的最后一个问题:你能删除分支吗?当然,那个分支一点也不特别。只要没有在任何地方签出,就可以删除它。

似乎您可以 运行 在分离模式下使用 --detach,这不会创建分支。如果您不打算在工作树中进行修改,而只是 运行 构建或 运行 测试,这可能很有用。

来源: https://stacktoheap.com/blog/2016/01/19/using-multiple-worktrees-with-git/#long-running-tasks

当其他人回答这个问题时,我在此处输入删除 folder、删除 worktree 和删除 branch 的命令:

首先,列出所有工作树以仔细检查...

$ git worktree list

然后,删除worktree的文件夹

$ rm -rf path/to/worktree

之后,删除工作树本身

$ git worktree prune

如果您有多个工作树,上述命令只会修剪其路径不再存在的工作树,所以不用担心!

最后,删除分支(与工作树相同的分支名称)

$ git branch -D <branch-name>

从 Git 2.17.0 开始,您可以安全地 运行 这个一体化命令

git worktree remove <path>
如果指定

git worktree 将添加一个新分支:

If <commit-ish> is omitted and neither -b nor -B nor --detach used, then, as a convenience, a new branch based at HEAD is created automatically, as if -b $(basename <path>) was specified.

Since Git 2.17, you can delete that branch with git worktree remove.

但是,同样的 remove 命令还包括:

Unclean working trees or ones with submodules can be removed with --force.
The main working tree cannot be removed.

正确...除了 --force 在 Git 2.17.

中没有 完全 实现

在 Git 2.18(2018 年第 2 季度)中,“git worktree remove”了解到“-f”是“--force”选项的 shorthand,就像 "git worktree add".

参见 commit d228eea (17 Apr 2018) by Stefan Beller (stefanbeller)
帮助:Eric Sunshine (sunshineco).
(由 Junio C Hamano -- gitster -- in commit 90186fa 合并,2018 年 5 月 8 日)

worktree: accept -f as short for --force for removal

Many commands support a "--force" option, frequently abbreviated as "-f".
However, "git worktree remove"'s hand-rolled OPT_BOOL forgets to recognize the short form, despite git-worktree.txt documenting "-f" as supported.
Replace OPT_BOOL with OPT__FORCE, which provides "-f" for free, and makes 'remove' consistent with 'add' option parsing (which also specifies the PARSE_OPT_NOCOMPLETE flag).