子模块
将一个Git仓库当作另一个Git仓库的子目录,并进行单独维护。
git submodule 和 git subtree的区别
git submodule类似于引用 基本不占用额外空间, 而git subtree类似于拷贝 会占用较大的额外空间;
git submodule 用法
1. 添加子模块
- 语法:git submodule add 仓库地址 路径
添加
submodule
// git-submodule-parent 下
git submodule add git@github.com:EchoVie/git-submodule-child.git childModule
提交 git-submodule-parent 的修改
git status
git add .
git commit -m '创建一个submodule childModule'
git push origin main -u
查看仓库
2. 克隆 带有 submodule 的仓库
方法1:
- 克隆仓库
git clone 仓库地址 克隆到的文件夹名 git submodule init初始化git submodule update --remote进行更新不加 --remote 可能会导致 子模块的头指针偏移,更新的子模块不是最新的数据
方法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: 父仓库中修改(不推荐)
- 跳转到子目录
cd childModule
- 查看当前分支 查看分支是否发生偏移
如果发生偏移,修正回来
- 修改内容
echo 'hello world' > 2.txt
- 提交修改
git add .
git commit -m ' 父仓库的子目录中修改子仓库的内容'
- 推到仓库 查看远程
git remote -v
👆 显示 origin 为子仓库的地址
git push origin main
方法2: 子仓库中修改
- 修改内容
echo 'hello world' > 3.txt
- 提交修改
git add .
git commit -m ' 子仓库中修改子仓库的内容'
- 推到仓库 查看远程
git push origin main
4. 更新
方法1:
跳转到子目录,然后git pull
方法2:
遍历所有子模块并更新
git submodule foreach git pull
git subtree 用法(推荐)
1. 给远程仓库起别名
git remote add subtree-origin git@github.com:EchoVie/git-subtree-child.git
2. 建立子模块
语法:git subtree add -P <prefix> <repository> <ref>
git subtree add -P git-subtree-child subtree-origin main
注意:会生成本地父仓库的一次提交记录
3. 更新
方法1:父仓库中修改子仓库的内容
- 跳转到子模块
cd git-subtree-child
- 修改
echo '父仓库中修改子仓库的内容' > 1.txt
- 提交
git add .
git commit -m '父仓库中修改子仓库的内容'
注意:会生成本地父仓库的一次提交记录
- 跳转到父级目录
cd ..
- 推送到远程
语法:
git subtree push -P <prefix> <repo> <ref>
git subtree push -P git-subtree-child subtree-origin main
方法2: 子仓库自我更新
- 修改
echo '子仓库中的修改' > 2.txt
- 提交
git add .
git commit -m '子仓库中的修改'
- 推送 推送之前先更新一下,有冲突时需解决冲突
git fetch origin main
git merge origin main

git push origin main
- 子仓库更新后,父仓库的更新操作
语法:
git subtree pull -P <prefix> <repo> <ref>
git subtree pull -P git-subtree-child subtree-origin main
4. 推送远程的父仓库
git push origin main