Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get branch name on GitHub action?

During a GitHub action, I'd like to know the name of the branch:

  • for a push action: name of the current branch
  • for a pull_request action: name of the target branch

I need a string like develop, master or feature/xxx (and not refs/pull/…).

The ${{ github.ref }} var gives me refs/heads/develop. How can I get only the develop?

like image 423
Sylvain Avatar asked Feb 19 '20 12:02

Sylvain


People also ask

What is GitHub Head_ref?

github.head_ref. string. The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target . github.job.

How do I find the branch name in terminal?

In order to add branch name to bash prompt we have to edit the PS1 variable(set value of PS1 in ~/. bash_profile). This git_branch function will find the branch name we are on. Once we are done with this changes we can nevigate to the git repo on the terminal and will be able to see the branch name.


2 Answers

Update: GitHub added the context variable ${{ github.ref_name }}, returning "The branch or tag name that triggered the workflow run."

Original Answer:

You can create a step output of the last part of GITHUB_REF like the following.

on: push
jobs:
  example:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Set output
        id: vars
        run: echo ::set-output name=short_ref::${GITHUB_REF#refs/*/}

      - name: Check output
        run: echo ${{ steps.vars.outputs.short_ref }}
like image 180
peterevans Avatar answered Oct 22 '22 14:10

peterevans


This creates an environment variable GIT_BRANCH which has the following behavior:

  • Outside of a PR, this is set to the branch short name (master, not refs/heads/master)
  • Inside a PR, this is set to the target branch short name (master, not refs/pull/123/merge)
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Set environment variables
        run: |
          # Short name for current branch. For PRs, use target branch (base ref)
          GIT_BRANCH=${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}}
          echo "GIT_BRANCH=$GIT_BRANCH" >> $GITHUB_ENV

How this works:

  • GITHUB_BASE_REF is the short branch name for the target branch during a PR trigger, and it is empty otherwise.
  • GITHUB_REF always has a value, but the value changes based on the context. Outside of a PR, GITHUB_REF is the "full" branch name (refs/heads/master). Inside of a PR, it is the PR branch name (refs/pull/123/merge).

So this script uses GITHUB_BASE_REF if set, otherwise it uses GITHUB_REF and removes the "refs/heads/" prefix.

like image 9
Michael R Avatar answered Oct 22 '22 14:10

Michael R