I trigger my workflow using
on:
push:
tags:
GITHUB_REF
won't contain a branch name in this case, how could I get it?
Tags and branch are completely unrelated, since tags refer to a specific commit, and branch is a moving reference to the last commit of a history. Branches go, tags stay. So when you tag a commit, git doesn't care which commit or branch is checked out, if you provide him the SHA1 of what you want to tag.
git push <remote> --tags will push both lightweight and annotated tags. There is currently no option to push only lightweight tags, but if you use git push <remote> --follow-tags only annotated tags will be pushed to the remote.
ID is used as a reference, from other jobs or steps (for example, in jobs. <job_id>. needs ). Name is used for display purposes on GitHub.
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..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With