Pull latest changes for all git submodules

Pull latest changes for all git submodules

技术背景

在使用Git进行项目管理时,子模块(submodule)是一种很有用的功能,它允许你将一个Git仓库作为另一个Git仓库的子目录。当子模块有更新时,我们需要将这些最新的更改拉取到主项目中。

实现步骤

首次克隆仓库

如果你是第一次检出一个包含子模块的仓库,需要使用 --init 选项来初始化子模块:

1
git submodule update --init --recursive

Git 1.8.2及以上版本

对于Git 1.8.2及以上版本,可以使用 --remote 选项将子模块更新到远程分支的最新提交:

1
git submodule update --recursive --remote

Git 1.7.3及以上版本

如果你使用的是Git 1.7.3及以上版本,可以使用以下命令:

1
git submodule update --recursive

或者

1
git pull --recurse-submodules

开发过程中更新子模块

在开发过程中,你可以使用以下命令拉取主项目和子模块的最新更改:

1
git pull --recurse-submodules && git submodule update --recursive

将子模块更新到远程分支的最新提交

如果你想将子模块更新到远程分支的最新提交,可以使用以下命令:

1
git submodule foreach git pull origin master

或者

1
git submodule update --remote --merge

递归更新嵌套子模块

如果有嵌套子模块需要更新到最新版本,可以使用以下命令:

1
git submodule foreach --recursive git pull

使用别名简化操作

你可以在 .gitconfig 文件中添加别名来简化子模块更新的操作:

1
2
[alias]
updatesubs = "!sh -c \"git submodule init && git submodule update && git submodule status\" "

然后使用以下命令更新子模块:

1
git updatesubs

拉取所有Git仓库(包括子模块)

以下命令可以从所有Git仓库(无论是否为子模块)中拉取最新更改:

1
2
ROOT=$(git rev-parse --show-toplevel 2> /dev/null)
find "$ROOT" -name .git -type d -execdir git pull -v ';'

核心代码

以下是一些常用的核心代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
# 首次克隆并初始化子模块
git clone [email protected]:speedovation/kiwi-resources.git resources
git submodule init

# 开发过程中更新子模块
git pull --recurse-submodules && git submodule update --recursive

# 将子模块更新到远程分支的最新提交
git submodule foreach git pull origin master

# 递归更新嵌套子模块
git submodule foreach --recursive git pull

最佳实践

  • 明确更新需求:根据具体情况选择合适的更新命令,例如是否需要将子模块更新到远程分支的最新提交。
  • 使用别名:为常用的子模块更新命令设置别名,提高操作效率。
  • 定期更新:定期拉取子模块的最新更改,确保主项目使用的是最新的子模块代码。

常见问题

git pull --recurse-submodulesgit submodule update --recursive --remote 的区别

从测试来看,git pull --recurse-submodules 可能无法将子模块更新到 .gitmodules 中定义的远程分支的最新提交,而 git submodule update --recursive --remote 可以。

子模块默认分支不是 master 的情况

如果子模块的默认分支不是 master,可以使用以下脚本自动化更新:

1
2
3
git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'

子模块更新时遇到错误

如果在子模块更新过程中遇到错误,首先检查网络连接是否正常,然后查看错误信息,根据具体错误进行排查和解决。


Pull latest changes for all git submodules
https://119291.xyz/posts/2025-05-13.pull-latest-changes-for-all-git-submodules/
作者
ww
发布于
2025年5月13日
许可协议