0

GitHub Actions support running workflows for pull requests targets specific branches but the names of the branches must be specified, thus if we want it to run on repositories with default branch named main:

  pull_request:
    branches:    
      - main

I'm wondering if there's a way to share the same workflow across multiple repositories without the need to asking each repositories to specify their default branch name, and the workflow can work upon renaming default branches. Is there a way to just run the workflow upon pull requests to default branch without specifying all the possible default branch names across these repositories as below?

I want to avoid:

  pull_request:
    branches:    
      - main
      - master
      - develop
      - dev
      - i-dont-know-what-else
      - ${{ remember-to-update-this-after-renaming-default-branch }}

I've tried listing all possible default branch names and use a variable but these are not elegant.

LongYC
  • 476
  • 3
  • 13
  • 1
    Does this answer your question? [GitHub actions: default branch variable](https://stackoverflow.com/questions/64781462/github-actions-default-branch-variable) – GuiFalourd Nov 07 '22 at 11:10
  • @GuiFalourd, that's an interesting find, but somehow it's not documented on https://docs.github.com/en/developers/webhooks-and-events/events/github-event-types, yet it can be found on https://docs.github.com/en/rest/repos/repos. Anyway I went ahead to try with `- ${{ github.event.repository.default_branch }}` but only ending up with an error: `Unrecognized named-value: 'github'. Located at position 1 within expression: github.event.repository.default_branch`. – LongYC Nov 07 '22 at 14:23
  • I don't think this solution works at the workflow level – GuiFalourd Nov 07 '22 at 15:44

1 Answers1

0

You can achieve this with the conditional github.ref == github.event.repository.default_branch.

Here's an example which only runs when a PR is merged into the default branch.

on:
  pull_request:
    types:
      - closed

jobs:
  example:
    if: github.event.pull_request.merged && github.ref == github.event.repository.default_branch
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

gardar
  • 75
  • 4