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
关键说明
- 拉取base分支:通过
actions/checkout指定ref为PR的base分支,确保基础代码完整。 - 拉取Fork分支:添加Fork仓库为远程源并拉取head分支,使Fork的提交SHA可被本地git识别。
- 标签添加逻辑:使用
gh命令行工具(GitHub Actions环境默认预装)修改PR标签,默认的GITHUB_TOKEN拥有足够权限完成此操作。
内容的提问来源于stack exchange,提问作者adrinospy
相关产品推荐
相关产品推荐

