使用子模块为项目创建工作树

问题描述

我有一个顶级项目,大约有 10 个子模块和一些嵌套的子模块。

./top-project/
./top-project/module-a
./top-project/module-b
...

一些子模块有一个经典的 url,比如 url = git:software/module-a,其他的有一个 url 相对远程顶级项目,比如 url = ../module-b。顶级项目网址为 url = git:software/top-project

我想创建 top-project 及其所有子模块的工作树副本。

git worktree add -f ../top-project-v2

但我找不到让子模块指向其原始路径的方法。我希望 top-project-v2/module-a git 指向 top-project/module-a,而不是克隆一个全新的模块-a。

如果我执行 cd top-project-v2; git submodule upate --init --recursive,命令会成功,但子模块未链接到顶级项目子模块。

如果我执行 git checkout --recurse-submodules origin/v2,我会收到一个错误

git checkout --recurse-submodules origin/v2
fatal: not a git repository: ../../top-project/.git/worktrees/top-project-v2/modules/module-a
fatal: Could not reset submodule index

有什么办法吗?

解决方法

如果子模块不是可选的或便宜到无法获取,请将子模块历史记录作为分支和 git submodule init; git worktree add 放在主仓库中。