Github Action : 如果 PR 已存在则停止操作

问题描述 投票:0回答:2

我正在通过 GitHub 操作创建自动 PR,因此每当

dev
分支上发生新推送时。自动创建一个从
dev
master

的 PR

我想更改:如果 PR 已经存在 (

master
<-
dev
),则无需运行此操作,那么如何检查 PR 是否已存在?

Github 行动

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

jobs:
    create-pull-request:
        runs-on: ubuntu-latest
        steps:
            - name: Create Pull Request
              uses: actions/github-script@v6
              with:
                  script: |
                      const { repo, owner } = context.repo;
                      const result = await github.rest.pulls.create({
                        title: 'Master Sync : Auto Generated PR',
                        owner,
                        repo,
                        head: '${{ github.ref_name }}',
                        base: 'master',
                        body: [
                          'This PR is auto-generated by',
                          '[actions/github-script](https://github.com/actions/github-script).'
                        ].join('\n')
                      });
                      github.rest.issues.addLabels({
                        owner,
                        repo,
                        issue_number: result.data.number,
                        labels: ['feature', 'automated pr']
                      });
github github-actions github-api
2个回答
3
投票

没有条件可以直接在作业本身的

if
步骤中使用,但您可以使用 GitHub CLI 查看是否已经存在这样的 PR,然后提前退出:

steps:
  - name: Check if PR exists
    id: check
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    run: |
      prs=$(gh pr list \
          --repo "$GITHUB_REPOSITORY" \
          --json baseRefName,headRefName \
          --jq '
              map(select(.baseRefName == "master" and .headRefName == "dev"))
              | length
          ')
      if ((prs > 0)); then
          echo "skip=true" >> "$GITHUB_OUTPUT"
      fi

  - name: Create pull request
    if: '!steps.check.outputs.skip'
  # ...

0
投票

我成功地使用了它的大部分内容,但是|长管不起作用。我对 bash 不太熟悉,但是

prs
数组中始终有 1 个元素,无论是否有 PR。但当没有 PR 时,数组中第一个元素的长度为 0。这就是我最终的结果:

  name: Check if PR already exists
    id: check-pr-exists
    env:
      GH_TOKEN: ${{ github.token }}
    run: |
      prs=$(gh pr list -B targetBranch -H sourceBranch)  
      # Even when there are no PRs, this array always seems to have 1 result
      echo Size of PRS ARRAY: ${#prs[@]}
      # Locally, it seems the gh cli says 'no pull requests match your search..' but not here.
      # The first element exists but is of length 0
      echo Length of PRS[0] string: ${#prs[0]}
      
      if ((${#prs[@]} > 0 && ${#prs[0]} != 0 )); then
        echo skipping PR creation
        echo "skip=true" >> "$GITHUB_OUTPUT"
      fi
  - name: Create PR
    if: '!steps.check-pr-exists.outputs.skip'
    run: |
      gh pr create -B targetBranch -H source Branch .....
© www.soinside.com 2019 - 2024. All rights reserved.