From 427c9b35dc9d43009cbdffeb7a460d523d253c11 Mon Sep 17 00:00:00 2001 From: Cheng-Yang Chou Date: Mon, 24 Mar 2025 17:22:21 +0800 Subject: [PATCH] Introduce REST API fallback Switch to using the GitHub REST API as a fallback when HTML parsing fails to retrieve the commit hash from the GitHub commits page. This ensures that the script continues to work even under rate limit conditions and improves reliability. Optionally, authentication can be used to further mitigate rate limits. Co-authored-by: Po-Ying Chiu Change-Id: I8688fdb093e88ed95326b911f198c974cd615ad4 --- scripts/check-repo.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scripts/check-repo.sh b/scripts/check-repo.sh index 69b428c2b..3cac89e9e 100755 --- a/scripts/check-repo.sh +++ b/scripts/check-repo.sh @@ -85,6 +85,28 @@ upstream_hash=$( rm -f "$temp_file" +# If HTML parsing fails, fallback to using GitHub REST API +if [ -z "$upstream_hash" ]; then + API_URL="https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/commits" + + # Try to use cached GitHub credentials from GitHub CLI + # https://docs.github.com/en/get-started/git-basics/caching-your-github-credentials-in-git + if command -v gh >/dev/null 2>&1; then + TOKEN=$(gh auth token 2>/dev/null) + if [ -n "$TOKEN" ]; then + response=$(curl -sSL -H "Authorization: token $TOKEN" "$API_URL") + fi + fi + + # If response is empty (i.e. token not available or failed), use unauthenticated request. + if [ -z "$response" ]; then + response=$(curl -sSL "$API_URL") + fi + + # Extract the latest commit SHA from the JSON response + upstream_hash=$(echo "$response" | grep -m 1 '"sha":' | sed -E 's/.*"sha": "([^"]+)".*/\1/') +fi + if [ -z "$upstream_hash" ]; then throw "Failed to retrieve upstream commit hash from GitHub.\n" fi