Github Action更新Git子模块时出现‘拒绝合并无关历史’错误
解决GitHub Action中Git子模块合并历史冲突问题
问题根源
GitHub Actions的actions/checkout@v4默认采用浅克隆(仅拉取最近1次提交),导致子模块的本地历史不完整,和远程仓库的历史无法关联,触发"refusing to merge unrelated histories"错误。而本地环境通常是完整克隆仓库,所以不会出现这个问题。
解决方案
1. 启用完整克隆,获取完整历史
修改actions/checkout步骤,添加fetch-depth: 0参数,确保拉取仓库及子模块的完整历史:
- name: Setup github uses: actions/checkout@v4 with: token: ${{ secrets.GH_CI_TOK }} submodules: 'recursive' ref: 'main' fetch-depth: 0 # 关键:拉取完整仓库及子模块历史
2. 确保子模块分支配置正确
检查父仓库根目录的.gitmodules文件,确认子模块已配置跟踪的远程分支(比如main):
[submodule "DataSubMod"] path = DataSubMod url = https://github.com/myrepos/DataSubMod.git branch = main # 新增或确认这一行,指定子模块跟踪的分支
3. 优化子模块更新命令
去掉冗余的git pull --recurse-submodules步骤,直接使用标准的子模块更新命令:
- name: Update submodules to latest remote commit run: | git submodule update --remote --merge
如果有临时兼容需求,可以在git pull时强制允许合并无关历史(不推荐长期使用,建议优先解决历史不完整问题):
- name: Update submodules (临时兼容方案) run: | cd ./DataSubMod git pull https://github.com/myrepos/DataSubMod.git main --allow-unrelated-histories cd ..
修改后的完整Action代码
name: Handle_New_Data on: repository_dispatch: types: [new_data] jobs: build: runs-on: windows-latest env: GH_ACCESS_TOKEN: ${{secrets.GH_AT}} steps: - name: Setup github uses: actions/checkout@v4 with: token: ${{ secrets.GH_CI_TOK }} submodules: 'recursive' ref: 'main' fetch-depth: 0 # 拉取完整历史 - name: Setup for git private repos run: | git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ git branch -M main - name: Check submodule dir run: ls DataSubMod - name: Update submodules to latest remote version run: | git submodule update --remote --merge
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

