如何在 GitHub Actions 工作流程中获取拉取请求编号

How to get pull request number within GitHub Actions workflow

我想在 Github Actions 工作流程中访问 Pull Request 编号。我可以访问可用的 GITHUB_REF 环境变量。尽管在 Pull Request 操作中它具有值:"refs/pull/125/merge"。我只需要提取“125”。

我发现了一个类似的 post 显示了如何使用此变量获取当前分支。尽管在这种情况下,我解析的内容不同,而且我一直无法隔离 Pull Request 编号。

我试过使用解析为 "merge" 的 {GITHUB_REF##*/} 我也试过 {GITHUB_REF#*/} 解析为 "pull/125/merge"

我只需要 Pull Request 编号(在我的例子中是 125)

如何使用 awk 来提取部分 GITHUB_REF 而不是 bash magick?

来自 awk 联机帮助页:

-F fs

--field-separator fs

Use fs for the input field separator (the value of the FS predefined variable).

只要你记住这一点,只提取你需要的部分变量是微不足道的。 awk 适用于所有平台,因此以下步骤适用于所有平台:

- run:   echo ::set-env name=PULL_NUMBER::$(echo "$GITHUB_REF" | awk -F / '{print }')
  shell: bash

虽然@Samira 的回答正确。我发现有一种新方法可以做到这一点,并想与可能偶然发现此方法的任何人分享。

解决方案是在工作流程的开头添加一个阶段,从 Github 令牌(事件)中获取 PR 编号,然后将其设置为环境变量,以便于在其余部分使用工作流程。这是代码:

  - name: Test
    uses: actions/github-script@0.3.0
    with:
      github-token: ${{github.token}}
      script: |
        const core = require('@actions/core')
        const prNumber = context.payload.number;
        core.exportVariable('PULL_NUMBER', prNumber);

现在在任何后续阶段,您只需使用 $PULL_NUMBER 即可访问之前设置的环境变量。

虽然已经回答了,但我发现最简单的方法是使用 github 上下文。以下示例显示如何将其设置为环境变量。

env:
  PR_NUMBER: ${{ github.event.number }}

如果您试图找出提交链接到 push 而不是 pull_request 事件的 PR,另一种方法是使用 gh CLI which is included in the standard GitHub Action images.

例如:

      - name: Get Pull Request Number
        id: pr
        run: echo "::set-output name=pull_request_number::$(gh pr view --json number -q .number || echo "")"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

请务必在作业中添加 pull_request: read permissions

然后在接下来的步骤中,您可以使用变量访问它,

${{ steps.pr.outputs.pull_request_number }}

只是放弃对我有用的东西

      - id: find-pull-request
        uses: jwalton/gh-find-current-pr@v1
        with:
          # Can be "open", "closed", or "all".  Defaults to "open".
          state: open
      - name: create TODO/FIXME comment body
        id: comment-body
        run: |
          yarn leasot '**/*.{js,ts,jsx,tsx}' --ignore 'node_modules/**/*' --exit-nicely --reporter markdown > TODO.md
          body="$(sed 1,2d TODO.md)"
          body="${body//'%'/'%25'}"
          body="${body//$'\n'/'%0A'}"
          body="${body//$'\r'/'%0D'}" 
          echo "::set-output name=body::$body"
      - name: post TODO/FIXME comment to PR
        uses: peter-evans/create-or-update-comment@v2
        with:
          issue-number: ${{ steps.find-pull-request.outputs.number }}
          body: ${{ steps.comment-body.outputs.body }}