Git submodule 的入门操作

版权声明: https://blog.csdn.net/u011361138/article/details/83451552

1) 简单介绍

有种情况我们经常会遇到:某个工作中的项目需要包含并使用另一个项目。 也许是第三方库,或者你独立开发的,用于多个父项目的库。 现在问题来了:你想要把它们当做两个独立的项目,同时又想在一个项目中使用另一个。

2) 创建准备的项目仓库

在github上创建一个project仓库作为和一个module仓库来演示对submodule的操作, 下面project项目, module与它相同, 只包含一个readme.md文件.

# project 项目
[email protected]:xxxxx/project1.git
# module项目
[email protected]:xxxxx/module.git

3) 添加 submodule

通过如下命令在project目录下添加module, 首先切换到project目录下, cd ~/project

git submodule add https://github.com/xxx/module.git

等待结束

$ pwd
显示路径为 ~/project
$ ls
.  module/  readme.md .gitmodules

在module目录下 git status 查看状态

On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
    new file:   .gitmodules
    new file:   module

在module目录下

git add ./
git commit -m "add submodule"
git push

到这里你成功添加了一个submodule.

4) 克隆含有子模块的项目

切换到project2目录下, 执行下面命令

$ pwd
~/project2
$ git clone [email protected]:xxxxx/project1.git
.........省略
$ ls
.  module/  readme.md .gitmodules

其中有 module 目录, 不过是空的, 你必须运行两个命令:
git submodule init 用来初始化本地配置文件;
git submodule update 则从该项目中抓取所有数据并检出父项目中列出的合适的提交。
现在 module 子目录是处在和之前提交时相同的状态了。
补充: 如果在clone project 项目的同时加上--recursive参数, 它就会自动初始化并更新仓库中的每一个子模块。

5) 修改module

project2目录下

$ pwd
~/project2
$ ls
.  module/  readme.md .gitmodules
$ cd module 
$ ls
. readme.md 
$ touch a.py    
$ ls
. readme.md  a.py

module目录下添加文件a.py, 通过git status 查看状态

On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
  
    new file:   a.py

在module目录下

git add ./
git commit -m "add a.py"
git push

然后回退到上层目录project2目录下, 通过git status 查看状态

On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  
  	modified:   a.py (new commits)

在project2目录下

git add ./
git commit -m "update submodule"
git push

6) 更新子模块

现在我是另一个人,我想使用这次修改的提交, 我要切换到project1目录下执行git pull操作
, 同时到module目录下执行git pull 操作即可.

cd project1
git pull
git submodule update

参考文档:
https://git-scm.com/book/zh/v2/Git-工具-子模块

猜你喜欢

转载自blog.csdn.net/u011361138/article/details/83451552