如何处理 Github Actions Workflow 中的长条件表达式

Kor*_*out 11 github-actions

如何最好地处理 GitHub Actions Workflow 中的长条件表达式?

我有一个工作流程,我想在两种情况下运行:

  1. 当拉取请求关闭时
  2. 当在拉取请求上创建包含特定字符串的评论时

这导致工作流定义具有长if表达式:

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:
      ...
Run Code Online (Sandbox Code Playgroud)

我看到的一个解决方案是将工作流程分成 2 个定义,但由于 DRY,我想避免这种情况。

我搜索了一些想法,但没有找到以下可行的解决方案:

  • 在多行上定义表达式
  • 将 if 拆分为多个 if 表达式

All*_*ain 32

使用 yaml 多行字符串可以轻松定义多行表达式(参考:https: //yaml-multiline.info/)。例如:

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')
  )

Run Code Online (Sandbox Code Playgroud)

要使用表达式语法 ( ${{ }}),应修剪最后的新行。因为表达式应该以 结尾}},没有尾随空格。

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')
    )
  }}
Run Code Online (Sandbox Code Playgroud)

有关演示,请参阅https://github.com/AllanChain/test-action-if/blob/main/.github/workflows/test-if.yml 。

  • @Korthout我编辑了答案以澄清表达式语法问题。 (2认同)