How to deal with long conditional expression in Github Actions Workflow

Viewed 3151

How to best deal with long conditional expressions in GitHub Actions Workflow?

I have a workflow that I want to run in 2 cases:

  1. when a pull request is closed
  2. when a comment containing a specific string is created on a pull request

This leads to a workflow definition with a long if expression:

on:
  pull_request:
    types: [ closed ]
  issue_comment:
    types: [ created ]
jobs:
  do:
    if: ${{ github.event_name == 'pull_request' || (github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, 'specific string')) }}
    steps:
      ...

A solution I see is to split the workflow in 2 definitions, but I'd like to avoid this due to DRY.

Ideas I searched for, but did not find working solutions for:

  • define the expression on multiple lines
  • split the if in multiple if expressions
1 Answers

It's easy to define the expression on multiple lines using yaml multiline strings (ref: https://yaml-multiline.info/). For example:

if: >  # Either `>`, `>-`, `|`, `|-` will be OK
  github.event_name == 'pull_request' ||
  (
    github.event_name == 'issue_comment' &&
    github.event.issue.pull_request &&
    contains(github.event.comment.body, 'specific string')
  )

To use expression syntax (${{ }}), the final new line should be trimmed. Because expression should end with }}, no trailing white space.

if: >-  # Use `>-` or `|-`
  ${{
    github.event_name == 'pull_request' ||
    (
      github.event_name == 'issue_comment' &&
      github.event.issue.pull_request &&
      contains(github.event.comment.body, 'specific string')
    )
  }}

See https://github.com/AllanChain/test-action-if/blob/main/.github/workflows/test-if.yml for the demo.

Related