Skip to content

Commit d1b1296

Browse files
committed
fix: Handle cases when BASE SHA isn't known - push events
If the first commit is pushed to a new branch, `${{ github.event.before }}` has a default value of `0000000000000000000000000000000000000000`. When we detect such SHA, we should try to get older `BASE` SHA from the `HEAD` branch if possible. Inspired by: * [How can I get the previous commit before a push or merge in GitHub Action workflow? - Answered by Peter Evans](https://stackoverflow.com/a/61861763/10221282) * [tj-actions/changed-files GitHub Action](https://github.com/tj-actions/changed-files/blob/main/diff-sha.sh#L116-L118)
1 parent d24099b commit d1b1296

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/functions.sh

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,16 @@ is_strict_check_on_push_demanded () {
4141

4242
# Function that picks values of BASE and HEAD commit based on triggrring event (INPUT_TRIGGERING_EVENT)
4343
# It sets BASE and HEAD for external use.
44+
# https://github.com/tj-actions/changed-files/blob/main/diff-sha.sh#L116-L118
45+
# https://stackoverflow.com/a/61861763/10221282
4446
# $? - return value - 0 on success
4547
pick_base_and_head_hash () {
4648
case ${INPUT_TRIGGERING_EVENT-${GITHUB_EVENT_NAME}} in
4749
"push")
50+
if [[ -z "${INPUT_PUSH_EVENT_BASE}" || "${INPUT_PUSH_EVENT_BASE}" == "0000000000000000000000000000000000000000" ]]; then
51+
INPUT_PUSH_EVENT_BASE=$(git rev-list -n 1 "HEAD~1")
52+
fi
53+
4854
export BASE=${INPUT_PUSH_EVENT_BASE:-}
4955
export HEAD=${INPUT_PUSH_EVENT_HEAD:-}
5056
[[ ${UNIT_TESTS:-1} -eq 0 ]] && echo "BASE:\"${BASE}\" ; HEAD:\"${HEAD}\""

test/pick_base_and_head_hash.bats

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@ setup () {
4040
# assert_equal "\"${HEAD}\"" "\"${INPUT_PUSH_EVENT_HEAD}\""
4141
}
4242

43+
@test "pick_base_and_head_hash() - trigger event = push - first commit/new branch" {
44+
source "${PROJECT_ROOT}/src/functions.sh"
45+
46+
INPUT_TRIGGERING_EVENT="push"
47+
48+
UNIT_TESTS=0
49+
INPUT_PUSH_EVENT_BASE="0000000000000000000000000000000000000000"
50+
TRUE_BASE=$(git rev-list -n 1 "HEAD~1")
51+
INPUT_PUSH_EVENT_HEAD="ghijkl789012"
52+
53+
run pick_base_and_head_hash
54+
assert_success
55+
assert_output "BASE:\"${TRUE_BASE}\" ; HEAD:\"${INPUT_PUSH_EVENT_HEAD}\""
56+
# TODO: Doesn't work, don't know why...
57+
# assert_equal "\"${BASE}\"" "\"${TRUE_BASE}\""
58+
# assert_equal "\"${HEAD}\"" "\"${INPUT_PUSH_EVENT_HEAD}\""
59+
}
60+
4361
@test "pick_base_and_head_hash() - trigger event = pull_request" {
4462
source "${PROJECT_ROOT}/src/functions.sh"
4563

0 commit comments

Comments
 (0)