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']
});
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" \
--head 'dev' \
--base 'master' \
--json title \
--jq 'length')
if ((prs > 0)); then
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- name: Create pull request
if: '!steps.check.outputs.skip'
# ...
I used this successfully for the bulk of it, but the | length pipe did not work. I'm not as familiar with bash, but the prs array always had 1 element in it regardless of if there was or wasn't a PR. But the first element in the array was of length 0 when there were no PRs. This is what I ended up with:
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 .....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With