如何在目标分支合并其他PR时触发PR中的GitHub Workflow?
解决main分支更新后自动重新运行PR测试的问题
问题根源
你之前的配置无效的原因:
- PR分支里的Workflow只会响应该PR自身的事件(比如代码同步),main分支的push事件不会触发PR分支中的Workflow执行。
- 把Workflow放在main分支用push触发时,默认是在main分支的上下文运行,无法自动切换到各个打开PR与main合并后的状态。
可行解决方案
方案一:通过API触发PR合并状态的测试
在main分支新建一个监听main推送的Workflow,当main有代码推送时,自动调用GitHub API遍历所有打开的、目标为main的PR,触发它们的测试Workflow以合并状态运行。
- 首先修改你的测试Workflow,添加
repository_dispatch触发条件:
name: PR Tests on: pull_request: types: [opened, reopened, synchronize] repository_dispatch: # 允许通过API触发
- 在main分支创建触发用的Workflow(命名比如
trigger-pr-tests.yml):
name: Trigger PR Tests on Main Update on: push: branches: [main] jobs: trigger-tests: runs-on: ubuntu-latest steps: - name: 获取所有打开的目标为main的PR id: fetch-prs uses: octokit/request-action@v2.x with: route: GET /repos/${{ github.repository }}/pulls state: open base: main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: 逐个触发PR的测试运行 run: | # 解析返回的PR列表,提取PR编号 PR_NUMBERS=$(echo '${{ steps.fetch-prs.outputs.data }}' | jq -r '.[].number') # 遍历每个PR,触发测试Workflow for PR in $PR_NUMBERS; do echo "触发PR #$PR的测试运行" curl -X POST \ -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -H "Accept: application/vnd.github.v3+json" \ https://api.github.com/repos/${{ github.repository }}/actions/workflows/pr-tests.yml/dispatches \ -d '{"ref":"refs/pull/'$PR'/merge"}' done env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
注意:把上面的pr-tests.yml替换成你实际的测试Workflow文件名。
这个方案的核心是利用refs/pull/PR编号/merge这个特殊引用,它代表PR代码与base分支(main)合并后的状态,触发测试时会自动在这个合并状态下执行。
方案二:使用pull_request_target实现合并状态测试
如果不想调用API,可以把测试Workflow放在main分支,用pull_request_target触发,手动合并main分支到PR代码:
name: PR Tests on: pull_request: types: [opened, reopened, synchronize] push: branches: [main] pull_request_target: types: [opened, reopened, synchronize] jobs: run-tests: runs-on: ubuntu-latest steps: - name: 拉取PR代码 uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - name: 合并main分支到PR代码 run: | git remote add upstream https://github.com/${{ github.repository }}.git git fetch upstream main git merge upstream/main --no-edit - name: 执行测试 run: | # 替换成你的测试命令,比如 npm test、pytest等 echo "Running tests..."
如果要配合main推送触发所有PR测试,需要额外扩展逻辑遍历PR,实现起来比方案一繁琐,更推荐方案一。
注意事项
- 方案一中的
GITHUB_TOKEN默认拥有仓库的基本权限,私有仓库如果权限不足,需要生成带有repo权限的个人访问令牌(PAT)并替换。 - 确保测试Workflow的所有依赖(比如环境变量、缓存配置)在
repository_dispatch触发时能正常生效。
内容的提问来源于stack exchange,提问作者Collin Grady
相关产品推荐
相关产品推荐

