Get commit SHA in Github actions
In a Github action you can get the commit SHA using ${GITHUB_SHA}
, which is a default env variable.. However, this commit SHA seems to be a merge commit!? which does not equal the commit SHA displayed on PR's Github UI. Any thoughts on how I can get the SHA that is displayed in PRs (on Github UI)?
To understand what happens
Reference: Github community post with the weide-zhou (Github Partner) answer.
When you can create a pull request, github will execute workflow based on a fake merge branch:
refs/pull/:prNumber/merge
, themerge_commit_sha
doesn’t exist on base or head branch, but points to that surrogate merge commit, and there is a mergeable key to show the status of the test commit.Therefore, here, the
github.sha
stands for the actual merge commit.
Github Variables
Tip: you can print the GitHub variables
using the following step:
- name: Show GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
It seems that what you want here is the ${{ github.event.pull_request.head.sha }}
value.
In the case of pull_request
, the hash of the latest commit can be found in the ${{ github.event.pull_request.head.sha }}
variable, whereas ${{ github.sha }}
refers to the PR merge commit.
Note that if the pull_request has been opened for a fork repo, the github.event.pull_request
variable will be empty (don't know if it's a bug or something they are working on).