Reputation: 41
I have a GitHub action running my unit tests for a web app. I run CodeClimate test reporting from this action.
CodeClimate requires two environment variables to be set for the report to be correctly sent. These are;
GitHub actions makes the git commit sha avaiable through the github context via github.sha
so I can set an environment variable on the action like this;
env:
GIT_SHA: ${{ github.sha }}
However github actions does not make the branch name available.
It does provide a default environment variable called GITHUB_REF
this is the full ref but I understand that I can grab the short ref i.e. the branch name using this shorthand syntax $GITHUB_REF##*/
The problem I have is that I cannot set an env variable called GITHUB_BRANCH with this value $GITHUB_REF##*/
Does anyone how I might get the branch name and set it to the environment variable GIT_BRANCH
so the CodeClimate test script would be able to use it.
Ultimately I want my env config to look like this:
env:
GIT_SHA: <git commit sha>
GIT_BRANCH: <current git branch>
Upvotes: 2
Views: 10651
Reputation: 31
Indeed, rather than using GITHUB_REF, it could be useful to use GITHUB_HEAD_REF or GITHUB_BASE_REF to figure out the real branch names (above all, if workflow is associated to a PR):
Examples of output:
GITHUB_REF="refs/pull/4/merge"
GITHUB_BASE_REF="main"
GITHUB_HEAD_REF="key_advertisement"
More information here: https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
Upvotes: 3
Reputation: 5961
Ultimately I want my env config to look like this:
env: GIT_SHA: <git commit sha> GIT_BRANCH: <current git branch>
You can achieve the same effect (setting the environment variables) not only in the workflow definition but by setting the variables dynamically in a dedicated workflow step. You can do it by environment files and built-in GITHUB_SHA
and GITHUB_BRANCH
variables:
jobs:
set-env:
runs-on: ubuntu-latest
steps:
- name: Set environment variables
run: |
echo "GIT_SHA=${GITHUB_SHA}" >> $GITHUB_ENV
echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV
- name: Use environment variables
run: |
echo "GIT_SHA=${GIT_SHA}"
echo "GIT_BRANCH=${GIT_BRANCH}"
Executing the workflow should give you the output:
Upvotes: 9