How to best deal with long conditional expressions in GitHub Actions Workflow?
I have a workflow that I want to run in 2 cases:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With