Search code examples
githubgithub-actions

Specify source branch in addition to target branch in PR workflow trigger?


I'd like to be able to specify a specific source-target combination to trigger a GitHub Actions workflow, rather than just a target branch. How might I do this?

Here's the idea (this doesn't actually work):

  pull_request:
    branches: 
      target_branch: "main"
      source_branch: "dev"
      

My use case for this is a pre-prod check that runs on PRs into main. I want the pattern to be that folks need to get their changes into the semi-protected dev branch first, rather than opening the PR into main from their own unvetted feature branches. Then, only dev sourced PRs are allowed to trigger the pre-prod check.

I know I could get similar functionality by combining a PR trigger with an Environment Protection rule, but I'm not actually trying to limit deployments from certain branches broadly (I have a dev process that some users should be able to trigger at will) but rather be able to granularly specify which source-target combinations trigger specific workflows when PRs are opened/updated.


Solution

  • I found my own answer in the docs: Running your pull_request workflow based on the head or base branch of a pull request

    You can set jobs to only run if the source/HEAD branch matches a certain name pattern. When coupled with the on pull_request branch trigger:

    on:
      pull_request:
        branches: ["main"] # the target branch
    
    jobs:
      job_that_only_runs_when_head_ref_is_dev:
        if: ${{ github.head_ref == 'dev' }}
        runs-on: ubuntu-latest
        steps:
          - run: echo "This job run came from branch 'dev'!"