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


当前回答

所有的答案看起来都过时了。我使用的是git版本2.28.0。一行回答是,

git rm path-to-submodule

然而,即使从源代码管理中删除了子模块,.git/modules/path到子模块仍然包含子模块存储库,.git/config包含其URL,因此您仍然需要手动删除这些子模块:

git config --remove-section submodule.path-to-submodule
rm -rf .git/modules/path-to-submodule

有时,必须使用-f标志:

$ git rm -f img2vec

例如,因为您可能会收到如下错误:

$ git rm img2vec/
error: the following file has changes staged in the index:
    img2vec
(use --cached to keep the file, or -f to force removal)

其他回答

我不得不进一步执行John Douth的步骤,并将其cd到子模块的目录中,然后删除Git存储库:

cd submodule
rm -fr .git

然后,我可以将文件作为父Git存储库的一部分提交,而无需对子模块的旧引用。

project dir:     ~/foo_project/
submodule:       ~/foo_project/lib/asubmodule
- - - - - - - - - - - - - - - - - - - - - - - - -
run:
  1.   cd ~/foo_project
  2.   git rm lib/asubmodule && 
          rm .git/modules/lib/asubmodule && 
            git submodule lib/asubmodule deinit --recursive --force

所有的答案看起来都过时了。我使用的是git版本2.28.0。一行回答是,

git rm path-to-submodule

然而,即使从源代码管理中删除了子模块,.git/modules/path到子模块仍然包含子模块存储库,.git/config包含其URL,因此您仍然需要手动删除这些子模块:

git config --remove-section submodule.path-to-submodule
rm -rf .git/modules/path-to-submodule

有时,必须使用-f标志:

$ git rm -f img2vec

例如,因为您可能会收到如下错误:

$ git rm img2vec/
error: the following file has changes staged in the index:
    img2vec
(use --cached to keep the file, or -f to force removal)

简单的步骤

删除配置项:git-config-f.git/config--删除节子模块$submodulename git-config-f.gitmodules—删除部分子模块$子模块名称从索引中删除目录:git rm--cached$submodule路径犯罪删除未使用的文件:rm-rf$submodulepathrm-rf.git/modules/$submodulename

请注意:$submodulepath不包含前导或尾随斜杠。

出身背景

当您执行git子模块add时,它只将其添加到.gitmodules中,但是完成git子模块init后,它将添加到.git/config中。

因此,如果您希望删除模块,但能够快速恢复,那么就这样做:

git rm --cached $submodulepath
git config -f .git/config --remove-section submodule.$submodulepath

首先执行git rebase HEAD和git commit是一个好主意最后,如果你把这个写在脚本中。

还可以看看我可以取消填充Git子模块吗?的答案?。

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

[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