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


当前回答

可以通过运行git rm<submodule path>和git commit来删除子模块。这可以使用git-restore撤消。删除将删除超级项目的跟踪数据,这些数据既是gitlink条目,也是.gitmodules文件中的部分。子模块的工作目录从文件系统中删除,但Git目录被保留下来,以便可以在不需要从另一个存储库获取的情况下签出过去的提交。要完全删除子模块,请另外手动删除$GIT_DIR/modules/<name>/。

来源:git help子模块

其他回答

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

#!/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)
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

总而言之,这是您应该做的:

设置path_to_submodule变量(无尾随斜杠):

path_to_submodule=path/to/submodule

从.gitmodules文件中删除相关行:

git config -f .gitmodules --remove-section submodule.$path_to_submodule

从.git/config中删除相关部分

git config -f .git/config --remove-section submodule.$path_to_submodule

仅从索引中取消存储并删除$path_to_submodule(以防止丢失信息)

git rm --cached $path_to_submodule

跟踪对.gitmodules所做的更改

git add .gitmodules

提交超级项目

git commit -m "Remove submodule submodule_name"

删除现在未跟踪的子模块文件

rm -rf $path_to_submodule

rm -rf .git/modules/$path_to_submodule

另请参见:备选指导线

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

使用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

要删除添加的子模块,请使用:

REPOSITORY=blah@blah.com:repos/blah.git
MOD_DIR=lib/blah
git submodule add $REPOSITORY $MOD_DIR

Run:

git rm $MOD_DIR

就是这样。

对于旧版本的git(约为1.8.5,实际上甚至在2.26.2中),请使用:

git submodule deinit $MOD_DIR
git rm $MOD_DIR
git config -f .gitmodules --remove-section submodule.$MOD_DIR