1 parent
3b0e25bc4b
commit
94f22e7cde
5 files changed
+256
No files matched your search
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Daily stale pull-request reminders for the `Stale pull requests` workflow.
|
||||
*
|
||||
* A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review
|
||||
* event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross
|
||||
* references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow
|
||||
* comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE`
|
||||
* and pull requests opened by bots receive no reminders. The workflow never closes pull requests.
|
||||
*
|
||||
* Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently updated pull requests first, so a backlog
|
||||
* spreads over several days within GitHub's content-creation limits. A failed pull request is reported and skipped.
|
||||
*/
|
||||
|
||||
/** Label that exempts a pull request from reminders. */
|
||||
export const EXEMPT_LABEL = 'DO_NOT_CLOSE'
|
||||
|
||||
/** Days without activity after which each reminder is posted, in ascending order. */
|
||||
export const REMINDER_DAYS = [7, 14]
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
// GitHub asks integrations to wait at least one second between content-creating requests.
|
||||
const COMMENT_INTERVAL_MS = 1000
|
||||
const MAX_COMMENTS_PER_RUN = 100
|
||||
const MARKER = /<!-- stale-pr-reminder:(\d+) -->/
|
||||
// Review bots that use ordinary user accounts.
|
||||
const BOT_LOGINS = new Set(['ds-review-bot'])
|
||||
|
||||
const isBot = account => account?.type === 'Bot' || (account?.login ?? '').endsWith('[bot]') || BOT_LOGINS.has(account?.login)
|
||||
|
||||
/**
|
||||
* Returns the timestamps a timeline event contributes to the last activity.
|
||||
* @param {object} event GitHub issue timeline event.
|
||||
* @returns {string[]} ISO timestamps; empty for bot activity and events that are not activity.
|
||||
*/
|
||||
function activityTimes(event) {
|
||||
switch (event.event) {
|
||||
case 'committed':
|
||||
return [event.committer?.date].filter(Boolean)
|
||||
case 'head_ref_force_pushed':
|
||||
case 'reopened':
|
||||
case 'ready_for_review':
|
||||
return [event.created_at]
|
||||
case 'commented':
|
||||
return isBot(event.actor) ? [] : [event.created_at]
|
||||
case 'line-commented':
|
||||
case 'commit-commented':
|
||||
return (event.comments ?? []).filter(comment => !isBot(comment.user)).map(comment => comment.created_at)
|
||||
case 'reviewed':
|
||||
return isBot(event.user) ? [] : [event.submitted_at]
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the reminder a pull request is due for.
|
||||
* @param {object} options
|
||||
* @param {string} options.createdAt Pull-request creation time.
|
||||
* @param {object[]} options.timeline Complete issue timeline of the pull request.
|
||||
* @param {Date} options.now Evaluation time.
|
||||
* @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due.
|
||||
*/
|
||||
export function dueReminder({ createdAt, timeline, now }) {
|
||||
const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite)
|
||||
const lastActivity = Math.max(...times)
|
||||
const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1)
|
||||
if (due === undefined) return undefined
|
||||
const sent = timeline
|
||||
.filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity)
|
||||
.map(event => Number(MARKER.exec(event.body ?? '')?.[1]))
|
||||
return sent.some(days => days >= due) ? undefined : due
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the reminder comment.
|
||||
* @param {string} author Pull-request author login.
|
||||
* @param {number} days Reminder stage in days.
|
||||
* @returns {string} Comment body.
|
||||
*/
|
||||
export function reminderBody(author, days) {
|
||||
return [
|
||||
`<!-- stale-pr-reminder:${days} -->`,
|
||||
`@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label to stop these reminders.`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts every due reminder on open pull requests of the workflow repository.
|
||||
* @param {object} options
|
||||
* @param {object} options.github Authenticated Octokit client from `actions/github-script`.
|
||||
* @param {object} options.context Workflow context from `actions/github-script`.
|
||||
* @param {object} options.core Actions toolkit core from `actions/github-script`.
|
||||
* @param {Date} [options.now] Evaluation time.
|
||||
* @param {(ms: number) => Promise<void>} [options.sleep] Delay between comments.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
|
||||
const { owner, repo } = context.repo
|
||||
const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 })
|
||||
// Pull requests updated within the last six days skip the timeline read: a reminder becomes due at least seven days
|
||||
// after the last activity, and the day margin covers the time a run takes to reach a pull request.
|
||||
const cutoff = now.getTime() - (REMINDER_DAYS[0] - 1) * DAY_MS
|
||||
let posted = 0
|
||||
let failed = 0
|
||||
for (const pull of pulls) {
|
||||
if (posted >= MAX_COMMENTS_PER_RUN) break
|
||||
if (isBot(pull.user) || Date.parse(pull.updated_at) > cutoff) continue
|
||||
if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue
|
||||
try {
|
||||
const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 })
|
||||
const days = dueReminder({ createdAt: pull.created_at, timeline, now })
|
||||
if (days === undefined) continue
|
||||
if (posted > 0) await sleep(COMMENT_INTERVAL_MS)
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) })
|
||||
posted++
|
||||
core.info(`#${pull.number}: posted the ${days}-day reminder`)
|
||||
} catch (error) {
|
||||
failed++
|
||||
core.warning(`#${pull.number}: ${error.message}`)
|
||||
}
|
||||
}
|
||||
if (failed > 0) core.setFailed(`${failed} pull requests failed; see the warnings above.`)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs'
|
||||
|
||||
const now = new Date('2026-11-30T00:00:00Z')
|
||||
const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString()
|
||||
const human = { login: 'author', type: 'User' }
|
||||
const bot = { login: 'github-actions[bot]', type: 'Bot' }
|
||||
const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body })
|
||||
const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage))
|
||||
|
||||
test('no reminder is due within 7 days of the last activity', () => {
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined)
|
||||
})
|
||||
|
||||
test('the latest due stage is posted once after the last activity', () => {
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined)
|
||||
})
|
||||
|
||||
test('human activity restarts the cycle and bot activity does not', () => {
|
||||
const sentBefore = [reminder(30, 7), reminder(23, 14)]
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined)
|
||||
})
|
||||
|
||||
test('mentions, labels and cross references are not activity', () => {
|
||||
const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) })
|
||||
// GitHub records a `mentioned` event for the author right after each reminder.
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14)
|
||||
})
|
||||
|
||||
test('reminders mention the author and skip exempt, bot-authored and recently updated pull requests', async () => {
|
||||
const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides })
|
||||
const pulls = [
|
||||
pull(1),
|
||||
pull(2, { labels: [{ name: 'DO_NOT_CLOSE' }] }),
|
||||
pull(3, { user: { login: 'dependabot[bot]', type: 'Bot' } }),
|
||||
pull(4, { updated_at: daysAgo(1) }),
|
||||
pull(6),
|
||||
pull(5),
|
||||
]
|
||||
const comments = []
|
||||
const timelines = []
|
||||
const github = {
|
||||
rest: {
|
||||
pulls: { list: 'pulls' },
|
||||
issues: {
|
||||
listEventsForTimeline: 'timeline',
|
||||
createComment: async params => {
|
||||
if (params.issue_number === 6) throw new Error('locked')
|
||||
comments.push(params)
|
||||
},
|
||||
},
|
||||
},
|
||||
paginate: async (method, params) => {
|
||||
if (method === 'pulls') return pulls
|
||||
timelines.push(params.issue_number)
|
||||
return []
|
||||
},
|
||||
}
|
||||
const sleeps = []
|
||||
const warnings = []
|
||||
const failures = []
|
||||
const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) }
|
||||
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) })
|
||||
assert.deepEqual(timelines, [1, 6, 5])
|
||||
assert.deepEqual(warnings, ['#6: locked'])
|
||||
assert.equal(failures.length, 1)
|
||||
assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 5])
|
||||
assert.match(comments[0].body, /^<!-- stale-pr-reminder:14 -->\n@author This pull request has had no activity for 14 days\./)
|
||||
assert.deepEqual(sleeps, [1000, 1000])
|
||||
})
|
||||
|
||||
test('a run posts at most 100 reminders', async () => {
|
||||
const pulls = Array.from({ length: 105 }, (_, number) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20) }))
|
||||
let comments = 0
|
||||
const github = {
|
||||
rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } },
|
||||
paginate: async method => method === 'pulls' ? pulls : [],
|
||||
}
|
||||
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} })
|
||||
assert.equal(comments, 100)
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them.
|
||||
# Rules: .github/stale-pull-requests/remind.mjs.
|
||||
name: Stale pull requests
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: stale-pull-requests
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
remind:
|
||||
name: Remind stale pull requests
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Check out reminder rules
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
sparse-checkout: .github/stale-pull-requests
|
||||
persist-credentials: false
|
||||
- name: Post due reminders
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3
|
||||
with:
|
||||
script: |
|
||||
const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`)
|
||||
await remindStalePullRequests({ github, context, core })
|
||||
@@ -70,6 +70,7 @@
|
||||
"test:expected:refresh": "DSH_SNAPSHOT=refresh vitest run --config vitest.expected.config.ts",
|
||||
"test:approval-policy": "node --test .github/review-ownership/check-approval.test.mjs .github/review-ownership/blame-ownership.test.mjs .github/review-ownership/author-weight.test.mjs",
|
||||
"test:issue-management": "node .github/issue-management/policy.test.mjs",
|
||||
"test:stale-pull-requests": "node --test .github/stale-pull-requests/remind.test.mjs",
|
||||
"test:snapshot": "vitest run --config vitest.snapshot.config.ts",
|
||||
"test:snapshot:record": "DSH_SNAPSHOT=record vitest run --config vitest.snapshot.config.ts --update",
|
||||
"test:snapshot:refresh": "DSH_SNAPSHOT=refresh vitest run --config vitest.snapshot.config.ts",
|
||||
|
||||
@@ -357,6 +357,7 @@ export function gatesForMode(selected: Mode): Gate[] {
|
||||
pnpmScript('test', 'test'),
|
||||
pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }),
|
||||
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
|
||||
pnpmScript('stale-pull-requests', 'test:stale-pull-requests', { label: 'Stale pull-request reminders' }),
|
||||
pnpmScript('duplication', 'duplication'),
|
||||
snapshotGate(),
|
||||
expectedOutputGate(),
|
||||
@@ -401,6 +402,7 @@ function ciSharedStaticGates(): Gate[] {
|
||||
...sharedHygieneGates(),
|
||||
pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }),
|
||||
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
|
||||
pnpmScript('stale-pull-requests', 'test:stale-pull-requests', { label: 'Stale pull-request reminders' }),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user