|
| 1 | +name: close-stale-prs |
| 2 | + |
| 3 | +on: |
| 4 | + workflow_dispatch: |
| 5 | + inputs: |
| 6 | + dryRun: |
| 7 | + description: "Log actions without closing PRs" |
| 8 | + type: boolean |
| 9 | + default: false |
| 10 | + schedule: |
| 11 | + - cron: "0 6 * * *" |
| 12 | + |
| 13 | +permissions: |
| 14 | + contents: read |
| 15 | + issues: write |
| 16 | + pull-requests: write |
| 17 | + |
| 18 | +jobs: |
| 19 | + close-stale-prs: |
| 20 | + runs-on: ubuntu-latest |
| 21 | + timeout-minutes: 15 |
| 22 | + steps: |
| 23 | + - name: Close inactive PRs |
| 24 | + uses: actions/github-script@v8 |
| 25 | + with: |
| 26 | + github-token: ${{ secrets.GITHUB_TOKEN }} |
| 27 | + script: | |
| 28 | + const DAYS_INACTIVE = 60 |
| 29 | + const MAX_RETRIES = 3 |
| 30 | +
|
| 31 | + // Adaptive delay: fast for small batches, slower for large to respect |
| 32 | + // GitHub's 80 content-generating requests/minute limit |
| 33 | + const SMALL_BATCH_THRESHOLD = 10 |
| 34 | + const SMALL_BATCH_DELAY_MS = 1000 // 1s for daily operations (≤10 PRs) |
| 35 | + const LARGE_BATCH_DELAY_MS = 2000 // 2s for backlog (>10 PRs) = ~30 ops/min, well under 80 limit |
| 36 | +
|
| 37 | + const startTime = Date.now() |
| 38 | + const cutoff = new Date(Date.now() - DAYS_INACTIVE * 24 * 60 * 60 * 1000) |
| 39 | + const { owner, repo } = context.repo |
| 40 | + const dryRun = context.payload.inputs?.dryRun === "true" |
| 41 | +
|
| 42 | + core.info(`Dry run mode: ${dryRun}`) |
| 43 | + core.info(`Cutoff date: ${cutoff.toISOString()}`) |
| 44 | +
|
| 45 | + function sleep(ms) { |
| 46 | + return new Promise(resolve => setTimeout(resolve, ms)) |
| 47 | + } |
| 48 | +
|
| 49 | + async function withRetry(fn, description = 'API call') { |
| 50 | + let lastError |
| 51 | + for (let attempt = 0; attempt < MAX_RETRIES; attempt++) { |
| 52 | + try { |
| 53 | + const result = await fn() |
| 54 | + return result |
| 55 | + } catch (error) { |
| 56 | + lastError = error |
| 57 | + const isRateLimited = error.status === 403 && |
| 58 | + (error.message?.includes('rate limit') || error.message?.includes('secondary')) |
| 59 | +
|
| 60 | + if (!isRateLimited) { |
| 61 | + throw error |
| 62 | + } |
| 63 | +
|
| 64 | + // Parse retry-after header, default to 60 seconds |
| 65 | + const retryAfter = error.response?.headers?.['retry-after'] |
| 66 | + ? parseInt(error.response.headers['retry-after']) |
| 67 | + : 60 |
| 68 | +
|
| 69 | + // Exponential backoff: retryAfter * 2^attempt |
| 70 | + const backoffMs = retryAfter * 1000 * Math.pow(2, attempt) |
| 71 | +
|
| 72 | + core.warning(`${description}: Rate limited (attempt ${attempt + 1}/${MAX_RETRIES}). Waiting ${backoffMs / 1000}s before retry...`) |
| 73 | +
|
| 74 | + await sleep(backoffMs) |
| 75 | + } |
| 76 | + } |
| 77 | + core.error(`${description}: Max retries (${MAX_RETRIES}) exceeded`) |
| 78 | + throw lastError |
| 79 | + } |
| 80 | +
|
| 81 | + const query = ` |
| 82 | + query($owner: String!, $repo: String!, $cursor: String) { |
| 83 | + repository(owner: $owner, name: $repo) { |
| 84 | + pullRequests(first: 100, states: OPEN, after: $cursor) { |
| 85 | + pageInfo { |
| 86 | + hasNextPage |
| 87 | + endCursor |
| 88 | + } |
| 89 | + nodes { |
| 90 | + number |
| 91 | + title |
| 92 | + author { |
| 93 | + login |
| 94 | + } |
| 95 | + createdAt |
| 96 | + commits(last: 1) { |
| 97 | + nodes { |
| 98 | + commit { |
| 99 | + committedDate |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + comments(last: 1) { |
| 104 | + nodes { |
| 105 | + createdAt |
| 106 | + } |
| 107 | + } |
| 108 | + reviews(last: 1) { |
| 109 | + nodes { |
| 110 | + createdAt |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + ` |
| 118 | +
|
| 119 | + const allPrs = [] |
| 120 | + let cursor = null |
| 121 | + let hasNextPage = true |
| 122 | + let pageCount = 0 |
| 123 | +
|
| 124 | + while (hasNextPage) { |
| 125 | + pageCount++ |
| 126 | + core.info(`Fetching page ${pageCount} of open PRs...`) |
| 127 | +
|
| 128 | + const result = await withRetry( |
| 129 | + () => github.graphql(query, { owner, repo, cursor }), |
| 130 | + `GraphQL page ${pageCount}` |
| 131 | + ) |
| 132 | +
|
| 133 | + allPrs.push(...result.repository.pullRequests.nodes) |
| 134 | + hasNextPage = result.repository.pullRequests.pageInfo.hasNextPage |
| 135 | + cursor = result.repository.pullRequests.pageInfo.endCursor |
| 136 | +
|
| 137 | + core.info(`Page ${pageCount}: fetched ${result.repository.pullRequests.nodes.length} PRs (total: ${allPrs.length})`) |
| 138 | +
|
| 139 | + // Delay between pagination requests (use small batch delay for reads) |
| 140 | + if (hasNextPage) { |
| 141 | + await sleep(SMALL_BATCH_DELAY_MS) |
| 142 | + } |
| 143 | + } |
| 144 | +
|
| 145 | + core.info(`Found ${allPrs.length} open pull requests`) |
| 146 | +
|
| 147 | + const stalePrs = allPrs.filter((pr) => { |
| 148 | + const dates = [ |
| 149 | + new Date(pr.createdAt), |
| 150 | + pr.commits.nodes[0] ? new Date(pr.commits.nodes[0].commit.committedDate) : null, |
| 151 | + pr.comments.nodes[0] ? new Date(pr.comments.nodes[0].createdAt) : null, |
| 152 | + pr.reviews.nodes[0] ? new Date(pr.reviews.nodes[0].createdAt) : null, |
| 153 | + ].filter((d) => d !== null) |
| 154 | +
|
| 155 | + const lastActivity = dates.sort((a, b) => b.getTime() - a.getTime())[0] |
| 156 | +
|
| 157 | + if (!lastActivity || lastActivity > cutoff) { |
| 158 | + core.info(`PR #${pr.number} is fresh (last activity: ${lastActivity?.toISOString() || "unknown"})`) |
| 159 | + return false |
| 160 | + } |
| 161 | +
|
| 162 | + core.info(`PR #${pr.number} is STALE (last activity: ${lastActivity.toISOString()})`) |
| 163 | + return true |
| 164 | + }) |
| 165 | +
|
| 166 | + if (!stalePrs.length) { |
| 167 | + core.info("No stale pull requests found.") |
| 168 | + return |
| 169 | + } |
| 170 | +
|
| 171 | + core.info(`Found ${stalePrs.length} stale pull requests`) |
| 172 | +
|
| 173 | + // ============================================ |
| 174 | + // Close stale PRs |
| 175 | + // ============================================ |
| 176 | + const requestDelayMs = stalePrs.length > SMALL_BATCH_THRESHOLD |
| 177 | + ? LARGE_BATCH_DELAY_MS |
| 178 | + : SMALL_BATCH_DELAY_MS |
| 179 | +
|
| 180 | + core.info(`Using ${requestDelayMs}ms delay between operations (${stalePrs.length > SMALL_BATCH_THRESHOLD ? 'large' : 'small'} batch mode)`) |
| 181 | +
|
| 182 | + let closedCount = 0 |
| 183 | + let skippedCount = 0 |
| 184 | +
|
| 185 | + for (const pr of stalePrs) { |
| 186 | + const issue_number = pr.number |
| 187 | + const closeComment = `Closing this pull request because it has had no updates for more than ${DAYS_INACTIVE} days. If you plan to continue working on it, feel free to reopen or open a new PR.` |
| 188 | +
|
| 189 | + if (dryRun) { |
| 190 | + core.info(`[dry-run] Would close PR #${issue_number} from ${pr.author?.login || 'unknown'}: ${pr.title}`) |
| 191 | + continue |
| 192 | + } |
| 193 | +
|
| 194 | + try { |
| 195 | + // Add comment |
| 196 | + await withRetry( |
| 197 | + () => github.rest.issues.createComment({ |
| 198 | + owner, |
| 199 | + repo, |
| 200 | + issue_number, |
| 201 | + body: closeComment, |
| 202 | + }), |
| 203 | + `Comment on PR #${issue_number}` |
| 204 | + ) |
| 205 | +
|
| 206 | + // Close PR |
| 207 | + await withRetry( |
| 208 | + () => github.rest.pulls.update({ |
| 209 | + owner, |
| 210 | + repo, |
| 211 | + pull_number: issue_number, |
| 212 | + state: "closed", |
| 213 | + }), |
| 214 | + `Close PR #${issue_number}` |
| 215 | + ) |
| 216 | +
|
| 217 | + closedCount++ |
| 218 | + core.info(`Closed PR #${issue_number} from ${pr.author?.login || 'unknown'}: ${pr.title}`) |
| 219 | +
|
| 220 | + // Delay before processing next PR |
| 221 | + await sleep(requestDelayMs) |
| 222 | + } catch (error) { |
| 223 | + skippedCount++ |
| 224 | + core.error(`Failed to close PR #${issue_number}: ${error.message}`) |
| 225 | + } |
| 226 | + } |
| 227 | +
|
| 228 | + const elapsed = Math.round((Date.now() - startTime) / 1000) |
| 229 | + core.info(`\n========== Summary ==========`) |
| 230 | + core.info(`Total open PRs found: ${allPrs.length}`) |
| 231 | + core.info(`Stale PRs identified: ${stalePrs.length}`) |
| 232 | + core.info(`PRs closed: ${closedCount}`) |
| 233 | + core.info(`PRs skipped (errors): ${skippedCount}`) |
| 234 | + core.info(`Elapsed time: ${elapsed}s`) |
| 235 | + core.info(`=============================`) |
0 commit comments