Skip to content

Commit

Permalink
fix: Handle cases when BASE SHA isn't known - push events
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
jamacku committed Jan 27, 2023
1 parent d24099b commit a666fc6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/functions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,16 @@ is_strict_check_on_push_demanded () {

# Function that picks values of BASE and HEAD commit based on triggrring event (INPUT_TRIGGERING_EVENT)
# It sets BASE and HEAD for external use.
# https://github.com/tj-actions/changed-files/blob/main/diff-sha.sh#L116-L118
# https://stackoverflow.com/a/61861763/10221282
# $? - return value - 0 on success
pick_base_and_head_hash () {
case ${INPUT_TRIGGERING_EVENT-${GITHUB_EVENT_NAME}} in
"push")
if [[ -z "${INPUT_PUSH_EVENT_BASE}" || "${INPUT_PUSH_EVENT_BASE}" == "0000000000000000000000000000000000000000" ]]; then
INPUT_PUSH_EVENT_BASE=$(git rev-list -n 1 "HEAD~1")
fi

export BASE=${INPUT_PUSH_EVENT_BASE:-}
export HEAD=${INPUT_PUSH_EVENT_HEAD:-}
[[ ${UNIT_TESTS:-1} -eq 0 ]] && echo "BASE:\"${BASE}\" ; HEAD:\"${HEAD}\""
Expand Down
19 changes: 19 additions & 0 deletions test/pick_base_and_head_hash.bats
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ setup () {
# assert_equal "\"${HEAD}\"" "\"${INPUT_PUSH_EVENT_HEAD}\""
}

@test "pick_base_and_head_hash() - trigger event = push - first commit/new branch" {
source "${PROJECT_ROOT}/src/functions.sh"

INPUT_TRIGGERING_EVENT="push"

UNIT_TESTS=0
INPUT_PUSH_EVENT_BASE="0000000000000000000000000000000000000000"
INPUT_PUSH_EVENT_HEAD="ghijkl789012"

run pick_base_and_head_hash
assert_success
assert_output \
"first commit on new branch detected
BASE:\"${TRUE_BASE}\" ; HEAD:\"${INPUT_PUSH_EVENT_HEAD}\""
# TODO: Doesn't work, don't know why...
# assert_equal "\"${BASE}\"" "\"${TRUE_BASE}\""
# assert_equal "\"${HEAD}\"" "\"${INPUT_PUSH_EVENT_HEAD}\""
}

@test "pick_base_and_head_hash() - trigger event = pull_request" {
source "${PROJECT_ROOT}/src/functions.sh"

Expand Down

0 comments on commit a666fc6

Please sign in to comment.