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

如何配置GitHub Actions,在merge_to_main.yml成功后触发main分支工作流?

实现GitHub Actions分支自动合并与后续工作流触发

1. 配置 merge_to_main.yml

这个工作流负责在代码推送到development分支时,先执行测试,通过后自动合并到main分支:

name: Merge Development to Main
on:
  push:
    branches: [ development ]

permissions:
  contents: write
  pull-requests: write

jobs:
  test-and-merge:
    runs-on: ubuntu-latest
    steps:
      - name: 拉取代码
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # 拉取完整提交历史,确保合并操作正常执行

      - name: 在development分支运行测试
        run: |
          # 替换为你的项目实际测试命令(如npm test、pytest、mvn test等)
          echo "执行测试..."
          # npm test

      - name: 合并development到main分支
        uses: actions/github-script@v7
        with:
          script: |
            const { repo, owner } = context.repo;
            try {
              await github.rest.repos.merge({
                owner: owner,
                repo: repo,
                base: 'main',
                head: 'development'
              });
              console.log('development分支已成功合并到main');
            } catch (error) {
              console.error('合并失败:', error.message);
              throw error;
            }

2. 配置 run_on_main.yml

这个工作流会在merge_to_main.yml执行成功后,自动在main分支运行指定任务:

name: Run on Main Branch
on:
  workflow_run:
    workflows: [ "Merge Development to Main" ] # 必须与merge_to_main.yml的name完全一致
    branches: [ development ]
    types:
      - completed

jobs:
  execute-main-tasks:
    runs-on: ubuntu-latest
    # 仅当上游工作流成功完成时才触发
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - name: 拉取main分支代码
        uses: actions/checkout@v4
        with:
          ref: main

      - name: 在main分支执行任务
        run: |
          # 替换为你需要在main分支执行的命令(如构建、部署、打包等)
          echo "在main分支执行任务..."
          # npm run build && npm run deploy

关键注意事项

  • 权限配置:merge_to_main.yml中的permissions必须设置contents: write和pull-requests: write,否则工作流没有权限执行合并操作。
  • 分支保护规则:如果main分支开启了分支保护(如需要PR审核、状态检查通过),直接合并会失败。此时可以调整分支保护规则,允许GitHub Actions进行合并,或者修改合并步骤为创建并自动合并PR的逻辑。
  • 测试命令替换:务必将测试步骤中的占位命令替换为项目实际的测试命令,否则会跳过真实测试直接执行合并。
  • 工作流名称匹配:run_on_main.yml中workflows字段的内容必须和merge_to_main.yml的name完全一致,否则无法触发后续工作流。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:35:19