diff --git a/.github/workflows/clear_old_branches.yml b/.github/workflows/clear_old_branches.yml index 514cd3c22..073ce3038 100644 --- a/.github/workflows/clear_old_branches.yml +++ b/.github/workflows/clear_old_branches.yml @@ -38,9 +38,9 @@ jobs: echo "Found $(echo "$EXISTING_BRANCHES" | wc -l) branches to check." - # Get branches from old merged/closed PRs + # Get branches from merged/closed PRs older than 7 days echo "Fetching closed/merged PRs older than 7 days..." - OLD_PR_BRANCHES=$(gh pr list \ + OLD_CLOSED_PR_BRANCHES=$(gh pr list \ --state all \ --base main \ --json state,mergedAt,closedAt,headRefName \ @@ -50,12 +50,32 @@ jobs: select(((.mergedAt // .closedAt) | fromdateiso8601) < ($cutoff | tonumber)) | .headRefName' | sort -u) - # Delete only branches that exist AND are from old PRs + # Get branches with open PRs (never delete these) + echo "Fetching branches with open PRs..." + OPEN_PR_BRANCHES=$(gh pr list \ + --state open \ + --base main \ + --json headRefName \ + --limit 500 | + jq -r '.[].headRefName' | sort -u) + + # Delete only branches that: + # 1. Exist in repo + # 2. Have a merged/closed PR older than 7 days + # 3. Do NOT have an open PR for branch in $EXISTING_BRANCHES; do - if echo "$OLD_PR_BRANCHES" | grep -qx "$branch"; then - echo "Deleting branch: $branch" + # Skip if branch has an open PR + if echo "$OPEN_PR_BRANCHES" | grep -qx "$branch"; then + echo "Skipping (open PR): $branch" + continue + fi + # Only delete if branch has a closed/merged PR + if echo "$OLD_CLOSED_PR_BRANCHES" | grep -qx "$branch"; then + echo "Deleting branch: $branch (PR was merged/closed >7 days ago)" gh api -X DELETE repos/${{ github.repository }}/git/refs/heads/$branch \ || echo "Failed to delete branch $branch" + else + echo "Skipping (no closed PR found): $branch" fi done