git submodule add
命令接受 --name
选项,该选项允许您为子模块指定逻辑名称。否则,子模块将以创建它的路径命名。
创建子模块后有没有办法更改此逻辑名称?
从 Git 版本 2.30.1 开始,除了完全删除子模块并从头开始重新创建之外,我还没有找到使用 Git 命令行执行此操作的方法。
为了重命名 Git 子模块,需要更改 4 件事:
.gitmodules
文件中子模块标题的名称。.git/modules
树下的位置。.git
文件的内容。.git/modules
树下子模块中指定的工作树位置。这是可行的,但可能会很混乱。如果您勇敢、鲁莽和/或绝望,请继续。
假设您在
vendor/libfoo
中保存了一个子模块,现在您想为其指定逻辑名称 vendor-libfoo
,而不更改其在工作树中的物理位置。
这是相应的
.gitmodules
文件:
[submodule "vendor/libfoo"]
path = vendor/libfoo
url = https://git.example.net/libfoo
并且
vendor/libfoo/.git
将是一个文本文件(不是目录,如顶级 git 存储库),包含:
gitdir: ../../.git/modules/vendor/libfoo
此文件指向存储 Git 数据文件的位置,即目录
.git/modules/vendor/libfoo
。
文件
.git/modules/vendor/libfoo/config
将包含(除其他外):
[core]
worktree = ../../../../vendor/libfoo
所有这些都必须调整才能做出改变!
[submodule "vendor/libfoo"]
更改为 [submodule "vendor-libfoo"]
,但不要更改该部分标题下的 path =
选项。
.git/modules/vendor-libfoo
而不是
.git/modules/vendor/libfoo
中查找此模块。因此,我们必须将后者重命名为前者,以反映步骤 1 中的更改。
vendor/libfoo/.git
的内容将是错误的,因为相对路径将不再指向正确的位置。我们必须将
../../.git/modules/vendor/libfoo
更改为
../../.git/modules/vendor-libfoo
,以反映步骤 2 中的更改。
worktree = ../../../../vendor/libfoo
中的
.git/modules/vendor-libfoo
选项也会出错。将其更改为
../../../vendor/libfoo
以反映我们已将此目录在
.git/modules
范围内向上移动了 1 级。
理论上这个过程可以脚本化/自动化,但正确解析 Git 配置格式可能会遇到困难。在大多数情况下,您可能可以通过正则表达式替换来逃脱。
祝你好运!也许希望这个功能在 git 的后续版本中得到更多关注。