Woldie
Woldie

Reputation: 3

Can I prevent a GitHub Pull Request from being created when the selected target branch fails a GitHub Actions workflow?

I have a branch name validity check GitHub Actions workflow that is intended to prevent PR's from merging when the target branch is incompatible with the source branch name.

For example, if my target branch is main, then only release\* branches are allowed to merge. Similarly, if my target branch is develop, then only feature\* or bug\* branches are allowed to merge.

An interesting effect of having this GitHub Action is, when I am creating a PR with the GitHub UX, it seems to be running the workflow and giving me visual feedback that, with the settings as-is, my branch could not be automatically merged (but it would still allow the branch to be created.)

Create PR UX showing an incompatible branch target

My question is: based on my workflow results, can I also dynamically enable/disable the Create Pull Request button whenever the target branch dropdown changes?

GitHub allows me to create a PR when the source branch name and target branches are incompatible, based on rules in my GitHub Actions workflow that is set to trigger on:

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - edited
      - ready_for_review
      - auto_merge_enabled
      - synchronize

I would like to include some setting that prevents creation of the Pull Request when this GitHub Action workflow exits with an error.

Upvotes: 0

Views: 122

Answers (1)

Delta George
Delta George

Reputation: 4236

GitHub Actions does not allow us to control pull request creation based on a custom check. However, it does allow us to present PR merge based on branch protection rules.

Create a workflow that validates source branch against the base branch:

name: PR Check

on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  check:
    runs-on: ubuntu-latest

steps:
- name: Checkout repository
  uses: actions/checkout@v2

- name: Set environment variables
  run: |
    echo "BASE_BRANCH=${{ github.event.pull_request.base.ref }}" >> $GITHUB_ENV
    echo "HEAD_BRANCH=${{ github.event.pull_request.head.ref }}" >> $GITHUB_ENV

- name: Use branches in a script
  run: |
    echo "Running checks for base branch: $BASE_BRANCH and head branch: $HEAD_BRANCH"

Create branch protection rule for main and develop branches and use the above workflow as a required check.

Upvotes: 0

Related Questions