'Determine source branch name on merge push in GitHub action workflow
I have a GitHub action workflow where I am doing a merge of various different source branches into target branch main.
Here is a test workflow to read the values of env variables:
name: Print Github Env Variables
on:
push:
branches:
- main
- test
pull_request:
branches:
- main
- test
workflow_dispatch:
jobs:
print-env-variabes:
name: Print Github Variables
runs-on: ubuntu-latest
steps:
- name: Print Github Variables
run: |
echo "GITHUB_WORKFLOW:$GITHUB_WORKFLOW"
echo "GITHUB_EVENT_NAME:$GITHUB_EVENT_NAME"
echo "GITHUB_EVENT_PATH:$GITHUB_EVENT_PATH"
echo "GITHUB_WORKSPACE:$GITHUB_WORKSPACE"
echo "GITHUB_SHA:$GITHUB_SHA"
echo "GITHUB_REF:$GITHUB_REF"
echo "GITHUB_HEAD_REF:$GITHUB_HEAD_REF"
- name: Print complete webhook event payload
run: cat $GITHUB_EVENT_PATH
Create test.txt file in a branch called test, create a pull request then merge into main. You will see what I am seeing then.
When I look at GITHUB_REF it contains main branch.
For pull_requests GITHUB_HEAD_REF contains ‘test’, but for push it is empty. I need the value when the files get merged, so when a push occurs.
The test workflow also prints out the entire event json object, on push event I didn’t see any entry with the branch ‘test’ in there either.
How do I get the name of the source branch during a push event?
Solution 1:[1]
This works for me after a merge request:
export LATESTLOG=$(git log -1 --pretty=%B)
export SOURCEBRANCH=$(echo $LATESTLOG | awk -F '\\\\n' '{print $1}' | awk -F '/' '{print $2}' | awk '{print $1}')
Solution 2:[2]
name: Test closed branch
on:
pull_request:
types: [closed]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Get PR closed number
env:
PR_NUMBER: ${{ toJson(github.event.number) }}
run: |
echo "$PR_NUMBER"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Finn Arild Aasheim |
Solution 2 | utiq |