Get original branch name in Github action push event to master

Viewed 3420

I'm trying to set up a Github action push event to master (so, a merge). The problem is that for what I want to do, I need the name of the original pull request branch. The Github pull request event makes this easy by calling ${{ github.head_ref }}, but this option doesn't exist on a push event. I originally thought ${{ github.head }} would give me what I want, but it actually just gives me refs/heads/master, not the name of the original PR branch.

In other words, say I opened a PR to the master branch with a branch named foo. In a push event, I want to be able to get foo for what I want to do in the job.

Is this possible?

3 Answers

I found an acceptable workaround solution for my use case using a pull request event instead of a push event:

on:
  pull_request:
    types: [closed]
    branches:
      - master

The above says to run only on pull requests to the master branch that have been closed, since merged PRs are closed automatically. But in order to have this action only run on closed PRs that have also been merged and not just any closed PR, in the relevant step(s) in the job, I add a conditional check to make sure the closed PR has also been merged:

if: github.event.pull_request.merged == true

And then I can access the branch name as I mentioned in the question: ${{ github.head_ref }}

For the first question, how to get source branch name on push action on master? Github action does not provide the way so far. I created an action to help to achieve it but require some prerequisite.

  • This action need to run on main or any (or any merging target branch)
  • The source branch need to be merge from Github Merge button and the auto message must not be change.
  • If the branch is not merged by Github Merge button, you need to specify branch name e.g xxx xxx/branch-name xxx in commit message

Then you can get source name. Example

name: "Log RECENT_MERGED_BRANCH_NAME"
on:
    push:
      branches:
        - "main"
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: tonynguyenit18/github-action-custom-vars@v1
      - run: echo $RECENT_MERGED_BRANCH_NAME

Check more details here: https://github.com/tonynguyenit18/github-action-custom-vars

If you just want to get the branch that triggered the pipeline then you can get it from env GITHUB_REF also able to accessed as ${{ github.ref }}. If you are triggering on a tag, then GITHUB_REF won't have the proper branch name so you will need follow process shown here How to get a branch name on GitHub action when push on a tag?

Related