3

I trigger my workflow using

on:
  push:
    tags:

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

Dmitrii
  • 31
  • 3
  • 1
    You could use `git branch --contains $GITHUB_REF` or `git_branch=$(git for-each-ref | grep ${commit_num} | grep origin | sed "s/.*\///")` (see https://stackoverflow.com/q/12754078/10871900) – dan1st Sep 04 '20 at 17:45
  • @dan1st that doesn't work due to the way that github actions checkout works. You will need to add `-r` flag to contains command to make it work. Example provided in my answer. – Edward Romero Sep 04 '20 at 19:34

1 Answers1

5

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

Edward Romero
  • 2,100
  • 1
  • 2
  • 11
  • 1
    Nice solution! I had some issues: 1. `set-env` is deprecated, so I used `echo "BRANCH=$branch" >> $GITHUB_ENV` 2. The output of git branch contains leading whitespace. I used `branch=${raw##*/}` to remove everything before the last slash. – wensveen Dec 02 '20 at 10:56
  • 1
    If you use checkout@v2, only the last commit will be fetched by default, which makes git branch unable to find the current branch. To resolve this, you need to set `fetch-depth: 0` in the checkout@v2 step. See: https://github.com/actions/checkout#Fetch-all-history-for-all-tags-and-branches – wensveen Dec 02 '20 at 14:07
  • Thanks a lot for this guys, awesome solution. – Kevin Vella Jan 20 '21 at 08:44