GitHub Actions で commit から PR 番号を取得する

2024-09-23

octkit.js の機能で、commit から PR が取得できる

pull request number を GitHub Actions 内で取得できないか探していたら、以下にスクリプトの例があった。

https://github.com/actions/checkout/issues/58#issuecomment-1426758830

steps:
  - name: checkout
    uses: actions/checkout@v4

  # permissions.pull_requests や permissions.contents の追加が必要だったはず
  - name: get pull-request number
    uses: actions/github-script@v7
    id: get_pr_number
    env:
      GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    with:
      script: |
        if ( context.issue.number ) {
          return context.issue.number;
        } else {
          return (
            await github.rest.repos.listPullRequestsAssociatedWithCommit({
              commit_sha: context.sha,
              owner: context.repo.owner,
              repo: context.repo.repo,
            })
          ).data[0].number
        }        
      result-encoding: string

github-script の githubA pre-authenticated octokit/rest.js client with pagination plugins なので octokit と同義。 なので、 octokit.rest... でなく、github.rest... となっている。

API の仕様は以下を参照。返ってくる Object の説明がない? https://octokit.github.io/rest.js/v18/#repos-list-pull-requests-associated-with-commit

id を指定しているので次以降の step で、steps.get_pr_number.outputs.result から取得できる。 result で値が取得できるのは、actions/github-script - Reading step results に記述があった。

参考