git submodule
git submodule,子模块,允许将一个git仓库作为另一个git仓库的子目录,能够让你将另一个仓库克隆到自己的项目中,同时保持提交的独立性。
添加子模块
将一个已存在的远程仓库添加到当前仓库作为子模块
1 | git submodule add https://github.com/{username}/{repo} |
默认情况下,子模块会将子项目放在当前仓库的同名目录中
如果需要将子项目放在其他目录
1 | git submodule add https://github.com/{username}/{repo} path |
此时运行git status
会在目录下发现新增了.gitmodules
文件
.gitmodules文件范例
1 | [submodule "themes/hexo-theme-next"] |
配置文件保存项目URL与本地目录之间的映射关系
如果有多个子模块,配置文件中会有多条记录
Clone 含有子模块的项目
当clone一个含有子模块的项目到本地时,仓库中默认会包含子模块目录,但目录内没有任何文件。
此时需要先运行git submodule init
命令初始化本地配置文件,然后运行git submodule update
命令拉取子模块代码
除此之外,在clone项目时,还可以添加--recurse-submodule
选项,此选项会自动初始化并更新仓库中的每一个子模块以及嵌套子模块
如果已经clone项目但没有添加--recurse-submodule
,可以通过运行git submodule update --init
来完成相同的任务
如果需要初始化、抓取并检出任何嵌套的子模块, 可以使用 git submodule update --init --recursive