5

I am trying to find the SHA of the commit where a branch split from another branch in a GitHub Action.

Locally, I can achieve this by running git merge-base <commit> <commit>. I am trying to achieve the same in a workflow.

I've got the following workflow.yaml:

name: "Find common ancestor"

on:
  pull_request:
    branches:
      - master

jobs:
  find:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0     

      - name: Find common ancestor
        run: git merge-base "$GITHUB_HEAD_REF" "$GITHUB_BASE_REF"

When the workflow runs when a pull request for a branch 'dev' into 'master' is opened, the workflow reports the following error:

2021-08-14T19:17:04.5732118Z fatal: Not a valid object name dev

All of my research points towards needing to set fetch-depth. I understand that without setting fetch-depth to 0, only a shallow clone is fetched. Unfortunately, even with fetch-depth set to 0, the workflow cannot find the necessary refs, and I am out of ideas.

Does anybody know why merge-base cannot recognize the refs, or know an alternative for finding the common ancestor?

EDIT:

Running git branch -a, I've discovered that the refs are prepended with remote/origin/*, which explains why they could not be found when calling merge-base. Why can't I access the local branches after checking out?

Florian
  • 95
  • 4

1 Answers1

4
  FindCommon:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Find common ancestor
        env:
          BASE_BRANCH: ${{ github.base_ref }}
        run: git merge-base --fork-point origin/$BASE_BRANCH

works for me.

Aron Woost
  • 19,268
  • 13
  • 43
  • 51
  • 1
    If someone else pushes another commit to origin/$BASE_BRANCH, that new commit hash will be returned. Is there a way to get the commit hash in origin/$BASE_BRANCH when the pr first opened? What's the difference between this solution and using ${{ github.event.pull_request.base_sha }}? wanna use it to diff only my changes from the base branch – user3687289 Jul 24 '22 at 15:39