【工具】Git 子仓库管理

文章目录

    • [添加 submodule](#添加 submodule)
    • [克隆带 submodule 的仓库](#克隆带 submodule 的仓库)
    • [更新 submodule](#更新 submodule)
    • [删除 submodule](#删除 submodule)

更好的阅读体验https://wiki.dwj601.cn/develop/tools/git/submodule/


当项目依赖另一个仓库(例如公共工具库、第三方组件、自家多个项目共用的模块)时,可以用 git submodule 将它挂载进来,而不是复制代码。这样的好处在于:

  • 独立更新或回退子仓库版本;
  • 避免将子仓库的提交历史混入主仓库;
  • 保持版本可控,而不是直接拉取最新代码。

添加 submodule

bash 复制代码
git submodule add <submodule_remote_url> <submodule_local_path>

克隆带 submodule 的仓库

标准方法:

bash 复制代码
# 克隆主仓库
git clone <remote_url>

# 进入主仓库
cd <project>

# 初始化子模块配置
git submodule init

# 同步数据
git submodule update

一步到位(克隆时):

bash 复制代码
git clone --recurse-submodules <remote_url>

一步到位(克隆后):

bash 复制代码
# 克隆主仓库
git clone <remote_url>

# 进入主仓库
cd <project>

# 克隆子仓库
git submodule update --init

更新 submodule

submodule 并不会自动同步最新代码,需要手动更新。

bash 复制代码
# 进入子仓库目录
cd <submodule>

# 同步代码
git pull <submodule_remote_name> <submodule_branch>

删除 submodule

bash 复制代码
# 删除子仓库
git rm -rf <submodule>

# 删除子仓库缓存
rm -rf .git/modules/<submodule>

# 删除子仓库配置
git config -f .git/config --remove-section submodule.<submodule>
相关推荐
醇氧9 小时前
【git】WARNING: connection is not using a post-quantum key exchange algorithm.
git
一只程序熊10 小时前
Git不常用操作记录
git
小龙10 小时前
【Git 报错解决】 远程仓库 origin 已存在(`remote origin already exists`)
git·报错
BORN(^-^)18 小时前
Git 操作概要
git
bigHead-21 小时前
Git合并操作详解:安全高效地合并远程分支
git·安全·elasticsearch
C_心欲无痕21 小时前
ts - 交叉类型
前端·git·typescript
秋饼1 天前
【K8S测试程序--git地址】
git·容器·kubernetes
小龙1 天前
【Git 报错解决】本地无有效提交无法推送(`src refspec main does not match any`)
git·github·报错
小扶苏1 天前
删除git全局账号信息并设置成新的账号密码命令
git
Greg_Zhong2 天前
Git创建任务分支进行开发,最后合并主分支master【纯git命令执行过程】阐述
git