Yuri Astrakhan
Yuri Astrakhan

Reputation: 9965

Getting base branch SHA on pull request in Github Action Workflow

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 ?"

Upvotes: 13

Views: 17261

Answers (4)

IanEdington
IanEdington

Reputation: 526

I ran into this issue and found that there isn't one place you can get the SHA. This is what I'm using

- name: some task
  env:
    PR_SHA: ${{ github.event.pull_request.head.sha }}
    GITHUB_SHA: ${{ github.sha }}
  run: |
    COMMIT_SHA="${PR_SHA:-$GITHUB_SHA}"
    <some other work>

Upvotes: 1

Ben Perlmutter
Ben Perlmutter

Reputation: 131

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

Upvotes: 6

Jacob Rask
Jacob Rask

Reputation: 24368

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

Upvotes: 20

Yuri Astrakhan
Yuri Astrakhan

Reputation: 9965

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

Upvotes: 3

Related Questions