Git submodule允许一个git仓库,作为另一个git仓库的子目录,并且保持父项目和子项目相互独立。
添加
cd <git repo dir>
git submodule add <仓库地址> <本地路径>
# 使用 -b 指定分支创建
git submodule add -b main [URL to Git repo] [Path]
# 修改已创建的为分支
git config -f .gitmodules submodule.<path>.branch main添加成功后,在父仓库根目录增加了.gitmodules文件,内容如下:
[submodule "themes/hugo-bootstrap-x"]
path = themes/hugo-bootstrap-x
url = https://github.com/xiexianbin/hugo-bootstrap-x.git并且在父仓库的.git配置文件中加入了submodule段。
cat .git/config
...
[submodule "themes/hugo-bootstrap-x"]
url = https://github.com/xiexianbin/hugo-bootstrap-x.git
active = true目录变更说明
添加后,影响的目录:
.gitmodules新增相关 path.git/config中新增子模块信息.git/modules/<path>子模块的.git文件夹- 代码路径新增 git submodule 指定的
<path>
检出子仓库
clone一个包含子仓库的仓库目录,并不会clone下子仓库的文件,需要添加如下操作:
git submodule init
git submodule update
# 或
git submodule update <path-of-submodule>
# 或
git submodule update --init <path-of-submodule>或者使用组合指令:
git submodule update --init --recursive此时子目录在一个未命名分支,此时子仓库有改动并没有检测到,切换到 master 分支,并 git pull 最新代码之后,回到主仓库目录,会显示子仓库修改,需要在主仓库提交修改,即修改指定的 commit id:
# 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 restore <file>..." to discard changes in working directory)
(commit or discard the untracked or modified content in submodules)
modified: themes/hugo-bootstrap-x (modified content)查看
查看 submodule 状态
git submodule status更新
git add themes/hugo-bootstrap-x
git commit -m "..."
git pushupdate –init 与 –remote 的区别
| 比较维度 | git submodule update --init | git submodule update --remote |
|---|---|---|
| 代码从哪来 | 主项目锁定的版本(主项目记录的 Commit ID) | 子模块自身的远程仓库(跟踪分支的最新 Commit) |
| 是否会更新版本号 | 否,严格对齐当前主项目指定的版本 | 是,会跳到子模块远端的最新版本 |
| 主要用途 | 同步/拉取子模块以匹配主项目要求 | 主动升级子模块依赖 |
| 未初始化时的处理 | 自动进行注册初始化并下载代码 | 若未曾初始化,需要搭配 --init 一起使用 |
使用 --remote 升级后,子模块指向的 Commit 变更仍需回到主仓库 git add <submodule> 并提交,才能将新版本固化到主项目中。
遍历所有的 submodule
- 获取每个 submodule 的 commit 缩写
git submodule foreach git rev-list HEAD --abbrev-commit --max-count=1- 遍历每个 submodule,并执行
git stash
git submodule foreach 'git stash'删除子仓库
# -f 同时删除子仓库的数据
git submodule deinit <path>或手动删除:
- 删除
.gitmodules里相关部分 - 删除
.git/config文件里相关字段 - 删除子仓库目录
$ git rm --cached <子仓库路径>如果未按照上述步骤删除,可能残留在 .git/modules 文件夹内