43

I want to access the Pull Request number in a Github Actions workflow. I can access the GITHUB_REF environment variable that is available. Although on a Pull Request action it has the value: refs/pull/125/merge. I need to extract just the 125.

I have found a similar post here that shows how to get the current branch using this variable. Although in this case, what I am parsing is different and I have been unable to isolate the Pull Request number.

  • I have tried using {GITHUB_REF##\*/} which resolves to merge
  • I have also tried {GITHUB_REF#\*/} which resolves to pull/125/merge

I only need the Pull Request number (which in my example is 125)

zessx
  • 68,042
  • 28
  • 135
  • 158
Colby Hill
  • 811
  • 1
  • 8
  • 13
  • 1
    If the event is a `pull_request`, you should be able to use `${{ github.event.pull_request.number }}`. See all of the attributes here: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request – Joshua Pinter May 03 '22 at 21:23

8 Answers8

83

Although it is already answered, the easiest way I found is using the github context. The following example shows how to set it to an environment variable.

env:
  PR_NUMBER: ${{ github.event.number }}
David Perfors
  • 1,273
  • 13
  • 15
  • 1
    This solution is good because the one above gives deprecation warnings form github actions, also this is a short 2 liner as well – george_h Nov 17 '20 at 09:52
  • 3
    But I GUESS this only works when the action is filtered on only pull requests, for example if the action is triggered by an issue, the event.number will be the issue's one. – Obay Abd-Algader Jan 28 '21 at 13:54
  • 2
    @ObayAbd-Algader, actually, it looks like to be just for PRs, issues will be inside github.event.issue.number. I didn't find any documentation of this behaviour (yet) – David Perfors Feb 01 '21 at 12:47
10

An alternative if you are trying to figure out which PR a commit is linked to on a push instead of a pull_request event is to use the gh CLI which is included in the standard GitHub Action images.

For example:

      - 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 }}

Be sure to add pull_request: read permissions on the job as well.

Then in following steps, you can access it with the variable,

${{ steps.pr.outputs.pull_request_number }}
Pete
  • 2,503
  • 4
  • 21
  • 20
  • I tried your implementation, but the `gh cli` didn't recognised the repo without adding the `actions/checkout` to the job steps. Once I added it, it worked as expected ! Thanks for sharing. I quoted your answer [here](https://stackoverflow.com/questions/70101736/grabbing-pr-number-from-a-push-event) – GuiFalourd Nov 24 '21 at 20:51
9

While the answer by @Samira worked correctly. I found out that there is a new way to do this and wanted to share it with anyone who might stumble upon this.

The solution is to add a stage at the beginning of your workflow which gets the PR number from the Github Token (event) and then set it as an environment variable for easy use throughout the rest of the workflow. Here is the code:

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

Now in any later stage, you can simply use $PULL_NUMBER to access the environment variable set before.

Colby Hill
  • 811
  • 1
  • 8
  • 13
6

How about using awk to extract parts of GITHUB_REF instead of bash magick?

From awk manpage:

-F fs

--field-separator fs

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

As long you remember this, it's trivial to extract only part of variable you need. awk is available on all platforms, so step below will work everywhere:

- run:   echo ::set-env name=PULL_NUMBER::$(echo "$GITHUB_REF" | awk -F / '{print $3}')
  shell: bash
Samira
  • 7,795
  • 3
  • 25
  • 25
3

Here's a working snippet to get the issue number in both push and pull_request events within a GitHub Actions workflow by leveraging actions/github-script:

steps:
  - uses: actions/github-script@v6
    id: get_issue_number
    with:
      script: |
        if (context.issue.number) {
          // Return issue number if present
          return context.issue.number;
        } else {
          // Otherwise return issue number from commit
          return (
            await github.rest.repos.listPullRequestsAssociatedWithCommit({
              commit_sha: context.sha,
              owner: context.repo.owner,
              repo: context.repo.repo,
            })
          ).data[0].number;
        }
      result-encoding: string
  - name: Issue number
    run: echo '${{steps.get_issue_number.outputs.result}}'

The script queries the list labels for an issue REST API endpoint via octokit/rest.js client.

Rishav
  • 55
  • 1
  • 11
1

In my case my job is trigged by

  pull_request_review:
    types: [submitted]

so using github.event.number doesn't give me the PR number.

The other solutions here are all using the deprecated set-env method which require you to "allow unsecure commands"

I was able to successfully put the PR into my env variables using a more modern method w/ awk (I took that part from Samarai's answer):

      - name: Get Pull Request Number
        run: echo "PULL_NUMBER=$(echo "$GITHUB_REF" | awk -F / '{print $3}')" >> $GITHUB_ENV
        shell: bash

Then using it in other steps is simply: ${{ env.PULL_NUMBER }}

RyanG
  • 4,393
  • 2
  • 39
  • 64
0

Just gonna drop what worked out for me

      - 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 }}
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
0

For actions that need to run on PRs and on comments on PRs, I ended up extracting it with:

export PR_NUMBER="${{ github.event.pull_request.number || github.event.issue.number }}"

This is because github.event.pull_request.number is only defined for events triggered by a PR opening/closing, while github.event.issue.number is only defined for comments on PRs (the former needs a on: pull_request, the latter needs a on: issue_comment): this method allowed me to recycle the same action across different workflows.

Alberto Chiusole
  • 2,204
  • 2
  • 16
  • 26