如何删除Git子模块?为什么我不能git子模块rm模块名称?


当前回答

您可以使用别名自动化其他人提供的解决方案:

[alias]
  rms = "!f(){ git rm --cached \"$1\";rm -r \"$1\";git config -f .gitmodules --remove-section \"submodule.$1\";git config -f .git/config --remove-section \"submodule.$1\";git add .gitmodules; }; f"

将其放入git配置中,然后可以执行:git rms path/to/submodule

其他回答

您可以使用别名自动化其他人提供的解决方案:

[alias]
  rms = "!f(){ git rm --cached \"$1\";rm -r \"$1\";git config -f .gitmodules --remove-section \"submodule.$1\";git config -f .git/config --remove-section \"submodule.$1\";git add .gitmodules; }; f"

将其放入git配置中,然后可以执行:git rms path/to/submodule

除了这些建议之外,我还必须rm-Rf.git/modules/path/to/submodule,才能添加一个同名的新子模块(在我的例子中,我用原来的fork替换了一个fork)

2012年12月我正在做的事情(结合了这些答案中的大部分):

oldPath="vendor/example"
git config -f .git/config --remove-section "submodule.${oldPath}"
git config -f .gitmodules --remove-section "submodule.${oldPath}"
git rm --cached "${oldPath}"
rm -rf "${oldPath}"              ## remove src (optional)
rm -rf ".git/modules/${oldPath}" ## cleanup gitdir (optional housekeeping)
git add .gitmodules
git commit -m "Removed ${oldPath}"

在现代git中(我在2022年编写了这篇文章,并更新了git安装),这变得非常简单:

运行git-rm<path to submodule>并提交。

这将删除<path to submodule>处的文件树,以及.gitmodules文件中的子模块条目。即,删除存储库中子模块的所有痕迹。

然而,正如文档所指出的,子模块的.git目录(在主项目.git目录的模块/目录中)被保留了下来,“这样就可以在不需要从另一个存储库获取的情况下签出过去的提交”。如果您仍然想删除此信息,请手动删除.git/modules/中的子模块目录,并删除.git/config文件中的子模板条目

rm-rf.git/modules/<子模块路径>,以及git-config—删除节子模块<子模块路径>。



较旧的社区wiki说明:

通过Git子模块教程页面:

要删除子模块,您需要:

从.gitmodules文件中删除相关部分。暂存.gitmodules更改:git-add.gitmoduls从.git/config中删除相关部分。从工作树中删除子模块文件,并索引:git rm--cached path_to_submodule(无斜杠)。删除子模块的.git目录:rm-rf.git/modules/path_to_submodule提交更改:gitcommit-m“已删除子模块<name>”删除现在未跟踪的子模块文件:rm-rf path_to_submodule

另请参见:以下替代步骤。

如果您刚刚添加了子模块,例如,您只是添加了错误的子模块或将其添加到了错误的位置,只需执行git stash,然后删除文件夹。这是假设添加子模块是您在最近的回购中唯一做的事情。