Git系列讲解(二):项目子模块submodule

Git支持在项目中添加别的项目为子模块,这篇文章将详细讲解其中用法

一. 为Git项目添加子模块

这里说的子模块其实就是另外一个Git管理的项目。假设现在已经有了名为subsampleproject的项目,将其作为sampleproject的子模块。

1. 先将主项目克隆到本地

克隆sampleproject项目到本地

sun@sun-pc:~/myProjects/codechina$ git clone [email protected]:In_engineer/sampleproject.git

2. 使用git命令添加子模块

进入sampleproject目录中,将subsampleproject添加到sampleproject的3rd_party中,注意这里的3rd_party不需要手动创建。这一步执行完就可以看到3rd_party中就已经包含了subsampleproject的内容了。

sun@sun-pc:~/myProjects/codechina/sampleproject$ git submodule add [email protected]:In_engineer/subsampleproject.git 3rd_party
正克隆到 '/home/sun/codechina/sampleproject/3rd_party'...
remote: Enumerating objects: 73, done.
remote: Total 73 (delta 0), reused 0 (delta 0), pack-reused 73
接收对象中: 100% (73/73), 128.83 KiB | 2.01 MiB/s, 完成.
处理 delta 中: 100% (1/1), 完成.

3. 添加完子模块后目录的变化

① 项目中多了子模块的内容
在这里插入图片描述
② 多了一个.gitmodule隐藏文件
在这里插入图片描述
.git/config发生改变
在这里插入图片描述

4. 把变化提交到远程仓库

这里不需要git add,因为git submodule会自动将变化更新到暂存区
在这里插入图片描述远程仓库的变化如下:
在这里插入图片描述

二. 克隆包含子模块的项目

1. 克隆项目

sun@ubuntu:~/myProject$ git clone [email protected]:In_engineer/sampleproject.git

2. 同步子模块的url信息

sun@ubuntu:~/myProject/sampleproject$ git submodule sync'3rd_party' 同步子模组 url
...

3. 初始化本地配置文件

如果第二步不做,有可能会报错:子模组 ‘3rd_party’ ([email protected]:In_engineer/subsampleproject.git) 未对路径 ‘3rd_party’ 注册

sun@ubuntu:~/myProject/sampleproject$ git submodule init

4. 将子模块更新到本地

sun@ubuntu:~/myProject/sampleproject$ git submodule update
正克隆到 '3rd_party'...
remote: Enumerating objects: 73, done.
remote: Total 73 (delta 0), reused 0 (delta 0), pack-reused 73
接收对象中: 100% (73/73), 128.83 KiB | 0 bytes/s, 完成.
处理 delta 中: 100% (1/1), 完成.
检查连接... 完成。
子模组路径 '3rd_party':检出 '8c63ff33ccb67b51078ddf09f3054cb068b680aa'

三. 在子模块中修改内容并上传到其远程仓库

子模块也是单独的一个仓库管理,所以大体步骤和正常提交一致,可以参考: Git系列讲解 —— 同一分支下多人协同开发.
这里需要注意的是通过上面克隆下的子模块仓库没有在一个特定的分支,需要先创建个本地分支,然后提交的时候merge到master分支进行提交

sun@ubuntu:~/myProject/sampleproject/3rd_party$ git branch dev
sun@ubuntu:~/myProject/sampleproject/3rd_party$ git checkout dev
sun@ubuntu:~/myProject/sampleproject/3rd_party$ touch test.c
sun@ubuntu:~/myProject/sampleproject/3rd_party$ git add test.c
sun@ubuntu:~/myProject/sampleproject/3rd_party$ git commit -m "add test.c"
sun@ubuntu:~/myProject/sampleproject/3rd_party$ git checkout master
sun@ubuntu:~/myProject/sampleproject/3rd_party$ git push origin master

猜你喜欢

转载自blog.csdn.net/In_engineer/article/details/122254930