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
添加成功后,在父仓库根目录增加了.gitmodule
文件,内容如下:
[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 "检出指定的代码"
或者使用组合指令:
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)
更新
git add themes/hugo-bootstrap-x
git commit -m "..."
git push
遍历所有的submodule
获取每个 submodule 的 commit 缩写
git submodule foreach git rev-list HEAD --abbrev-commit --max-count=1
删除子仓库
# -f 同时删除子仓库的数据
git submodule deinit <path>
或手动删除:
- 删除
.gitsubmodule
里相关部分
- 删除
.git/config
文件里相关字段
- 删除子仓库目录
$ git rm --cached <子仓库路径>
如果未按照上述步骤删除,可能残留在 .git/modudles
文件夹内