◆

Git submodule 子模块添加拉取更新与移除详解

2023-02-02 01:370

创建子项目

git submodule add https://gitee.com/miofly/apps-template

自定义名称

git submodule add https://gitee.com/miofly/apps-template customName

拉取指定分支

git submodule add -b dev https://gitee.com/miofly/apps-template customName

子模块拉取

对于主项目使用普通的 clone 操作并不会拉取到子模块中的实际代码。 如果希望子模块代码也获取到,一种方式是在克隆主项目的时候带上参数 --recurse-submodules,这样会递归地将项目中所有子模块的代码拉取。

git clone https://github.com/username/project-main.git --recurse-submodules

指定分支

git clone https://github.com/username/project-main.git -b dev --recurse-submodules

另一种方式:它会根据主项目的配置信息,拉取更新子模块中的代码。

git submodule init # 初始化本地配置文件
git submodule update # 从该项目中抓取所有数据并检出父项目中列出的合适的提交。

合成一个命令

git submodule update --init

抓取嵌套的子模块

git submodule update --init --recursive

改变子模块的分支

git config -f .gitmodules submodule.yourSubmoduleName.branch stable

子模块代码有更新

方式一:进入到子模块目录执行拉取操作

git pull origin master

当主项目的子项目特别多时,可能会不太方便,此时可以使用 git submodule 的一个命令 foreach 执行

git submodule foreach 'git pull origin master'

方式二:

从远端拉取更新

git submodule update --remote

指定子模块

git submodule update --remote common

加入 merge 与 rebase 参数

git submodule update --remote --merge
git submodule update --remote --rebase

如果不加入 merge 与 rebase,git 会将子模块更新为服务器上的状态。并且会将项目重置为一个游离的 HEAD 状态。 这时,需要手动切换到正常的分支。

如何移除 submodule 子项目

假设子项目的路径在 apps/apps-template

  • 第一步
git submodule deinit apps/apps-template

执行后会删除 .git/config 中记录的 submodule 信息

  • 第二步
git rm apps/apps-template

执行后移除了 apps/apps-template 文件夹,并自动在 .gitmodules 中删除了配置信息

  • 第三步
rm -rf .git/modules/apps/apps-template

执行后移除了 git modules 对应的子模块信息

本地子模块有修改,强制删除,这个命令如果添加上参数 --force(-f),则子模块工作区内即使有本地的修改,也会被移除。

git submodule deinit -f apps/apps-template
git rm apps/apps-template -f
💬留言板0

还没有留言,来发表第一条吧~

PAGE LOAD / LIVEGit submodule 子模块添加拉取更新与移除详解加载中