10

In GitHub action on pull request, I need to run some code in the context of the "current master", and later re-run the same code in the context of the PR branch.

I can check out compare a pull request to the base it is being PR-ed against. How would I find the SHA of the base branch (e.g. current master if PR is against the master)?

jobs:
  job_on_base:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: "${{ github.base_ref }}"
      - run: |
          # Seems like I can get it here with $(git log -1 --format="%H")
          echo "My current SHA is ... ?"

  job_on_pr:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: "${{ github.ref }}"
      - run: |
          echo "My current SHA is $GITHUB_SHA"
          echo "The BASE SHA is ?"
Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97

3 Answers3

14

If the job runs on a pull_request event the base sha is available as ${{ github.event.pull_request.base.sha }}

Jacob Rask
  • 22,804
  • 8
  • 38
  • 36
  • 9
    and if anyone is looking here for branch's sha it's: `${{github.event.pull_request.head.sha}}` https://github.com/actions/checkout#checkout-pull-request-head-commit-instead-of-merge-commit – Danny Varod Dec 14 '21 at 12:32
6

What worked for me was: github.event.workflow_run.head_sha.

The top-voted answer suggesting github.event.pull_request.head.sha didn't work for me.

I found this by examining all the possible data in the github.context object using the method suggested here - https://stackoverflow.com/a/70107953

Ben Perlmutter
  • 111
  • 2
  • 4
3

This turned out to be a git question, rather than Github actions. The actions/checkout@v2 creates a shallow --depth=1 clone, so to get PR's parent one can parse git cat-file -p output as described here. The first (base) parent could be accessed with

git cat-file -p <SHA> | awk 'NR > 1 {if(/^parent/){print $2; exit}}'

The better approach turned out to be using fetch-depth: 2 parameter. It allows just one job to handle both pull request and master merge cases, and can also be used with HEAD^1 to get to the parent.

steps:
  - uses: actions/checkout@v2
    with:
      fetch-depth: 2
Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97