Github 操作:将评论发布到触发当前工作流的 PR 工作流

时间:2021-06-28 10:18:19

标签: github continuous-integration github-actions pull-request

我有两个工作流,第一个运行构建脚本并生成工件。 第一个在创建拉取请求时触发,如下所示:

name: build
on:
  pull_request:
    types: [opened, edited, ready_for_review, reopened]

第二个流程在第一个流程完成后运行,使用 workflow_run 触发器,如下所示:

on: 
  workflow_run:
    workflows: ["build"]
    types:
      - "completed"

第二个流程必须分开并在第一个流程之后运行。完成后,它应该对触发第一个工作流程的 PR 发表评论,但我不知道如何。

根据 Github Action Docs,这是典型的用例之一,根据此 qoute:

 For example, if your pull_request workflow generates build artifacts, you can create 
 a new workflow that uses workflow_run to analyze the results and add a comment to the
 original pull request.

但我似乎无法找到方法。我可以在第二个工作流的 context.payload.workflow_run.id 中获取第一个工作流的 id,但 workflow_run 也应该有关于拉取请求的信息,但它们是空的。

我做错了什么,我在哪里可以找到必要的信息来评论我创建的拉取请求?

1 个答案:

答案 0 :(得分:0)

您没有做错任何事情,只是第一个工作流的拉取请求数据没有出现在第二个工作流的 Github Context 中。

要解决您的问题,您可以将您需要的拉取请求数据从第一个工作流发送到第二个工作流。

有不同的方法可以做到这一点,例如使用 dispatch event(而不是工作流运行)或工件。

对于工件,它看起来像下面这样:

FIRST 工作流程中,您从 github.event 获取 PR 编号。然后将该数字保存到一个文件中并将其作为工件上传。

      - name: Save the PR number in an artifact
        shell: bash
        env:
          PULL_REQUEST_NUMBER: ${{ github.event.number }}
        run: echo $PULL_REQUEST_NUMBER > pull_request_number.txt

      - name: Upload the PULL REQUEST number
        uses: actions/upload-artifact@v2
        with:
          name: pull_request_number
          path: ./pull_request_number.txt

SECOND 工作流程中,您使用以下 GitHub 应用程序从 FIRST 工作流程中获取工件和 Pull Request number

      - name: Download workflow artifact
        uses: dawidd6/action-download-artifact@v2.11.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          workflow: <first_workflow_name>.yml
          run_id: ${{ github.event.workflow_run.id }}

      - name: Read the pull_request_number.txt file
        id: pull_request_number_reader
        uses: juliangruber/read-file-action@v1.0.0
        with:
          path: ./pull_request_number/pull_request_number.txt

      - name: Step to add comment on PR
        [...]