From 43079f4ff0c01b8cab8abf4b6d7f688a16ba7251 Mon Sep 17 00:00:00 2001
From: Antti Kaihola <13725+akaihola@users.noreply.github.com>
Date: Tue, 30 Jul 2024 17:23:42 +0300
Subject: [PATCH] Handle force pushes

---
 .github/actions/commit-range/action.yml | 32 +++++++++++++++----------
 1 file changed, 19 insertions(+), 13 deletions(-)

diff --git a/.github/actions/commit-range/action.yml b/.github/actions/commit-range/action.yml
index 859001b4a..dfadfce62 100644
--- a/.github/actions/commit-range/action.yml
+++ b/.github/actions/commit-range/action.yml
@@ -42,27 +42,33 @@ runs:
         elif [[ "${{ github.event_name }}" == "push" ]]; then
           echo "Processing a push event"
           echo "Ref: ${{ github.ref }}"
-          echo "Before SHA: ${{ github.event.before }}"
           echo "After SHA: ${{ github.sha }}"
 
-          if [[ "${{ github.event.before }}" == \
-                "0000000000000000000000000000000000000000" ]]; then
-            echo "This is a push to a new branch"
-            echo "Fetching first commit of the branch from GitHub API..."
-            first_commit=$(gh api \
-              repos/${{ github.repository }}/commits/${{ github.ref_name }} \
-              --jq '.parents[0].sha // .sha')
-            echo "First commit (or its parent): ${first_commit}"
-            range="${first_commit}...${{ github.sha }}"
+          echo "Fetching the pull request information..."
+          pr_info=$(\
+            gh pr list \
+              --head ${{ github.ref_name }} \
+              --json number,baseRefName \
+              --limit 1)
+          if [[ -n "$pr_info" ]]; then
+            base_branch=$(echo "$pr_info" | jq -r '.[0].baseRefName')
+            echo "Associated PR found. Base branch: ${base_branch}"
           else
-            echo "This is a push to an existing branch"
-            range="${{ github.event.before }}...${{ github.sha }}"
+            echo "No associated PR found. Using default branch as base."
+            base_branch=$(gh api repos/${{ github.repository }} --jq '.default_branch')
           fi
+          echo "Base branch: ${base_branch}"
 
+          echo "Finding the branch point..."
+          branch_point=$(git merge-base origin/${base_branch} ${{ github.sha }})
+          echo "Branch point: ${branch_point}"
+
+          range="${branch_point}...${{ github.sha }}"
           echo "Calculated range: ${range}"
           echo "range=${range}" >> $GITHUB_OUTPUT
 
-          echo "This range represents all new commits pushed to the branch."
+          echo "This range represents all commits in the current branch since it"
+          echo "diverged from the base branch."
 
         else
           echo "Error: Unsupported event type: ${{ github.event_name }}"