git submodule 和 git subtree

847 阅读3分钟

子模块

将一个Git仓库当作另一个Git仓库的子目录,并进行单独维护。

git submodulegit subtree的区别

git submodule类似于引用 基本不占用额外空间, 而git subtree类似于拷贝 会占用较大的额外空间;

image.png image.png

git submodule 用法

1. 添加子模块

  • 语法:git submodule add 仓库地址 路径 添加 submodule
// git-submodule-parent 下
git submodule add git@github.com:EchoVie/git-submodule-child.git childModule

image.png

提交 git-submodule-parent 的修改

git status
git add .
git commit -m '创建一个submodule childModule'
git push origin main -u

image.png

查看仓库 image.png

2. 克隆 带有 submodule 的仓库

方法1:

  1. 克隆仓库git clone 仓库地址 克隆到的文件夹名
  2. git submodule init 初始化
  3. git submodule update --remote 进行更新

    不加 --remote 可能会导致 子模块的头指针偏移,更新的子模块不是最新的数据 image.png

方法2:

git clone 仓库地址 克隆到的文件夹名 --recursive --remote

git clone git@github.com:EchoVie/git-submodule-parent.git clone-git-module-parent --recursive --remote

注意:以上两种方法 submodule 的内容会添加到暂存区

git add .
git commit -m ''
git push origin main

3. 修改子仓库

方法1: 父仓库中修改(不推荐)

  1. 跳转到子目录
cd childModule
  1. 查看当前分支 查看分支是否发生偏移

image.png

如果发生偏移,修正回来

image.png

  1. 修改内容
echo 'hello world' > 2.txt
  1. 提交修改
git add .
git commit -m ' 父仓库的子目录中修改子仓库的内容'
  1. 推到仓库 查看远程
git remote -v

image.png

👆 显示 origin 为子仓库的地址

git push origin main

方法2: 子仓库中修改

  1. 修改内容
echo 'hello world' > 3.txt
  1. 提交修改
git add .
git commit -m ' 子仓库中修改子仓库的内容'
  1. 推到仓库 查看远程
git push origin main

4. 更新

方法1:

跳转到子目录,然后git pull

image.png

方法2:

遍历所有子模块并更新

git submodule foreach git pull 

git subtree 用法(推荐)

1. 给远程仓库起别名

git remote add subtree-origin git@github.com:EchoVie/git-subtree-child.git

image.png

2. 建立子模块

语法:git subtree add -P <prefix> <repository> <ref>

git subtree add -P git-subtree-child subtree-origin main

image.png

注意:会生成本地父仓库的一次提交记录

image.png

3. 更新

方法1:父仓库中修改子仓库的内容

  1. 跳转到子模块
cd git-subtree-child
  1. 修改
echo '父仓库中修改子仓库的内容' > 1.txt
  1. 提交
git add .
git commit -m '父仓库中修改子仓库的内容'

注意:会生成本地父仓库的一次提交记录

image.png

  1. 跳转到父级目录
cd ..
  1. 推送到远程 语法:git subtree push -P <prefix> <repo> <ref>
git subtree push -P git-subtree-child subtree-origin main

方法2: 子仓库自我更新

  1. 修改
echo '子仓库中的修改' > 2.txt
  1. 提交
git add .
git commit -m '子仓库中的修改'
  1. 推送 推送之前先更新一下,有冲突时需解决冲突
git fetch origin main
git merge origin main

![image.png](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cbae84167d354e0393c8f303ff8c8e94~tplv-k3u1fbpfcp-watermark.image?)
git push origin main
  1. 子仓库更新后,父仓库的更新操作 语法:git subtree pull -P <prefix> <repo> <ref>
git subtree pull -P git-subtree-child subtree-origin main

4. 推送远程的父仓库

git push origin main

image.png