Search code examples
githubgithub-actionsslack

Run Github action when pull request origin branch has certain prefix


I am trying to create actions which behave differently depending on the prefix of the origin (head?) branch.

Current use case is sending a Slack message when a branch named bug/<anything> is getting merged into main.

I've tried setting a script up like the following.

report-bugfix.yml

name: Report Bugfix
on:
  push: 
    branches: 
      - main
jobs:
  run_if:
    if: startsWith(github.ref_name, 'bug/')
    runs-on: self-hosted
    steps:
      - uses: 8BitJonny/[email protected]
        id: PR
      - name: Slack Notify
        uses: rtCamp/[email protected]
        env:
          SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_CHANGELOG }}
          SLACK_USERNAME: BugBuster Bot
          SLACK_COLOR: ${{ job.status }}
          SLACK_TITLE: 'A new bug has been fixed! :beetle:'
          SLACK_MESSAGE: ${{ steps.PR.outputs.pr_body }}

My action currently gets skipped as the if statement returns false, so I assume my syntax or variable checking is wrong.

Any action sharks who are aware of a elegant solution to my use case?

Edit: Changed following line if: startsWith(github.ref_name, 'bug/**') with if: startsWith(github.ref_name, 'bug/')

However testing with the branchname bug/action-testing the issue still persists


Solution

  • So the issue was related to looking for the push event. The event doesn't seem to know about where a push came from, so it was essentially impossible to locate that information for me.

    Instead I can use the pull_request event, which sets the github.head_ref variable to the branch which I am creating the request from.

    To ensure the action only triggered when the pull request was closed and merged, I used the type closed and github.event.pull_request.merged == true in an if statement.

    My final script is as follows:

    name: Bug Changelog
    on:
      pull_request:
        types: 
          - closed
        branches:
          - 'main'
    
    jobs:
      if_merged:
        if: github.event.pull_request.merged == true && startsWith(github.head_ref, 'bug/')
        runs-on: self-hosted
        steps:
          - uses: 8BitJonny/[email protected]
            id: PR
          - name: Slack Notify
            uses: rtCamp/[email protected]
            env:
              SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_CHANGELOG }}
              SLACK_USERNAME: BugBuster Bot
              SLACK_COLOR: ${{ job.status }}
              SLACK_TITLE: 'A new bug has been fixed! :beetle:'
              SLACK_MESSAGE: ${{ steps.PR.outputs.pr_body }}
              SLACK_FOOTER: ''
              MSG_MINIMAL: true