Getting the hash of the last commit when merging

I’m using the SHA hash of the last commit as a common value for a few workflows. So when a pull request is made, my PR workflow evaluates {{ github.event.after }} to get this hash, which is not the same as GITHUB_SHA. What I’m retrieving here is the last hash I would see on the GitHub UI before I even make the pull request. This is my common identifier that sets S3 keys, random seeds, etc. So far so good!

When merging the pull request, I have another workflow that triggers on [push]. I’d like to be able to access this same hash. The problem here is that the last commit is now the merge, so really I’m after the second-last commit. My usual tricks with git log don’t seem to work here because the only commit in the log is the merge? When I dump the github context, the has I want exists only in the github.event.commits array, but I’m not sure how to choose the second-last one. Indexing with [-2] doesn’t work, and the array doesn’t have a length attribute).

Is there a way to grab this second-last commit hash on merge? Or, equivalently, a way to grab the last commit hash before the merge? Does this hash have a special name that I’m missing?

I’d be grateful for any help here. I feel like I’m running up against the boundary of my git knowledge, and my practically non-existent Javascript knowledge.

Hi @mdneuzerling,

Glad to see you in Github Community Forum!

Since the hash exists in the github.event.commits array, you can use below sample code to get the second-last id, not ideal but it works.

      - name: get the sha
        run: |
          echo "$GITHUB_CONTEXT"| jq '.event.commits[].id' | tail -2 | head -1 |sed 's/\"//g'
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}

Please refer to my workflow for your reference.

Thanks.

2 Likes

Thank you so much, @weide-zhou! That use of jq is something I doubt I would have gotten to myself.

For anyone else who comes across this thread in the future:

  • The hash I’m referring to in a pull request is actually github.event.pull_request.head.sha, not github.event.after. Under certain circumstances, such as when an open pull request is updated with another commit, these two may be equal.
  • Another option here is to trigger the workflow when the pull request is closed, rather than on push, and then putting if: github.event.pull_request.merged == true in every job in the workflow. It’s messy, but it’s similar to a “when a pull request is merged” trigger. Then the github.event.pull_request context is available for the workflow.