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


当前回答

在这个网站上尝试了所有不同的答案后,我最终得到了这个解决方案:

#!/bin/sh
path="$1"
if [ ! -f "$path/.git" ]; then
  echo "$path is no valid git submodule"
  exit 1
fi
git submodule deinit -f $path &&
git rm --cached $path &&
rm -rf .git/modules/$path &&
rm -rf $path &&
git reset HEAD .gitmodules &&
git config -f .gitmodules --remove-section submodule.$path

这将恢复与添加子模块之前完全相同的状态。您可以立即再次添加子模块,这在大多数答案中是不可能的。

git submodule add $giturl test
aboveScript test

这将使您得到一个干净的签出,无需提交任何更改。

这是用以下方法测试的:

$ git --version
git version 1.9.3 (Apple Git-50)

其他回答

这个问题的大多数答案都过时、不完整或不必要的复杂。

使用git 1.7.8或更高版本克隆的子模块将在您的本地存储库中最多留下四条自己的痕迹。删除这四个轨迹的过程由以下三个命令给出:

# Remove the submodule entry from .git/config
git submodule deinit -f path/to/submodule

# Remove the submodule directory from the superproject's .git/modules directory
rm -rf .git/modules/path/to/submodule

# Remove the entry in .gitmodules and remove the submodule directory located at path/to/submodule
git rm -f path/to/submodule

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

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

您必须删除.gitmodules和.git/config中的条目,并从历史记录中删除模块的目录:

git rm --cached path/to/submodule

如果你在git的邮件列表上写东西,很可能有人会为你编写一个shell脚本。

只是一张纸条。从git1.8.5.2开始,有两个命令可以执行:

git rm -r the_submodule
rm -rf .git/modules/the_submodule

正如@Mark Cheverton的回答正确指出的那样,如果没有使用第二行,即使您现在删除了子模块,剩余的.git/modules/the_submodule文件夹也将阻止将来添加或替换相同的子模块。此外,正如@VonC所提到的,gitrm将在子模块上完成大部分工作。

--更新(07/05/2017)--

为了澄清,_submodule是项目中子模块的相对路径。例如,如果子模块位于子目录subdir内,则为subdir/my_submodule。

正如评论和其他答案中正确指出的,这两个命令(虽然功能上足以删除子模块)确实在.git/config的[submodule“the_submodule”]部分留下了痕迹(截至2017年7月),可以使用第三个命令删除:

git config -f .git/config --remove-section submodule.the_submodule 2> /dev/null