Created
April 14, 2025 20:14
-
-
Save adeekshith/77631ca7466e3bed21e7c9bac7b35d68 to your computer and use it in GitHub Desktop.
Auto merge PR that has label AutoMerge. Can be run regularly with cron job or similar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
# Optional: Set to true to update the PR with the base branch before merging | |
UPDATE_BEFORE_MERGE=true | |
# Get current ISO timestamp minus 2 hours | |
TWO_HOURS_AGO=$(date -u -d '2 hours ago' +"%Y-%m-%dT%H:%M:%SZ") | |
# Function to update the PR branch with base (main) | |
update_branch() { | |
local pr="$1" | |
echo "π Updating PR #$pr with base branch..." | |
gh pr update-branch "$pr" || echo "β οΈ Could not update PR #$pr" | |
} | |
# Function to attempt merging a PR | |
try_merge() { | |
local pr="$1" | |
echo "π Trying to merge PR #$pr..." | |
if gh pr merge "$pr" --squash ; then | |
echo "β Merged PR #$pr" | |
else | |
echo "β Merge failed or not ready for PR #$pr" | |
fi | |
} | |
# If no PRs passed, discover eligible ones | |
if [ "$#" -eq 0 ]; then | |
echo "π Discovering mergeable PRs with label 'AutoMerge' updated in the last 2 hours..." | |
mapfile -t PR_LIST < <( | |
gh pr list --state open --label AutoMerge --json number,isDraft,labels,mergeable,updatedAt | | |
jq --arg since "$TWO_HOURS_AGO" ' | |
[ .[] | select( | |
.isDraft == false and | |
.mergeable == "MERGEABLE" and | |
(.labels[].name? | contains("AutoMerge")) and | |
(.updatedAt > $since) | |
) | .number ] | .[]' | |
) | |
else | |
PR_LIST=("$@") | |
fi | |
if [ ${#PR_LIST[@]} -eq 0 ]; then | |
echo "βΉοΈ No eligible PRs to merge." | |
exit 0 | |
fi | |
# Merge each eligible PR | |
for pr in "${PR_LIST[@]}"; do | |
echo "π Processing PR #$pr..." | |
$UPDATE_BEFORE_MERGE && update_branch "$pr" | |
try_merge "$pr" | |
done | |
echo "β Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment