How to get PR branch name in GitHub Actions

https://help.github.com/en/articles/virtual-environments-for-github-actions#default-environment-variables
The GITHUB_REF var is currently returning value like “refs/pull/421/merge” which contains no mention of any branch name from which the PR was created. How can I achieve the same?

1 Like

The pull request event contains the information you’re looking for. If you’re in a javascript action, context.payload.pull_request.head.ref will give you the branch name. (where context comes from const {context} = require(’@actions/github’)).

If you’re in yaml, then I believe it would be github.payload.pull_request.head.ref (see https://help.github.com/en/articles/contexts-and-expression-syntax-for-github-actions#github-context).

3 Likes

@jaredly Here’s my problem, I am trying to use bundlesize package for my repo using github actions. The package uses another package called ci-env which reads branch name from process.env.GITHUB_REF here, which is wrong. So I just wanted to replace this env var value with the context value you suggested. But I see here that the GITHUB_ env vars can’t be overridden. What should be done now?

You’ll need to fork ci-env to allow the branch name to be overridden (using a different env vbl), I should think

That should be my final recourse. Is there no simpler solution according to you? Otherwise I will just raise a PR in ci-unv to fix the variable read.

I have raised a PR to fix this
https://github.com/siddharthkp/ci-env/pull/29/files

process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF && process.env.GITHUB_REF.split(’/’)[2]

should suffice, right?

Thanks for your post. It led me down the right path that will save me loads of time in the future.

Regarding:

If you’re in yaml, then I believe it would be github.payload.pull_request.head.ref 

That didn’t work, but this produced the branch to be merged as expected:

github.event.pull_request.head.ref
2 Likes

One way get the pull request’s base branch is:

- name: Step that prints name of pull request's base branch
  run: |
    echo "Pull request's base branch is: ${BASE_BRANCH}"
  env:
    BASE_BRANCH: ${{ github.base_ref }}
  if: github.event_name == 'pull_request'

For more details, see the documentation on the github context.

3 Likes

if: github.ref == ‘refs/heads/integration’ && github.event_name == ‘push’ 

You can this command and replace whatever branch or event you want to run for.

I would like to know how can I get the title of a pull request too!