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

GitHub Actions:合并到main分支后如何按源分支前缀触发对应发布?

解决方案

要实现合并到main分支后根据PR源分支前缀触发对应发布的需求,核心是在push触发的工作流中获取合并提交关联的PR源分支信息。因为push事件本身不提供github.head_ref,我们可以通过GitHub API查询当前提交对应的PR来获取源分支。

配置示例

修改后的完整工作流配置如下:

name: Release

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4
      # 这里添加你的Swift Package构建、测试步骤
      # 例如:
      # - name: Build
      #   run: swift build
      # - name: Test
      #   run: swift test

  get-pr-info:
    needs: build
    runs-on: ubuntu-latest
    outputs:
      source_branch: ${{ steps.get-branch.outputs.source_branch }}
    steps:
      - id: get-branch
        uses: actions/github-script@v7
        with:
          script: |
            const commitSha = context.sha;
            // 查询合并到main的已关闭PR,找到关联当前提交的PR
            const pulls = await github.rest.pulls.list({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'closed',
              base: 'main',
              sort: 'updated',
              direction: 'desc'
            });
            const targetPR = pulls.data.find(pr => pr.merge_commit_sha === commitSha);
            if (targetPR) {
              console.log(`关联PR #${targetPR.number},源分支:${targetPR.head.ref}`);
              return targetPR.head.ref;
            } else {
              console.log("未找到关联PR(直接推送至main的提交)");
              return '';
            }

  patch-release-on-push:
    needs: get-pr-info
    if: contains(needs.get-pr-info.outputs.source_branch, 'patch')
    runs-on: ubuntu-latest
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - id: release
        uses: rymndhng/release-on-push-action@master
        with:
          bump_version_scheme: patch

关键逻辑说明

  1. 新增get-pr-info任务:

    • 依赖build任务,确保构建通过后再查询PR信息。
    • 使用actions/github-script调用GitHub API,查询合并到main的已关闭PR,通过merge_commit_sha匹配当前推送的提交,找到对应的PR。
    • 提取PR的源分支名作为输出变量source_branch,供后续任务判断。
  2. 修改发布任务触发条件:

    • patch-release-on-push任务现在依赖get-pr-info的输出,通过contains(needs.get-pr-info.outputs.source_branch, 'patch')判断源分支是否包含patch前缀,只有符合条件才会执行发布。

注意事项

  • 仅对通过PR合并到main的提交生效,如果是直接推送至main的提交,因无关联PR,不会触发发布流程,符合常规的发布规范。
  • 默认的GITHUB_TOKEN已具备读取PR信息的权限,无需额外配置权限。
  • 若需支持其他前缀(如minor/、major/),只需复制patch-release-on-push任务,修改条件和bump_version_scheme参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:35:39