Skip to content

Instantly share code, notes, and snippets.

@adeekshith
Created April 14, 2025 20:14
Show Gist options
  • Save adeekshith/77631ca7466e3bed21e7c9bac7b35d68 to your computer and use it in GitHub Desktop.
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
#!/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