此文已由作者张磊薪授权网易云社区发布。
欢迎访问网易云社区,了解更多网易技术产品运营经验。
前言
submodule 目前对 git 仓库拆分的已有实现之一。环境 git version 2.7.4.windows.1
准备工作
首先创建主仓库 subrepo-master,随意提交一次文本,接着拉取到本地
建立子仓库 subrepo 和 subrepo1,随意提交一次文本
操作
在主仓库下运行如下命令后,可以看到在仓库中多出来文件 subrepo 以及 .gitmodules
git submodule add [subrepo url]
运行 git status
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: .gitmodules new file: subrepo
接着添加 submodule1,并指定路径
git submodule add [subrepo1 url] ./module/module1
运行 git status 得到
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: .gitmodules new file: module/module1 new file: subrepo
cat .gitmodules 得到
[submodule "subrepo"] path = subrepo url = [subrepo url] [submodule "module/module1"] path = module/module1 url = [subrepo1 url]
这是一份子模块与路径的映射关系图,这份文件很重要,git 根据这份文件去识别 submodule,所以这份文件应该被加入版本控制
接着运行提交命令,可以看到三个目录都被添加到仓库了,注意子模块下面的文件并没有被添加进去。160000 的含义是这是 Git 中的一种特殊模式,基本上意味着您将提交记录为目录条目而不是子目录或文件。 然后提交到远端,就有了一个 submodule 的仓库 :)
$ git commit -m "add submodule" [master 5c88033] add submodule 3 files changed, 8 insertions(+) create mode 100644 .gitmodules create mode 160000 module/module1 create mode 160000 subrepo
接下来模拟多人协作,首先新建一个文件夹,运行命令后,会发现 subrepo 以及 module/module1 目录并没有文件。
git clone [subrepo-master url]
这时候需要运行命令 git submodule init 去初始化本地配置文件以及 git submodule update 拉取代码。
$ git submodule init Submodule 'module/module1' (https://github.com/xxx/subrepo1.git) registered for path 'module/module1' Submodul