You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pull_request_target触发Workflow遇bad object错误,求Fork仓库PR分支对比方案

解决Fork PR的GitHub Workflow git diff SHA不存在错误

问题原因

使用pull_request_target事件时,Workflow运行在基础仓库的上下文,默认仅拉取基础仓库的代码。Fork仓库的head提交SHA并不存在于基础仓库中,因此git diff会抛出fatal: bad object错误。

解决方案

需要先拉取Fork仓库的head分支代码,确保head SHA存在本地仓库,再执行差异对比和标签添加逻辑。

修改后的Workflow配置

on:
  pull_request_target:
    types: [opened, synchronize] # 仅在PR打开或同步时触发

jobs:
  auto-label-pr:
    runs-on: ubuntu-latest
    steps:
      - name: 拉取基础仓库的base分支
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.base.ref }}

      - name: 添加Fork远程仓库并拉取head分支
        run: |
          # 添加Fork仓库作为远程源
          git remote add fork ${{ github.event.pull_request.head.repo.clone_url }}
          # 拉取Fork仓库的head分支所有提交
          git fetch fork ${{ github.event.pull_request.head.ref }}

      - name: 检查变更并添加标签
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          HEAD_SHA=${{ github.event.pull_request.head.sha }}
          BASE_SHA=${{ github.event.pull_request.base.sha }}

          # 列出所有变更文件
          git diff $BASE_SHA $HEAD_SHA --name-only

          # 根据变更路径添加对应标签
          # 示例:修改src目录文件添加code-change标签
          if git diff $BASE_SHA $HEAD_SHA --name-only | grep -q "^src/"; then
            gh pr edit ${{ github.event.pull_request.number }} --add-label "code-change"
          fi

          # 示例:修改docs目录文件添加documentation标签
          if git diff $BASE_SHA $HEAD_SHA --name-only | grep -q "^docs/"; then
            gh pr edit ${{ github.event.pull_request.number }} --add-label "documentation"
          fi

关键说明

  1. 拉取base分支:通过actions/checkout指定ref为PR的base分支,确保基础代码完整。
  2. 拉取Fork分支:添加Fork仓库为远程源并拉取head分支,使Fork的提交SHA可被本地git识别。
  3. 标签添加逻辑:使用gh命令行工具(GitHub Actions环境默认预装)修改PR标签,默认的GITHUB_TOKEN拥有足够权限完成此操作。

内容的提问来源于stack exchange,提问作者adrinospy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:30