/** * Pull request rules (#1669). `checkPr` decides; `checkPullRequest` runs from * .github/workflows/pr-rules.yml and keeps one comment on the PR up to date. */ import { BOT_LOGIN, loadMaintainers, prRulesStart, sameUser } from "./issue-claims.mjs"; export const MAX_OPEN_PRS = 5; // On since #1815; set to false to go back to warning only. const ENFORCE = true; export const MARKER = ""; const RULES_URL = "https://github.com/OWASP/cve-lite-cli/blob/main/CONTRIBUTING.md#opening-a-pull-request"; /** One sentence per broken rule; empty when the PR is fine. */ export function checkPr({ author, linkedIssues, olderOpenPrs }) { const problems = []; if (linkedIssues.length === 0) { problems.push( "No linked issue. Add `Closes #NNN` to the description, where #NNN is an issue, not a pull request; every pull request needs one, even typo and docs fixes.", ); } for (const issue of linkedIssues) { if (issue.assignees.some((login) => sameUser(login, author))) { continue; } if (issue.assignees.length > 0) { problems.push(`#${issue.number} is assigned to someone else. Pick a free issue, or ask the assignee there first.`); } else if (sameUser(issue.author, author)) { problems.push(`#${issue.number} isn't assigned to you. You opened it, so comment \`/assign-me\` on it to claim it.`); } else { problems.push(`#${issue.number} isn't assigned to you. Comment \`/assign-me\` on it if it's open for claiming, or ask a maintainer.`); } } if (olderOpenPrs >= MAX_OPEN_PRS) { problems.push(`You already had ${olderOpenPrs} open pull requests when you opened this one; the limit is ${MAX_OPEN_PRS}. Wait until some are merged or closed.`); } return problems; } function rulesComment({ author, problems, enforce }) { if (problems.length === 0) { return `${MARKER}\nThanks @${author}, this pull request now meets the [contribution rules](${RULES_URL}).`; } return [ MARKER, `@${author} this pull request doesn't meet the [contribution rules](${RULES_URL}) yet:`, "", ...problems.map((problem) => `- ${problem}`), "", `${enforce ? "This check fails until they're fixed." : "This is only a warning for now."} Edit the description or push a commit to re-check.`, ].join("\n"); } const LINKED_ISSUES_QUERY = ` query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { closingIssuesReferences(first: 20) { nodes { number author { login } assignees(first: 20) { nodes { login } } repository { nameWithOwner } } } } } }`; async function linkedIssues(github, { owner, repo }, number) { const result = await github.graphql(LINKED_ISSUES_QUERY, { owner, repo, number }); return (result.repository?.pullRequest?.closingIssuesReferences.nodes ?? []) .filter((issue) => issue.repository.nameWithOwner.toLowerCase() === `${owner}/${repo}`.toLowerCase()) .map((issue) => ({ number: issue.number, author: issue.author?.login ?? null, assignees: issue.assignees.nodes.map((node) => node.login), })); } /** * Decides whether a PR opened before the rules started is exempt. Closed when * they started and open again now counts as opened under them. `edited` also * fires on closed PRs, so a PR that's still closed stays exempt. */ function exemptBefore(github, repoRef, start) { return async (item) => { if (start === null || new Date(item.created_at) >= start) { return false; } const events = await github.paginate(github.rest.issues.listEvents, { ...repoRef, issue_number: item.number, per_page: 100 }); const lastBefore = events .filter((event) => (event.event === "closed" || event.event === "reopened") && new Date(event.created_at) < start) .at(-1); return lastBefore?.event !== "closed" || item.state !== "open"; }; } /** Checks one PR and keeps its comment up to date. Returns the problems, or null when the PR is skipped. */ async function checkOne({ github, repoRef, core, pr, maintainers, exempt, openPrs, enforce }) { const author = pr.user.login; if (pr.user.type === "Bot") { core.info(`${author} is a bot, skipping.`); return null; } if (maintainers.some((login) => sameUser(login, author))) { core.info(`${author} is a maintainer, skipping.`); return null; } if (await exempt(pr)) { core.info(`#${pr.number} was opened before these rules took effect, skipping.`); return null; } const [issues, comments] = await Promise.all([ linkedIssues(github, repoRef, pr.number), github.paginate(github.rest.issues.listComments, { ...repoRef, issue_number: pr.number, per_page: 100 }), ]); // Only PRs opened before this one count, so the PR over the limit is flagged, not the older ones. // Exempt PRs from before the rules don't count either. const older = openPrs.filter((open) => open.number < pr.number && sameUser(open.user?.login, author)); const olderOpenPrs = (await Promise.all(older.map(exempt))).filter((isExempt) => !isExempt).length; const problems = checkPr({ author, linkedIssues: issues, olderOpenPrs }); const existing = comments.find((comment) => sameUser(comment.user?.login, BOT_LOGIN) && comment.body?.includes(MARKER)); const body = rulesComment({ author, problems, enforce }); if (existing) { if (existing.body !== body) { await github.rest.issues.updateComment({ ...repoRef, comment_id: existing.id, body }); } } else if (problems.length > 0) { await github.rest.issues.createComment({ ...repoRef, issue_number: pr.number, body }); } return problems; } export async function checkPullRequest({ github, context, core, maintainers, enforce = ENFORCE }) { const repoRef = context.repo; const pr = context.payload.pull_request; const maintainerList = maintainers ?? (await loadMaintainers(core)); const start = await prRulesStart(github, repoRef, context.payload.repository.default_branch); const openPrs = await github.paginate(github.rest.pulls.list, { ...repoRef, state: "open", per_page: 100 }); const exempt = exemptBefore(github, repoRef, start); const problems = await checkOne({ github, repoRef, core, pr, maintainers: maintainerList, exempt, openPrs, enforce }); if (problems === null) { return; } if (problems.length === 0) { core.info("All contribution rules met."); } else if (enforce) { core.setFailed(problems.join("\n")); } else { core.warning(problems.join("\n")); } } /** * Daily: checks every open PR into the default branch again. A PR only gets * checked on its own events, but its issue can change hands without one: the * claims bot releases a claim, or a maintainer unassigns someone. Without this, * the comment would still say the rules are met. * shortcut: this updates the comment, not the PR's check status, which changes on the PR's next push or edit. * Re-running the check here doesn't help: a re-run uses the base branch code from the original event. */ export async function sweepPullRequests({ github, context, core, maintainers, enforce = ENFORCE }) { const repoRef = context.repo; const maintainerList = maintainers ?? (await loadMaintainers(core)); const branch = (await github.rest.repos.get(repoRef)).data.default_branch; const start = await prRulesStart(github, repoRef, branch); const openPrs = await github.paginate(github.rest.pulls.list, { ...repoRef, state: "open", per_page: 100 }); const exempt = exemptBefore(github, repoRef, start); for (const pr of openPrs.filter((open) => open.base?.ref === branch)) { // One failing PR mustn't stop the rest. try { const problems = await checkOne({ github, repoRef, core, pr, maintainers: maintainerList, exempt, openPrs, enforce }); if (problems?.length) { core.info(`#${pr.number}: ${problems.join(" ")}`); } } catch (error) { core.warning(`#${pr.number}: ${error instanceof Error ? error.message : String(error)}`); } } }