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

如何配置GitHub Actions工作流,PR获批前触发即失败且无冗余任务?

优化GitHub Actions工作流(Review_submitted_check)

问题根源

当前配置同时监听pull_request和pull_request_review事件,但未区分事件类型:

  • 当PR有活动(如新推送)触发pull_request事件时,github.event.review字段不存在,导致verify fail步骤执行exit 1,任务失败
  • 当审核提交触发pull_request_review事件时,若审核未通过也会失败,但PR活动触发的任务会额外产生一次无意义的失败记录,不符合预期

优化方案

通过区分事件类型处理不同场景:

  1. 针对PR活动事件(如新推送、PR创建):直接返回失败,强制等待审核
  2. 针对审核提交事件:仅当审核状态为approved时返回成功,否则失败

完整优化配置

name: Review_submitted_check

on:
  pull_request:
    # 指定PR活动的触发类型:创建、推送更新、重新打开
    types: [opened, synchronize, reopened]
    branches:
      - test_pr
  pull_request_review:
    types: [submitted]
    branches: test_pr

jobs:   
  approval:
    runs-on: ros-runner
    steps:
      # 处理PR活动事件:直接失败,提示需等待审核
      - name: Fail for PR activity (needs review)
        if: github.event_name == 'pull_request'
        run: |
          echo "PR has new activity, waiting for approval"
          exit 1

      # 处理审核提交事件:判断是否批准
      - name: Check approval status
        if: github.event_name == 'pull_request_review'
        run: |
          if [ "${{ github.event.review.state }}" = "approved" ]; then
            echo "PR approved, proceeding"
            exit 0
          else
            echo "PR not approved, failing check"
            exit 1
          fi

关键修改说明

  • 明确pull_request的触发类型:只监听opened(PR创建)、synchronize(分支推送更新)、reopened(PR重新打开),避免不必要的触发
  • 通过github.event_name区分事件类型,分别执行对应逻辑:
    • PR活动时直接失败,清晰提示原因
    • 审核提交时统一用shell脚本判断状态,避免多个步骤的条件判断混乱
  • 确保每次触发的任务只有一个逻辑分支执行,不会出现无意义的失败记录

额外适配建议

如果需要支持PR已有有效审核时,推送新代码后无需重新审核的场景,可以调用GitHub API查询PR的最新有效审核状态,但需给工作流配置pull-requests: read权限:

jobs:   
  approval:
    runs-on: ros-runner
    permissions:
      pull-requests: read
    steps:
      - name: Check PR approval status for activity events
        if: github.event_name == 'pull_request'
        run: |
          # 查询PR的最新审核状态
          APPROVAL_STATUS=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "${{ github.event.pull_request.url }}/reviews" | \
            jq -r '.[].state | select(. == "approved") | last')
          
          if [ "$APPROVAL_STATUS" = "approved" ]; then
            echo "PR has valid approval, proceeding"
            exit 0
          else
            echo "PR needs approval"
            exit 1
          fi

      - name: Check approval status for review events
        if: github.event_name == 'pull_request_review'
        run: |
          if [ "${{ github.event.review.state }}" = "approved" ]; then
            echo "PR approved, proceeding"
            exit 0
          else
            echo "PR not approved, failing check"
            exit 1
          fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:36:00