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

如何在GitHub Action中避免重复创建dev到master的自动PR

如何避免GitHub Action重复创建dev到master的PR

你当前的GitHub Action会在dev分支推送时自动创建到master的PR,但现在需要添加检查逻辑:如果已经存在从dev到master的开放PR,就不再执行创建操作。

修改方案

核心是利用GitHub REST API的pulls.list接口,先查询仓库中是否存在符合条件的开放PR,再决定是否执行创建逻辑:

  • 调用接口查询状态为open、源分支是dev、目标分支是master的PR
  • 如果查询结果为空,才执行原有的PR创建和标签添加逻辑
  • 如果已有符合条件的PR,直接输出提示信息,跳过创建步骤

修改后的完整配置

name: Pull Request Action
on:
    push:
        branches: ['dev']

jobs:
    create-pull-request:
        runs-on: ubuntu-latest
        steps:
            - name: Create Pull Request (if none exists)
              uses: actions/github-script@v6
              with:
                  script: |
                      const { repo, owner } = context.repo;
                      // 查询是否存在从dev到master的开放PR
                      const existingPulls = await github.rest.pulls.list({
                        owner,
                        repo,
                        state: 'open',
                        head: `${owner}:${context.ref_name}`,
                        base: 'master'
                      });

                      // 如果没有找到符合条件的PR,才执行创建
                      if (existingPulls.data.length === 0) {
                        const result = await github.rest.pulls.create({
                          title: 'Master Sync : Auto Generated PR',
                          owner,
                          repo,
                          head: context.ref_name,
                          base: 'master',
                          body: [
                            'This PR is auto-generated by actions/github-script.'
                          ].join('\n')
                        });
                        // 给PR添加标签
                        await github.rest.issues.addLabels({
                          owner,
                          repo,
                          issue_number: result.data.number,
                          labels: ['feature', 'automated pr']
                        });
                        console.log(`自动创建PR #${result.data.number}成功`);
                      } else {
                        console.log(`已存在从${context.ref_name}到master的开放PR,跳过创建步骤`);
                      }

关键说明

  • state: 'open':只查询处于开放状态的PR,避免把已合并/关闭的PR算进去
  • head: ${owner}:${context.ref_name}``:完整指定源分支的格式(所有者:分支名),确保查询准确
  • 逻辑判断:通过existingPulls.data.length判断是否存在符合条件的PR,为空则执行创建

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:46:58