Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with long conditional expression in Github Actions Workflow

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
like image 750
Korthout Avatar asked Dec 21 '25 13:12

Korthout


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.

like image 78
Allan Chain Avatar answered Dec 23 '25 06:12

Allan Chain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!