gitgithub-actionspull-requestgit-commitgithub-webhook

Retrieve commit message in a GH Action triggered on pull request


I want to create a GitHub Actions workflow triggered on pull_request. The workflow should get the last commit message in the Pull Request and check it against a given regular expression.

The part I am struggling on is actually getting the last commit message.

My workflow looks like this:

---
name: CI-PR-Check

on:
  pull_request:

jobs:
  build:
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout
        uses: actions/checkout@v3
 
      - name: Check commit message
        shell: bash
        run: |
          echo "commit message validation"
          message=$(git log --pretty=%B -n 1)
          python ${{ github.action_path }}/commitcheck.py "$message"

I expected the line message=$(git log --pretty=%B -n 1) to get me the message of the last commit, but I get the message from the pull request, so something like Merge <some sha> into <other sha>.

Using GitHub webhook events, I am able to get the sha of the commit that I am interested in using sha="${{ github.event.pull_request.head.sha }}". However, it is still not possible to get the commit message with git log --format=%B -n 1 $sha. I get an error fatal: bad object <my sha>.

Is there any way to get my commit message ?


Solution

  • As mentioned in a comment, actions/checkout is shallow by default, so the first step is to set fetch-depth to 0:

    - name: Checkout
      uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
      with:
        fetch-depth: 0
    

    I settled on this to retrieve all the commits in the PR:

    # retrieve pr id
    IFS=$'\/' read -r prId _ <<< $GITHUB_REF_NAME
    
    # fetch all commits
    prCommits=`gh pr view $prId --json commits | jq '.commits | length'`
    fetchDepthToPrBase=`expr $prCommits + 2`
    git fetch --no-tags --prune --progress --no-recurse-submodules --deepen=$fetchDepthToPrBase
    
    # retrive the commits of the PR
    commits="$(gh pr view $prId --json commits)"