Home > Enterprise >  Github Action : Stop the action if PR already exists
Github Action : Stop the action if PR already exists

Time:09-27

I am creating auto PR via GitHub action, So whenever a new push happens on dev branch. automatically a PR is created from dev to master

I want to change: If already a PR exists ( master <- dev ) no need to run this action, so how can I check if already PR exists?

Github Action

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']
                      });

CodePudding user response:

There's no condition that you could use directly in an if step on the job itself, but you could use the GitHub CLI to see if there is such a PR already, and then exit early:

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 "::set-output name=skip::true"
      fi

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