How to get a branch name on GitHub action when push on a tag?

Viewed 6219

I trigger my workflow using

on:
  push:
    tags:

GITHUB_REF won't contain a branch name in this case, how could I get it?

3 Answers

You will need to do a bit of string manipulation to get this going. Basically during a tag creation push, is like if you were to do git checkout v<tag> in your local but there's no reference to the original branch. This is why you will need to use the -r flag in the git branch contains command.

We get the clean branch with the following two commands.

    raw=$(git branch -r --contains ${{ github.ref }})
    branch=${raw/origin\/}

Here is a pipeline that creates a branch env

 name: Tag
 on: 
   create:
     tags:
       - v*
 jobs:
   job1:
     runs-on: ubuntu-latest
     steps:
     - name: checkout source code
       uses: actions/checkout@v1
     - name: Get Branch
       run: |
         raw=$(git branch -r --contains ${{ github.ref }})
         branch=${raw/origin\/}
         echo ::set-env name=BRANCH::$branch
     - run: echo ${{ env.BRANCH }}

Working Example

NOTE: I triggered the above pipeline by creating a tag and pushing it to origin

Building on Edward's answer, here is a modern script which allows getting branch name and passing it between jobs, including allowing jobs to be conditionally run based on branch

# This only runs for tags, and the job only processes for "master" branch
name: Example

on:
  push:
    tags:
      - "*"

jobs:
  check:
    runs-on: ubuntu-latest
    outputs:
      branch: ${{ steps.check_step.outputs.branch }}
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Get current branch
        id: check_step
        run: |
          raw=$(git branch -r --contains ${{ github.ref }})
          branch=${raw##*/}
          echo "::set-output name=branch::$branch"
          echo "Branch is $branch."

  job2:
    runs-on: ubuntu-latest
    needs: check # Wait for check step to finish
    if: ${{ needs.check.outputs.branch == 'master' }} # only run if branch is master

    steps:
      - run: echo "Running task..."

You can get it from the github.event variable:

on:
  push:
    tags:
      - '*'

jobs:
  main:
    runs-on: ubuntu-latest
    steps:
      - name: Echo branch
        run: echo "${{ github.event.base_ref }}"

The code results with:

enter image description here

Related