0%

git submodule

git submodule

git submodule,子模块,允许将一个git仓库作为另一个git仓库的子目录,能够让你将另一个仓库克隆到自己的项目中,同时保持提交的独立性。

添加子模块

将一个已存在的远程仓库添加到当前仓库作为子模块

1
git submodule add https://github.com/{username}/{repo}

默认情况下,子模块会将子项目放在当前仓库的同名目录中

如果需要将子项目放在其他目录

1
2
3
git submodule add https://github.com/{username}/{repo} path
# Example
git submodule add git@github.com:lvraikkonen/hexo-theme-next.git themes/next

此时运行git status会在目录下发现新增了.gitmodules文件

.gitmodules文件范例

1
2
3
[submodule "themes/hexo-theme-next"]
path = themes/hexo-theme-next
url = git@github.com:oahnus/hexo-theme-next.git

配置文件保存项目URL与本地目录之间的映射关系

如果有多个子模块,配置文件中会有多条记录

Clone 含有子模块的项目

当clone一个含有子模块的项目到本地时,仓库中默认会包含子模块目录,但目录内没有任何文件。

此时需要先运行git submodule init命令初始化本地配置文件,然后运行git submodule update命令拉取子模块代码

除此之外,在clone项目时,还可以添加--recurse-submodule选项,此选项会自动初始化并更新仓库中的每一个子模块以及嵌套子模块

如果已经clone项目但没有添加--recurse-submodule,可以通过运行git submodule update --init来完成相同的任务

如果需要初始化、抓取并检出任何嵌套的子模块, 可以使用 git submodule update --init --recursive

附录

git子模块文档