From 5a5a73b9ccea64e0d49b798ff82e080dc4980d45 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 01/61] feat(dependabot-reminder): classify pull requests by owning team --- .github/scripts/dependabot-pr-reminder.mts | 78 ++++++++++++++++ .../tests/dependabot-pr-reminder.test.mts | 89 +++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 .github/scripts/dependabot-pr-reminder.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder.test.mts diff --git a/.github/scripts/dependabot-pr-reminder.mts b/.github/scripts/dependabot-pr-reminder.mts new file mode 100644 index 00000000..9c16d6e1 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder.mts @@ -0,0 +1,78 @@ +export type PullRequest = { + number: number; + title: string; + url: string; + requestedTeams: string[]; + hasApproval: boolean; + ciFailing: boolean; +}; + +export type Reminder = { + byTeam: Record; + fallback: { + failingCi: PullRequest[]; + readyToMerge: PullRequest[]; + needsOwner: PullRequest[]; + }; +}; + +/** + * Normalizes a team reference to a bare lowercase slug. + * + * @param team - The team, e.g. `@MetaMask/Core-Platform`. + * @returns The slug, e.g. `core-platform`. + */ +export function normalizeTeam(team: string): string { + return team + .trim() + .toLowerCase() + .replace(/^@/u, '') + .replace(/^metamask\//u, ''); +} + +/** + * Sorts pull requests into per-team groups and fallback buckets. + * + * Failing CI goes to the fallback bucket first, then PRs with remaining + * requested teams are grouped by team, then approved PRs are ready to merge, + * and anything else needs an owner. + * + * @param pullRequests - The open Dependabot pull requests. + * @param options - Classification options. + * @param options.ownerTeams - If set, only these teams are kept as owners. + * @param options.fallbackTeam - The team that handles the fallback buckets. + * @returns The classified reminder. + */ +export function classifyPullRequests( + pullRequests: PullRequest[], + options: { ownerTeams?: string[]; fallbackTeam: string }, +): Reminder { + const ownerTeams = options.ownerTeams?.map(normalizeTeam); + const reminder: Reminder = { + byTeam: {}, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }; + + for (const pullRequest of pullRequests) { + if (pullRequest.ciFailing) { + reminder.fallback.failingCi.push(pullRequest); + continue; + } + + const teams = pullRequest.requestedTeams + .map(normalizeTeam) + .filter((team) => !ownerTeams || ownerTeams.includes(team)); + + if (teams.length > 0) { + for (const team of new Set(teams)) { + (reminder.byTeam[team] ??= []).push(pullRequest); + } + } else if (pullRequest.hasApproval) { + reminder.fallback.readyToMerge.push(pullRequest); + } else { + reminder.fallback.needsOwner.push(pullRequest); + } + } + + return reminder; +} diff --git a/.github/scripts/tests/dependabot-pr-reminder.test.mts b/.github/scripts/tests/dependabot-pr-reminder.test.mts new file mode 100644 index 00000000..3601bd4a --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder.test.mts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + classifyPullRequests, + normalizeTeam, +} from '../dependabot-pr-reminder.mts'; +import type { PullRequest } from '../dependabot-pr-reminder.mts'; + +/** + * Builds a pull request for tests. + * + * @param overrides - Fields to override on the default pull request. + * @returns The pull request. + */ +function pr(overrides: Partial = {}): PullRequest { + return { + number: 1, + title: 'Bump foo from 1.0.0 to 1.0.1', + url: 'https://github.com/MetaMask/example/pull/1', + requestedTeams: [], + hasApproval: false, + ciFailing: false, + ...overrides, + }; +} + +describe('normalizeTeam', () => { + it('lowercases and strips the @ and metamask/ prefixes', () => { + assert.equal(normalizeTeam('@MetaMask/Core-Platform'), 'core-platform'); + }); +}); + +describe('classifyPullRequests', () => { + it('groups a PR under each remaining requested team', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.byTeam.a, [pullRequest]); + assert.deepEqual(result.byTeam.b, [pullRequest]); + }); + + it('lists failing CI PRs under fallback only', () => { + const pullRequest = pr({ ciFailing: true, requestedTeams: ['a'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.failingCi, [pullRequest]); + assert.deepEqual(result.byTeam, {}); + }); + + it('lists approved PRs with no teams left as ready to merge', () => { + const pullRequest = pr({ requestedTeams: [], hasApproval: true }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + }); + + it('lists PRs with no teams and no approval as needs owner', () => { + const pullRequest = pr(); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.needsOwner, [pullRequest]); + }); + + it('filters other teams out when ownerTeams is set', () => { + const pullRequest = pr({ requestedTeams: ['ui', 'extension-platform'] }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['extension-platform'], + fallbackTeam: 'f', + }); + assert.deepEqual(Object.keys(result.byTeam), ['extension-platform']); + assert.deepEqual(result.byTeam['extension-platform'], [pullRequest]); + }); + + it('lists approved PRs as ready to merge when ownerTeams leaves nothing', () => { + const pullRequest = pr({ requestedTeams: ['ui'], hasApproval: true }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['extension-platform'], + fallbackTeam: 'f', + }); + assert.deepEqual(result.byTeam, {}); + assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + }); + + it('normalizes team names before comparing and grouping', () => { + const pullRequest = pr({ requestedTeams: ['MetaMask/UI', 'Core'] }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['@metamask/core'], + fallbackTeam: 'f', + }); + assert.deepEqual(Object.keys(result.byTeam), ['core']); + }); +}); From a3731a0337c6fc61c06e143da9d4d95479ecea29 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 02/61] feat(dependabot-reminder): build Slack payload with topology team tags --- .github/scripts/dependabot-pr-reminder.mts | 113 ++++++++++++++++++ .../tests/dependabot-pr-reminder.test.mts | 97 ++++++++++++++- 2 files changed, 209 insertions(+), 1 deletion(-) diff --git a/.github/scripts/dependabot-pr-reminder.mts b/.github/scripts/dependabot-pr-reminder.mts index 9c16d6e1..813bd8f0 100644 --- a/.github/scripts/dependabot-pr-reminder.mts +++ b/.github/scripts/dependabot-pr-reminder.mts @@ -76,3 +76,116 @@ export function classifyPullRequests( return reminder; } + +export type Topology = Record< + string, + { githubHandle?: string; slackHandle?: { team?: string } } +>; + +/** + * Escapes characters that Slack mrkdwn treats as control characters. + * + * @param text - The raw text. + * @returns The escaped text. + */ +function escapeSlack(text: string): string { + return text + .replace(/&/gu, '&') + .replace(//gu, '>'); +} + +/** + * Formats pull requests as bulleted Slack links. + * + * @param pullRequests - The pull requests to list. + * @returns The bulleted lines. + */ +function formatPullRequests(pullRequests: PullRequest[]): string { + return pullRequests + .map( + ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, + ) + .join('\n'); +} + +/** + * Builds the Slack incoming webhook payload for a reminder. + * + * @param reminder - The classified reminder. + * @param topology - The team topology used to look up Slack user groups. + * @param options - Payload options. + * @param options.fallbackTeam - The team tagged on the fallback sections. + * @param options.repository - The repository name shown in the header. + * @returns The payload, or undefined when there is nothing to post. + */ +export function buildSlackPayload( + reminder: Reminder, + topology: Topology, + options: { fallbackTeam: string; repository: string }, +): + | { + text: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + link_names: boolean; + blocks: { type: string; text: { type: string; text: string } }[]; + } + | undefined { + const teamEntries = Object.entries(reminder.byTeam).filter( + ([, pullRequests]) => pullRequests.length > 0, + ); + const fallbackSections = [ + { label: 'Failing CI', pullRequests: reminder.fallback.failingCi }, + { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, + { label: 'Needs owner', pullRequests: reminder.fallback.needsOwner }, + ].filter(({ pullRequests }) => pullRequests.length > 0); + + if (teamEntries.length === 0 && fallbackSections.length === 0) { + return undefined; + } + + const tag = (team: string): string => { + const slug = normalizeTeam(team); + const entry = Object.values(topology).find( + ({ githubHandle }) => + githubHandle && normalizeTeam(githubHandle) === slug, + ); + const id = entry?.slackHandle?.team; + return id ? `` : slug; + }; + + const section = (text: string) => ({ + type: 'section', + text: { type: 'mrkdwn', text }, + }); + + const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; + const blocks = [section(headline)]; + const mentions = new Set(); + const mention = (team: string): string => { + const value = tag(team); + if (value.startsWith(' { assert.deepEqual(Object.keys(result.byTeam), ['core']); }); }); + +describe('buildSlackPayload', () => { + const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; + const emptyReminder = (): Reminder => ({ + byTeam: {}, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }); + const allText = (payload: { text: string; blocks: unknown[] }): string => + `${payload.text}\n${JSON.stringify(payload.blocks)}`; + + it('returns undefined for an empty reminder', () => { + assert.equal(buildSlackPayload(emptyReminder(), {}, options), undefined); + }); + + it('tags a team using slackHandle.team', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr({ number: 7 })]; + const payload = buildSlackPayload( + reminder, + { + 'core-platform': { + githubHandle: 'MetaMask/core-platform', + slackHandle: { team: 'S123' }, + }, + }, + options, + ); + assert.ok(payload); + assert.match(allText(payload), //u); + assert.match(allText(payload), /#7/u); + assert.match(payload.text, //u); + assert.doesNotMatch(allText(payload), /:dependabot:/u); + }); + + it('matches githubHandle regardless of case or @ prefix', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr()]; + const payload = buildSlackPayload( + reminder, + { + key: { + githubHandle: '@MetaMask/Core-Platform', + slackHandle: { team: 'S9' }, + }, + }, + options, + ); + assert.ok(payload); + assert.match(allText(payload), //u); + }); + + it('falls back to the plain team name when topology has no match', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr()]; + const payload = buildSlackPayload(reminder, {}, options); + assert.ok(payload); + assert.match(allText(payload), /core-platform/u); + assert.doesNotMatch(allText(payload), /subteam\^/u); + }); + + it('escapes &, <, > in PR titles', () => { + const reminder = emptyReminder(); + reminder.byTeam.a = [pr({ title: 'Bump & b > c' })]; + const payload = buildSlackPayload(reminder, {}, options); + assert.ok(payload); + assert.match(allText(payload), /Bump <a> & b > c/u); + }); + + it('renders fallback sections under the fallback team', () => { + const reminder = emptyReminder(); + reminder.fallback.failingCi = [pr({ number: 1 })]; + reminder.fallback.readyToMerge = [pr({ number: 2 })]; + reminder.fallback.needsOwner = [pr({ number: 3 })]; + const payload = buildSlackPayload( + reminder, + { + platform: { + githubHandle: 'MetaMask/platform', + slackHandle: { team: 'SF' }, + }, + }, + options, + ); + assert.ok(payload); + const text = allText(payload); + assert.match(text, //u); + assert.match(text, /[Ff]ailing CI/u); + assert.match(text, /[Rr]eady to merge/u); + assert.match(text, /[Nn]eeds owner/u); + assert.match(text, /#1/u); + assert.match(text, /#2/u); + assert.match(text, /#3/u); + }); +}); From c51d38ca3b022ac07e9d07218dbea7f49df62ca4 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 03/61] feat(dependabot-reminder): fetch Dependabot PRs and add CLI entry point --- .github/scripts/dependabot-pr-reminder.mts | 284 +++++++++++++++++- .../tests/dependabot-pr-reminder.test.mts | 148 ++++++++- 2 files changed, 416 insertions(+), 16 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder.mts b/.github/scripts/dependabot-pr-reminder.mts index 813bd8f0..0eefd16c 100644 --- a/.github/scripts/dependabot-pr-reminder.mts +++ b/.github/scripts/dependabot-pr-reminder.mts @@ -1,3 +1,13 @@ +import { execFile } from 'node:child_process'; +import { appendFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import { retry } from './shared/retry.mts'; + +const execFileAsync = promisify(execFile); + export type PullRequest = { number: number; title: string; @@ -96,17 +106,52 @@ function escapeSlack(text: string): string { } /** - * Formats pull requests as bulleted Slack links. + * The maximum characters of a section text we emit. Slack rejects 3000+. + */ +const MAX_SECTION_LENGTH = 2800; + +/** + * Formats pull requests as bulleted Slack links, one line each. * * @param pullRequests - The pull requests to list. * @returns The bulleted lines. */ -function formatPullRequests(pullRequests: PullRequest[]): string { - return pullRequests - .map( - ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, - ) - .join('\n'); +function formatPullRequestLines(pullRequests: PullRequest[]): string[] { + return pullRequests.map( + ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, + ); +} + +/** + * Splits a header and lines into section texts that fit Slack's limit. The + * header is repeated on every section. + * + * @param header - The header line. + * @param lines - The lines to list below the header. + * @returns One or more section texts. + */ +function chunkSections(header: string, lines: string[]): string[] { + const budget = Math.max(MAX_SECTION_LENGTH - header.length - 1, 1); + const texts: string[] = []; + let current: string[] = []; + let length = 0; + + for (const rawLine of lines) { + const line = + rawLine.length > budget ? `${rawLine.slice(0, budget - 1)}…` : rawLine; + const added = line.length + (current.length > 0 ? 1 : 0); + if (current.length > 0 && length + added > budget) { + texts.push(`${header}\n${current.join('\n')}`); + current = []; + length = 0; + } + length += line.length + (current.length > 0 ? 1 : 0); + current.push(line); + } + if (current.length > 0) { + texts.push(`${header}\n${current.join('\n')}`); + } + return texts; } /** @@ -170,16 +215,20 @@ export function buildSlackPayload( return value; }; for (const [team, pullRequests] of teamEntries) { - blocks.push( - section(`${mention(team)}\n${formatPullRequests(pullRequests)}`), - ); + for (const text of chunkSections( + mention(team), + formatPullRequestLines(pullRequests), + )) { + blocks.push(section(text)); + } } for (const { label, pullRequests } of fallbackSections) { - blocks.push( - section( - `${mention(options.fallbackTeam)} *${label}*\n${formatPullRequests(pullRequests)}`, - ), - ); + for (const text of chunkSections( + `${mention(options.fallbackTeam)} *${label}*`, + formatPullRequestLines(pullRequests), + )) { + blocks.push(section(text)); + } } return { @@ -189,3 +238,208 @@ export function buildSlackPayload( blocks, }; } + +export type GraphQlPullRequestNode = { + number: number; + title: string; + url: string; + isDraft: boolean; + author: { login: string } | null; + reviewRequests: { + nodes: { + // eslint-disable-next-line @typescript-eslint/naming-convention + requestedReviewer: { __typename: string; slug?: string } | null; + }[]; + }; + latestOpinionatedReviews: { nodes: { state: string }[] }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; +}; + +/** + * Maps a GraphQL pull request node to a PullRequest. + * + * @param node - The GraphQL node. + * @returns The pull request, or undefined for drafts and non-Dependabot PRs. + */ +export function toPullRequest( + node: GraphQlPullRequestNode, +): PullRequest | undefined { + if (node.isDraft || node.author?.login !== 'dependabot[bot]') { + return undefined; + } + + const rollupState = + node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; + + return { + number: node.number, + title: node.title, + url: node.url, + requestedTeams: node.reviewRequests.nodes.flatMap( + ({ requestedReviewer }) => + requestedReviewer?.__typename === 'Team' && requestedReviewer.slug + ? [requestedReviewer.slug] + : [], + ), + hasApproval: node.latestOpinionatedReviews.nodes.some( + ({ state }) => state === 'APPROVED', + ), + ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', + }; +} + +/** + * Parses the comma-separated OWNER_TEAMS value. + * + * @param value - The raw value. + * @returns The team list, or undefined when no teams are configured (so that + * no filtering is applied). + */ +export function parseOwnerTeams( + value: string | undefined, +): string[] | undefined { + const teams = (value ?? '') + .split(',') + .map((team) => team.trim()) + .filter(Boolean); + return teams.length > 0 ? teams : undefined; +} + +const PULL_REQUESTS_QUERY = ` +query($owner: String!, $name: String!, $endCursor: String) { + repository(owner: $owner, name: $name) { + pullRequests(states: OPEN, first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { + number + title + url + isDraft + author { login } + reviewRequests(first: 20) { + nodes { requestedReviewer { __typename ... on Team { slug } } } + } + latestOpinionatedReviews(first: 20) { nodes { state } } + commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } + } + } + } +}`; + +/** + * Runs `gh api`, retrying transient failures. + * + * @param argumentsList - Arguments after `gh api`. + * @param token - The token passed as GH_TOKEN, if different from the default. + * @param environment - The base environment. + * @returns The standard output. + */ +async function ghApi( + argumentsList: string[], + token: string | undefined, + environment: NodeJS.ProcessEnv, +): Promise { + return await retry( + async () => { + const { stdout } = await execFileAsync('gh', ['api', ...argumentsList], { + env: token ? { ...environment, GH_TOKEN: token } : environment, + maxBuffer: 100 * 1024 * 1024, + }); + return stdout; + }, + { maxAttempts: 3, delayMilliseconds: 2_000 }, + ); +} + +/** + * Fetches open Dependabot pull requests and writes the Slack payload. + * + * @param environment - The process environment. + */ +export async function main(environment: NodeJS.ProcessEnv): Promise { + const repository = environment.GITHUB_REPOSITORY; + const fallbackTeam = environment.FALLBACK_TEAM; + const planningToken = environment.PLANNING_TOKEN; + const outputPath = environment.GITHUB_OUTPUT; + if (!repository || !fallbackTeam || !planningToken || !outputPath) { + throw new Error( + 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', + ); + } + const [owner, name] = repository.split('/'); + if (!owner || !name) { + throw new Error('GITHUB_REPOSITORY must be in owner/name form'); + } + const ref = environment.TOPOLOGY_REF?.trim() + ? environment.TOPOLOGY_REF.trim() + : 'main'; + + const graphqlOutput = await ghApi( + [ + 'graphql', + '--paginate', + '--slurp', + '-f', + `query=${PULL_REQUESTS_QUERY}`, + '-F', + `owner=${owner}`, + '-F', + `name=${name}`, + ], + undefined, + environment, + ); + const pages = JSON.parse(graphqlOutput) as { + data: { repository: { pullRequests: { nodes: GraphQlPullRequestNode[] } } }; + }[]; + const pullRequests = pages + .flatMap((page) => page.data.repository.pullRequests.nodes) + .map(toPullRequest) + .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); + + const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); + const reminder = classifyPullRequests(pullRequests, { + ...(ownerTeams ? { ownerTeams } : {}), + fallbackTeam, + }); + + const topology = JSON.parse( + await ghApi( + [ + '-H', + 'Accept: application/vnd.github.raw', + `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${ref}`, + ], + planningToken, + environment, + ), + ) as Topology; + + const payload = buildSlackPayload(reminder, topology, { + fallbackTeam, + repository, + }); + + if (!payload) { + console.log('No open Dependabot pull requests to report.'); + appendFileSync(outputPath, 'has-prs=false\n'); + return; + } + + const payloadPath = join( + environment.RUNNER_TEMP ?? '.', + 'dependabot-reminder-payload.json', + ); + writeFileSync(payloadPath, JSON.stringify(payload)); + appendFileSync(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); + console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main(process.env).catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/.github/scripts/tests/dependabot-pr-reminder.test.mts b/.github/scripts/tests/dependabot-pr-reminder.test.mts index 13321e89..326624b9 100644 --- a/.github/scripts/tests/dependabot-pr-reminder.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder.test.mts @@ -5,8 +5,14 @@ import { buildSlackPayload, classifyPullRequests, normalizeTeam, + parseOwnerTeams, + toPullRequest, +} from '../dependabot-pr-reminder.mts'; +import type { + GraphQlPullRequestNode, + PullRequest, + Reminder, } from '../dependabot-pr-reminder.mts'; -import type { PullRequest, Reminder } from '../dependabot-pr-reminder.mts'; /** * Builds a pull request for tests. @@ -182,3 +188,143 @@ describe('buildSlackPayload', () => { assert.match(text, /#3/u); }); }); + +/** + * Builds a GraphQL node for tests. + * + * @param overrides - Fields to override. + * @returns The node. + */ +function node( + overrides: Partial = {}, +): GraphQlPullRequestNode { + return { + number: 7, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + isDraft: false, + author: { login: 'dependabot[bot]' }, + reviewRequests: { nodes: [] }, + latestOpinionatedReviews: { nodes: [] }, + commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, + ...overrides, + }; +} + +describe('toPullRequest', () => { + it('returns undefined for drafts', () => { + assert.equal(toPullRequest(node({ isDraft: true })), undefined); + }); + + it('returns undefined for non-Dependabot authors', () => { + assert.equal( + toPullRequest(node({ author: { login: 'someone-else' } })), + undefined, + ); + }); + + it('returns undefined when the author is missing', () => { + assert.equal(toPullRequest(node({ author: null })), undefined); + }); + + it('maps a Dependabot PR', () => { + assert.deepEqual(toPullRequest(node()), { + number: 7, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + requestedTeams: [], + hasApproval: false, + ciFailing: false, + }); + }); + + it('keeps Team reviewers and ignores Users', () => { + const result = toPullRequest( + node({ + reviewRequests: { + /* eslint-disable @typescript-eslint/naming-convention */ + nodes: [ + { requestedReviewer: { __typename: 'User' } }, + { requestedReviewer: { __typename: 'Team', slug: 'wallet' } }, + { requestedReviewer: null }, + ], + /* eslint-enable @typescript-eslint/naming-convention */ + }, + }), + ); + assert.deepEqual(result?.requestedTeams, ['wallet']); + }); + + it('sets hasApproval when any latest review is APPROVED', () => { + const result = toPullRequest( + node({ + latestOpinionatedReviews: { + nodes: [{ state: 'CHANGES_REQUESTED' }, { state: 'APPROVED' }], + }, + }), + ); + assert.equal(result?.hasApproval, true); + }); + + it('sets ciFailing only for FAILURE and ERROR', () => { + const rollup = (state: string | null) => + toPullRequest( + node({ + commits: { + nodes: [ + { commit: { statusCheckRollup: state ? { state } : null } }, + ], + }, + }), + )?.ciFailing; + assert.equal(rollup('FAILURE'), true); + assert.equal(rollup('ERROR'), true); + assert.equal(rollup('PENDING'), false); + assert.equal(rollup('SUCCESS'), false); + assert.equal(rollup(null), false); + }); +}); + +describe('parseOwnerTeams', () => { + it('returns undefined for undefined, empty, and whitespace input', () => { + assert.equal(parseOwnerTeams(undefined), undefined); + assert.equal(parseOwnerTeams(''), undefined); + assert.equal(parseOwnerTeams(' \n '), undefined); + assert.equal(parseOwnerTeams(' , ,'), undefined); + }); + + it('splits, trims, and drops empty entries', () => { + assert.deepEqual(parseOwnerTeams(' a, b ,,c '), ['a', 'b', 'c']); + }); +}); + +describe('buildSlackPayload chunking', () => { + it('splits a long team list into sections under the Slack limit', () => { + const pullRequests = Array.from({ length: 60 }, (_, index) => + pr({ + number: index + 1, + title: `Bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, + url: `https://github.com/MetaMask/example/pull/${index + 1}`, + }), + ); + const reminder: Reminder = { + byTeam: { wallet: pullRequests }, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }; + const payload = buildSlackPayload( + reminder, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + const texts = payload.blocks.map((block) => block.text.text); + assert.ok(texts.length > 3); + for (const text of texts) { + assert.ok(text.length <= 3000, `section has ${text.length} characters`); + } + const joined = texts.join('\n'); + for (const { number } of pullRequests) { + assert.ok(joined.includes(`#${number} `), `PR #${number} is missing`); + } + }); +}); From f21a1be91f6f4957cf0cafd931f137f949cc62d7 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 04/61] feat(dependabot-reminder): add composite action and reusable workflow --- .../actions/remind-dependabot-prs/action.yml | 53 +++++++++++++ .github/workflows/remind-dependabot-prs.yml | 78 +++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 .github/actions/remind-dependabot-prs/action.yml create mode 100644 .github/workflows/remind-dependabot-prs.yml diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml new file mode 100644 index 00000000..d41011c6 --- /dev/null +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -0,0 +1,53 @@ +name: Remind Dependabot PRs +description: 'Builds a Slack payload listing open Dependabot PRs grouped by owning team.' + +inputs: + github-token: + description: 'Token used to read pull request data from the invoking repository.' + required: true + planning-token: + description: 'Token with read access to MetaMask/MetaMask-planning (for topology.json).' + required: true + owner-teams: + description: 'Comma-separated list of team slugs that own the invoking repository. May be empty.' + required: false + default: '' + fallback-team: + description: 'Team slug used for PRs that cannot be attributed to a team.' + required: false + default: 'core-platform' + topology-ref: + description: 'Git ref of MetaMask-planning to read topology.json from.' + required: false + default: 'main' + +outputs: + has-prs: + description: '"true" when there are open Dependabot PRs to report, otherwise "false".' + value: ${{ steps.reminder.outputs.has-prs }} + payload-path: + description: 'Path to the JSON file containing the Slack payload.' + value: ${{ steps.reminder.outputs.payload-path }} + +runs: + using: composite + steps: + # The script is a .mts file, which requires Node 22+ to run directly. + - name: Set up Node + uses: actions/setup-node@v6 + with: + node-version: '24' + + - name: Build Dependabot PR reminder + id: reminder + shell: bash + env: + GITHUB_REPOSITORY: ${{ github.repository }} + GH_TOKEN: ${{ inputs.github-token }} + PLANNING_TOKEN: ${{ inputs.planning-token }} + OWNER_TEAMS: ${{ inputs.owner-teams }} + FALLBACK_TEAM: ${{ inputs.fallback-team }} + TOPOLOGY_REF: ${{ inputs.topology-ref }} + run: | + set -euo pipefail + node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder.mts" diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml new file mode 100644 index 00000000..4ec24957 --- /dev/null +++ b/.github/workflows/remind-dependabot-prs.yml @@ -0,0 +1,78 @@ +name: Remind Dependabot PRs + +# Note: the `@v1` references below only resolve after a github-tools release. +# Before release, smoke-test callers against a branch ref instead of `@v1`. + +on: + workflow_call: + inputs: + owner-teams: + required: false + type: string + default: '' + description: 'Comma-separated team slugs that own the calling repository' + fallback-team: + required: false + type: string + default: 'core-platform' + description: 'Team slug used for PRs that cannot be attributed to a team' + topology-ref: + required: false + type: string + default: 'main' + description: 'Git ref of MetaMask-planning to read topology.json from' + secrets: + slack-webhook-url: + required: true + description: 'Slack incoming webhook URL' + +jobs: + remind: + name: Remind Dependabot PRs + runs-on: ubuntu-latest + environment: default-branch + permissions: + contents: read + pull-requests: read + id-token: write + steps: + - name: Get planning token + id: planning-token + uses: MetaMask/github-tools/.github/actions/get-token@v1 + with: + token-exchange-url: ${{ vars.TOKEN_EXCHANGE_URL }} + target-repository: MetaMask/MetaMask-planning + permissions: | + contents: read + + - name: Build reminder + id: remind + uses: MetaMask/github-tools/.github/actions/remind-dependabot-prs@v1 + with: + github-token: ${{ github.token }} + planning-token: ${{ steps.planning-token.outputs.token }} + owner-teams: ${{ inputs.owner-teams }} + fallback-team: ${{ inputs.fallback-team }} + topology-ref: ${{ inputs.topology-ref }} + + - name: Read Slack payload + if: steps.remind.outputs.has-prs == 'true' + id: payload + shell: bash + env: + PAYLOAD_PATH: ${{ steps.remind.outputs.payload-path }} + run: | + { + echo "payload<> "$GITHUB_OUTPUT" + + - name: Send Slack notification + if: steps.remind.outputs.has-prs == 'true' + uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 + with: + webhook: ${{ secrets.slack-webhook-url }} + webhook-type: incoming-webhook + payload: ${{ steps.payload.outputs.payload }} From 0b14185d875f17e4ec0f28853531868e69f31359 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 05/61] docs: document the Dependabot PR reminder workflow --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/README.md b/README.md index 5418480e..d177d47b 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,72 @@ This repository holds a collection of scripts which are intended to be run local - `yarn segment-schema:draft-pr`: Local CLI for the Segment schema draft. See the [CLI](src/segment-schema-draft-pr/README.md) and the [action](.github/actions/draft-segment-schema-pr/README.md). +### Dependabot PR reminder + +The reusable workflow `.github/workflows/remind-dependabot-prs.yml` posts a Slack thread listing open Dependabot PRs, grouped by owning team. Team Slack tags come from `topology.json` in `MetaMask/MetaMask-planning`. Nothing is posted if no Dependabot PRs are open. Draft PRs are skipped. PRs with failing CI and PRs that are ready to merge are listed under the fallback team. + +| Input | Required | Default | Description | +| ------------------- | -------- | --------------- | ------------------------------------------------------------------------------------------- | +| `owner-teams` | No | | Comma-separated team slugs that own the repo. If unset, all requested-reviewer teams count. | +| `fallback-team` | No | `core-platform` | Team that gets PRs with no owning team, failing CI, or ready to merge. | +| `topology-ref` | No | `main` | Ref of `MetaMask/MetaMask-planning` to read `topology.json` from. | +| `slack-webhook-url` | Yes | | Secret. Each repo passes its own so it can post to its own channel. | + +Requirements for the calling repo: + +- The caller workflow must be named `remind-dependabot-prs.yml` (the token-exchange-service policy matches on the caller's workflow file name). +- The job permissions must include `id-token: write` and `pull-requests: read`. +- A `default-branch` environment must exist and allow the branch the cron runs on (`main`). +- The repository variable `TOKEN_EXCHANGE_URL` must be set. +- A token-exchange-service policy must let the caller read `MetaMask/MetaMask-planning` with `contents: read`. + +`@v1` resolves only after a release of this repository. + +Polyrepo (for example `metamask-extension`): + +```yaml +name: Remind Dependabot PRs + +on: + schedule: + - cron: '0 14 * * 1' + workflow_dispatch: + +jobs: + remind: + permissions: + contents: read + pull-requests: read + id-token: write + uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 + with: + owner-teams: extension-platform + fallback-team: extension-platform + secrets: + slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} +``` + +Monorepo (for example `core`), with no extra inputs: + +```yaml +name: Remind Dependabot PRs + +on: + schedule: + - cron: '0 14 * * 1' + workflow_dispatch: + +jobs: + remind: + permissions: + contents: read + pull-requests: read + id-token: write + uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 + secrets: + slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} +``` + ### Authentication Some scripts require a GitHub token in order to run fully. From f650a00eff6f76ae35e4fe7363c43481879b5432 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 06/61] fix(dependabot-reminder): match GraphQL bot author, read teams via REST, harden payload --- .github/scripts/dependabot-pr-reminder.mts | 124 +++++++++++---- .../tests/dependabot-pr-reminder.test.mts | 144 ++++++++++++++---- .github/workflows/remind-dependabot-prs.yml | 6 +- README.md | 12 +- 4 files changed, 219 insertions(+), 67 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder.mts b/.github/scripts/dependabot-pr-reminder.mts index 0eefd16c..f142f294 100644 --- a/.github/scripts/dependabot-pr-reminder.mts +++ b/.github/scripts/dependabot-pr-reminder.mts @@ -89,7 +89,7 @@ export function classifyPullRequests( export type Topology = Record< string, - { githubHandle?: string; slackHandle?: { team?: string } } + { githubHandle?: string; slackHandle?: { team?: string } } | null >; /** @@ -192,8 +192,9 @@ export function buildSlackPayload( const tag = (team: string): string => { const slug = normalizeTeam(team); const entry = Object.values(topology).find( - ({ githubHandle }) => - githubHandle && normalizeTeam(githubHandle) === slug, + (candidate) => + typeof candidate?.githubHandle === 'string' && + normalizeTeam(candidate.githubHandle) === slug, ); const id = entry?.slackHandle?.team; return id ? `` : slug; @@ -231,6 +232,19 @@ export function buildSlackPayload( } } + const maxBlocks = 50; + if (blocks.length > maxBlocks) { + const omitted = blocks.splice(maxBlocks - 1); + const omittedCount = omitted.reduce( + (total, block) => + total + + block.text.text.split('\n').filter((line) => line.startsWith('•')) + .length, + 0, + ); + blocks.push(section(`…and ${omittedCount} more pull request(s) not shown`)); + } + return { text: [headline, ...mentions].join(' '), // eslint-disable-next-line @typescript-eslint/naming-convention @@ -244,13 +258,8 @@ export type GraphQlPullRequestNode = { title: string; url: string; isDraft: boolean; - author: { login: string } | null; - reviewRequests: { - nodes: { - // eslint-disable-next-line @typescript-eslint/naming-convention - requestedReviewer: { __typename: string; slug?: string } | null; - }[]; - }; + // eslint-disable-next-line @typescript-eslint/naming-convention + author: { __typename: string; login: string } | null; latestOpinionatedReviews: { nodes: { state: string }[] }; commits: { nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; @@ -261,12 +270,21 @@ export type GraphQlPullRequestNode = { * Maps a GraphQL pull request node to a PullRequest. * * @param node - The GraphQL node. + * @param requestedTeams - The team slugs requested for review (from REST). * @returns The pull request, or undefined for drafts and non-Dependabot PRs. */ export function toPullRequest( node: GraphQlPullRequestNode, + requestedTeams: string[], ): PullRequest | undefined { - if (node.isDraft || node.author?.login !== 'dependabot[bot]') { + // GraphQL returns `dependabot` for the Bot actor; REST returns + // `dependabot[bot]`. Accept both, but only for Bot actors. + if ( + node.isDraft || + node.author?.__typename !== 'Bot' || + (node.author.login !== 'dependabot' && + node.author.login !== 'dependabot[bot]') + ) { return undefined; } @@ -277,19 +295,54 @@ export function toPullRequest( number: node.number, title: node.title, url: node.url, - requestedTeams: node.reviewRequests.nodes.flatMap( - ({ requestedReviewer }) => - requestedReviewer?.__typename === 'Team' && requestedReviewer.slug - ? [requestedReviewer.slug] - : [], - ), - hasApproval: node.latestOpinionatedReviews.nodes.some( - ({ state }) => state === 'APPROVED', - ), + requestedTeams, + hasApproval: + node.latestOpinionatedReviews.nodes.some( + ({ state }) => state === 'APPROVED', + ) && + !node.latestOpinionatedReviews.nodes.some( + ({ state }) => state === 'CHANGES_REQUESTED', + ), ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', }; } +/** + * Builds a map of PR number to requested team slugs from REST pull request + * pages. + * + * @param pages - The paginated REST responses. + * @returns The requested team slugs by PR number. + */ +export function collectRequestedTeams( + pages: { + number: number; + // eslint-disable-next-line @typescript-eslint/naming-convention + requested_teams?: { slug: string }[]; + }[][], +): Map { + const result = new Map(); + for (const restPullRequest of pages.flat()) { + if (restPullRequest.requested_teams) { + result.set( + restPullRequest.number, + restPullRequest.requested_teams.map(({ slug }) => slug), + ); + } + } + return result; +} + +/** + * Builds the REST path to read topology.json at a ref. + * + * @param ref - The git ref. + * @returns The `gh api` path. + */ +export function buildTopologyPath(ref: string): string { + return `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${encodeURIComponent(ref)}`; +} + /** * Parses the comma-separated OWNER_TEAMS value. * @@ -317,10 +370,7 @@ query($owner: String!, $name: String!, $endCursor: String) { title url isDraft - author { login } - reviewRequests(first: 20) { - nodes { requestedReviewer { __typename ... on Team { slug } } } - } + author { __typename login } latestOpinionatedReviews(first: 20) { nodes { state } } commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } } @@ -383,9 +433,9 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { '--slurp', '-f', `query=${PULL_REQUESTS_QUERY}`, - '-F', + '-f', `owner=${owner}`, - '-F', + '-f', `name=${name}`, ], undefined, @@ -394,9 +444,23 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { const pages = JSON.parse(graphqlOutput) as { data: { repository: { pullRequests: { nodes: GraphQlPullRequestNode[] } } }; }[]; + const restOutput = await ghApi( + [ + '--paginate', + '--slurp', + `repos/${owner}/${name}/pulls?state=open&per_page=100`, + ], + undefined, + environment, + ); + const requestedTeamsByNumber = collectRequestedTeams( + JSON.parse(restOutput) as Parameters[0], + ); const pullRequests = pages .flatMap((page) => page.data.repository.pullRequests.nodes) - .map(toPullRequest) + .map((node) => + toPullRequest(node, requestedTeamsByNumber.get(node.number) ?? []), + ) .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); @@ -407,11 +471,7 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { const topology = JSON.parse( await ghApi( - [ - '-H', - 'Accept: application/vnd.github.raw', - `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${ref}`, - ], + ['-H', 'Accept: application/vnd.github.raw', buildTopologyPath(ref)], planningToken, environment, ), diff --git a/.github/scripts/tests/dependabot-pr-reminder.test.mts b/.github/scripts/tests/dependabot-pr-reminder.test.mts index 326624b9..476258a5 100644 --- a/.github/scripts/tests/dependabot-pr-reminder.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder.test.mts @@ -3,7 +3,9 @@ import { describe, it } from 'node:test'; import { buildSlackPayload, + buildTopologyPath, classifyPullRequests, + collectRequestedTeams, normalizeTeam, parseOwnerTeams, toPullRequest, @@ -12,6 +14,7 @@ import type { GraphQlPullRequestNode, PullRequest, Reminder, + Topology, } from '../dependabot-pr-reminder.mts'; /** @@ -203,8 +206,8 @@ function node( title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', isDraft: false, - author: { login: 'dependabot[bot]' }, - reviewRequests: { nodes: [] }, + // eslint-disable-next-line @typescript-eslint/naming-convention + author: { __typename: 'Bot', login: 'dependabot' }, latestOpinionatedReviews: { nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, ...overrides, @@ -213,22 +216,48 @@ function node( describe('toPullRequest', () => { it('returns undefined for drafts', () => { - assert.equal(toPullRequest(node({ isDraft: true })), undefined); + assert.equal(toPullRequest(node({ isDraft: true }), []), undefined); }); it('returns undefined for non-Dependabot authors', () => { assert.equal( - toPullRequest(node({ author: { login: 'someone-else' } })), + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'Bot', login: 'someone-else' } }), + [], + ), + undefined, + ); + }); + + it('rejects a User named dependabot', () => { + assert.equal( + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'User', login: 'dependabot' } }), + [], + ), undefined, ); }); + it('accepts a Bot named dependabot[bot]', () => { + assert.equal( + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), + [], + )?.number, + 7, + ); + }); + it('returns undefined when the author is missing', () => { - assert.equal(toPullRequest(node({ author: null })), undefined); + assert.equal(toPullRequest(node({ author: null }), []), undefined); }); it('maps a Dependabot PR', () => { - assert.deepEqual(toPullRequest(node()), { + assert.deepEqual(toPullRequest(node(), []), { number: 7, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', @@ -238,32 +267,26 @@ describe('toPullRequest', () => { }); }); - it('keeps Team reviewers and ignores Users', () => { - const result = toPullRequest( - node({ - reviewRequests: { - /* eslint-disable @typescript-eslint/naming-convention */ - nodes: [ - { requestedReviewer: { __typename: 'User' } }, - { requestedReviewer: { __typename: 'Team', slug: 'wallet' } }, - { requestedReviewer: null }, - ], - /* eslint-enable @typescript-eslint/naming-convention */ - }, - }), - ); - assert.deepEqual(result?.requestedTeams, ['wallet']); + it('uses the given requested teams', () => { + assert.deepEqual(toPullRequest(node(), ['wallet'])?.requestedTeams, [ + 'wallet', + ]); }); - it('sets hasApproval when any latest review is APPROVED', () => { - const result = toPullRequest( - node({ - latestOpinionatedReviews: { - nodes: [{ state: 'CHANGES_REQUESTED' }, { state: 'APPROVED' }], - }, - }), - ); - assert.equal(result?.hasApproval, true); + it('sets hasApproval when approved and nothing requests changes', () => { + const result = (states: string[]) => + toPullRequest( + node({ + latestOpinionatedReviews: { + nodes: states.map((state) => ({ state })), + }, + }), + [], + )?.hasApproval; + assert.equal(result(['APPROVED']), true); + assert.equal(result(['APPROVED', 'CHANGES_REQUESTED']), false); + assert.equal(result(['CHANGES_REQUESTED']), false); + assert.equal(result([]), false); }); it('sets ciFailing only for FAILURE and ERROR', () => { @@ -276,6 +299,7 @@ describe('toPullRequest', () => { ], }, }), + [], )?.ciFailing; assert.equal(rollup('FAILURE'), true); assert.equal(rollup('ERROR'), true); @@ -328,3 +352,63 @@ describe('buildSlackPayload chunking', () => { } }); }); + +describe('buildSlackPayload limits and lookup', () => { + const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; + + it('caps blocks at 50 and appends an overflow line', () => { + const byTeam: Reminder['byTeam'] = {}; + for (let index = 0; index < 80; index++) { + byTeam[`team-${index}`] = [pr({ number: index + 1 })]; + } + const payload = buildSlackPayload( + { byTeam, fallback: { failingCi: [], readyToMerge: [], needsOwner: [] } }, + {}, + options, + ); + assert.ok(payload); + assert.ok(payload.blocks.length <= 50); + const last = payload.blocks[payload.blocks.length - 1]; + assert.match(last?.text.text ?? '', /…and \d+ more/u); + }); + + it('does not throw on null topology entries', () => { + const payload = buildSlackPayload( + { + byTeam: { a: [pr()] }, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }, + { + bad: null, + good: { githubHandle: 'MetaMask/a', slackHandle: { team: 'S1' } }, + } as unknown as Topology, + options, + ); + assert.match(payload?.text ?? '', //u); + }); +}); + +/* eslint-disable @typescript-eslint/naming-convention */ +describe('collectRequestedTeams', () => { + it('maps PR numbers to requested team slugs across pages', () => { + const map = collectRequestedTeams([ + [{ number: 1, requested_teams: [{ slug: 'a' }, { slug: 'b' }] }], + [{ number: 2, requested_teams: [] }, { number: 3 }], + ]); + assert.deepEqual(map.get(1), ['a', 'b']); + assert.deepEqual(map.get(2), []); + assert.equal(map.get(3), undefined); + assert.equal(map.get(4), undefined); + }); +}); + +/* eslint-enable @typescript-eslint/naming-convention */ + +describe('buildTopologyPath', () => { + it('encodes the ref', () => { + assert.equal( + buildTopologyPath('feat/a b#c'), + 'repos/MetaMask/MetaMask-planning/contents/topology.json?ref=feat%2Fa%20b%23c', + ); + }); +}); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 4ec24957..14c6e0b4 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -1,7 +1,9 @@ name: Remind Dependabot PRs # Note: the `@v1` references below only resolve after a github-tools release. -# Before release, smoke-test callers against a branch ref instead of `@v1`. +# Pointing a caller at a branch ref is not enough for a pre-release smoke test: +# this workflow also references `get-token@v1` and `remind-dependabot-prs@v1` +# internally, so temporarily edit those inner `uses:` refs to the branch ref. on: workflow_call: @@ -34,6 +36,8 @@ jobs: permissions: contents: read pull-requests: read + checks: read + statuses: read id-token: write steps: - name: Get planning token diff --git a/README.md b/README.md index d177d47b..bccf8a5d 100644 --- a/README.md +++ b/README.md @@ -15,24 +15,24 @@ This repository holds a collection of scripts which are intended to be run local ### Dependabot PR reminder -The reusable workflow `.github/workflows/remind-dependabot-prs.yml` posts a Slack thread listing open Dependabot PRs, grouped by owning team. Team Slack tags come from `topology.json` in `MetaMask/MetaMask-planning`. Nothing is posted if no Dependabot PRs are open. Draft PRs are skipped. PRs with failing CI and PRs that are ready to merge are listed under the fallback team. +The reusable workflow `.github/workflows/remind-dependabot-prs.yml` posts a Slack thread listing open Dependabot PRs, grouped by owning team. Team Slack tags come from `topology.json` in `MetaMask/MetaMask-planning`. Nothing is posted if no Dependabot PRs are open. Draft PRs are skipped. PRs with failing CI and PRs that are approved with no owning team left are listed under the fallback team. Owners are identified only by team review requests: if the org auto-assigns individual reviewers (not teams) via code owners or team settings, those PRs are reported under the fallback team as needing an owner. | Input | Required | Default | Description | | ------------------- | -------- | --------------- | ------------------------------------------------------------------------------------------- | | `owner-teams` | No | | Comma-separated team slugs that own the repo. If unset, all requested-reviewer teams count. | -| `fallback-team` | No | `core-platform` | Team that gets PRs with no owning team, failing CI, or ready to merge. | +| `fallback-team` | No | `core-platform` | Team that gets PRs with no owning team, failing CI, or approved with no owning team left. | | `topology-ref` | No | `main` | Ref of `MetaMask/MetaMask-planning` to read `topology.json` from. | | `slack-webhook-url` | Yes | | Secret. Each repo passes its own so it can post to its own channel. | Requirements for the calling repo: - The caller workflow must be named `remind-dependabot-prs.yml` (the token-exchange-service policy matches on the caller's workflow file name). -- The job permissions must include `id-token: write` and `pull-requests: read`. +- The job permissions must include `contents: read`, `pull-requests: read`, `checks: read`, `statuses: read` and `id-token: write`. - A `default-branch` environment must exist and allow the branch the cron runs on (`main`). - The repository variable `TOKEN_EXCHANGE_URL` must be set. - A token-exchange-service policy must let the caller read `MetaMask/MetaMask-planning` with `contents: read`. -`@v1` resolves only after a release of this repository. +`@v1` resolves only after a release of this repository. Pointing a caller at a branch ref is not enough for a pre-release smoke test, because the reusable workflow also references `MetaMask/github-tools/.github/actions/remind-dependabot-prs@v1` and `get-token@v1` internally; temporarily edit those inner `uses:` refs to the branch ref. Polyrepo (for example `metamask-extension`): @@ -49,6 +49,8 @@ jobs: permissions: contents: read pull-requests: read + checks: read + statuses: read id-token: write uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 with: @@ -73,6 +75,8 @@ jobs: permissions: contents: read pull-requests: read + checks: read + statuses: read id-token: write uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 secrets: From 3e8204625e99ff6632fa559a4d20842d785214d7 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 07/61] docs: shorten Dependabot reminder section in README --- README.md | 51 ++++++++------------------------------------------- 1 file changed, 8 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index bccf8a5d..f32d8058 100644 --- a/README.md +++ b/README.md @@ -15,30 +15,18 @@ This repository holds a collection of scripts which are intended to be run local ### Dependabot PR reminder -The reusable workflow `.github/workflows/remind-dependabot-prs.yml` posts a Slack thread listing open Dependabot PRs, grouped by owning team. Team Slack tags come from `topology.json` in `MetaMask/MetaMask-planning`. Nothing is posted if no Dependabot PRs are open. Draft PRs are skipped. PRs with failing CI and PRs that are approved with no owning team left are listed under the fallback team. Owners are identified only by team review requests: if the org auto-assigns individual reviewers (not teams) via code owners or team settings, those PRs are reported under the fallback team as needing an owner. +`.github/workflows/remind-dependabot-prs.yml` posts a Slack thread of open Dependabot PRs grouped by owning team. Owners are the teams still requested as reviewers; slack tags come from `MetaMask-planning/topology.json`. PRs with failing CI or no owning team are listed under `fallback-team`. Nothing is posted when no PRs are open. -| Input | Required | Default | Description | -| ------------------- | -------- | --------------- | ------------------------------------------------------------------------------------------- | -| `owner-teams` | No | | Comma-separated team slugs that own the repo. If unset, all requested-reviewer teams count. | -| `fallback-team` | No | `core-platform` | Team that gets PRs with no owning team, failing CI, or approved with no owning team left. | -| `topology-ref` | No | `main` | Ref of `MetaMask/MetaMask-planning` to read `topology.json` from. | -| `slack-webhook-url` | Yes | | Secret. Each repo passes its own so it can post to its own channel. | +| Input | Default | Description | +| ------------------- | --------------- | ---------------------------------------------------------------- | +| `owner-teams` | | Comma-separated team slugs that count as owners. Unset means all | +| `fallback-team` | `core-platform` | Team that gets PRs with no owner or failing CI | +| `topology-ref` | `main` | Ref of `MetaMask-planning` to read `topology.json` from | +| `slack-webhook-url` | | Required secret, one per repo and channel | -Requirements for the calling repo: - -- The caller workflow must be named `remind-dependabot-prs.yml` (the token-exchange-service policy matches on the caller's workflow file name). -- The job permissions must include `contents: read`, `pull-requests: read`, `checks: read`, `statuses: read` and `id-token: write`. -- A `default-branch` environment must exist and allow the branch the cron runs on (`main`). -- The repository variable `TOKEN_EXCHANGE_URL` must be set. -- A token-exchange-service policy must let the caller read `MetaMask/MetaMask-planning` with `contents: read`. - -`@v1` resolves only after a release of this repository. Pointing a caller at a branch ref is not enough for a pre-release smoke test, because the reusable workflow also references `MetaMask/github-tools/.github/actions/remind-dependabot-prs@v1` and `get-token@v1` internally; temporarily edit those inner `uses:` refs to the branch ref. - -Polyrepo (for example `metamask-extension`): +The caller must be named `remind-dependabot-prs.yml`, grant the permissions below, have a `default-branch` environment and a `TOKEN_EXCHANGE_URL` variable, and have a token-exchange-service policy allowing `contents: read` on `MetaMask/MetaMask-planning`. Example for `metamask-extension` (`core` omits `with`): ```yaml -name: Remind Dependabot PRs - on: schedule: - cron: '0 14 * * 1' @@ -60,29 +48,6 @@ jobs: slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} ``` -Monorepo (for example `core`), with no extra inputs: - -```yaml -name: Remind Dependabot PRs - -on: - schedule: - - cron: '0 14 * * 1' - workflow_dispatch: - -jobs: - remind: - permissions: - contents: read - pull-requests: read - checks: read - statuses: read - id-token: write - uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 - secrets: - slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} -``` - ### Authentication Some scripts require a GitHub token in order to run fully. From a06137a7d393b5f520e768604ebaa9c885108076 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 08/61] docs: fix capitalization in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f32d8058..e7b09580 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ This repository holds a collection of scripts which are intended to be run local ### Dependabot PR reminder -`.github/workflows/remind-dependabot-prs.yml` posts a Slack thread of open Dependabot PRs grouped by owning team. Owners are the teams still requested as reviewers; slack tags come from `MetaMask-planning/topology.json`. PRs with failing CI or no owning team are listed under `fallback-team`. Nothing is posted when no PRs are open. +`.github/workflows/remind-dependabot-prs.yml` posts a Slack thread of open Dependabot PRs grouped by owning team. Owners are the teams still requested as reviewers; Slack tags come from `MetaMask-planning/topology.json`. PRs with failing CI or no owning team are listed under `fallback-team`. Nothing is posted when no PRs are open. | Input | Default | Description | | ------------------- | --------------- | ---------------------------------------------------------------- | From 2e8e3fdd629d38101a8f665fd7cf06e9a5037511 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 3 Nov 2026 15:10:35 +0100 Subject: [PATCH 09/61] refactor: split Dependabot reminder script into domain modules --- .../actions/remind-dependabot-prs/action.yml | 2 +- .github/scripts/dependabot-pr-reminder.mts | 505 ------------------ .../dependabot-pr-reminder/classify.mts | 49 ++ .../scripts/dependabot-pr-reminder/cli.mts | 117 ++++ .../dependabot-pr-reminder/github-api.mts | 140 +++++ .../dependabot-pr-reminder/slack-payload.mts | 163 ++++++ .../scripts/dependabot-pr-reminder/teams.mts | 30 ++ .../scripts/dependabot-pr-reminder/types.mts | 22 + .../tests/dependabot-pr-reminder.test.mts | 414 -------------- .../dependabot-pr-reminder/classify.test.mts | 62 +++ .../tests/dependabot-pr-reminder/fixtures.mts | 19 + .../github-api.test.mts | 151 ++++++ .../slack-payload.test.mts | 169 ++++++ .../dependabot-pr-reminder/teams.test.mts | 26 + 14 files changed, 949 insertions(+), 920 deletions(-) delete mode 100644 .github/scripts/dependabot-pr-reminder.mts create mode 100644 .github/scripts/dependabot-pr-reminder/classify.mts create mode 100644 .github/scripts/dependabot-pr-reminder/cli.mts create mode 100644 .github/scripts/dependabot-pr-reminder/github-api.mts create mode 100644 .github/scripts/dependabot-pr-reminder/slack-payload.mts create mode 100644 .github/scripts/dependabot-pr-reminder/teams.mts create mode 100644 .github/scripts/dependabot-pr-reminder/types.mts delete mode 100644 .github/scripts/tests/dependabot-pr-reminder.test.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/classify.test.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/fixtures.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/github-api.test.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/teams.test.mts diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index d41011c6..15d0a995 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -50,4 +50,4 @@ runs: TOPOLOGY_REF: ${{ inputs.topology-ref }} run: | set -euo pipefail - node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder.mts" + node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" diff --git a/.github/scripts/dependabot-pr-reminder.mts b/.github/scripts/dependabot-pr-reminder.mts deleted file mode 100644 index f142f294..00000000 --- a/.github/scripts/dependabot-pr-reminder.mts +++ /dev/null @@ -1,505 +0,0 @@ -import { execFile } from 'node:child_process'; -import { appendFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { promisify } from 'node:util'; - -import { retry } from './shared/retry.mts'; - -const execFileAsync = promisify(execFile); - -export type PullRequest = { - number: number; - title: string; - url: string; - requestedTeams: string[]; - hasApproval: boolean; - ciFailing: boolean; -}; - -export type Reminder = { - byTeam: Record; - fallback: { - failingCi: PullRequest[]; - readyToMerge: PullRequest[]; - needsOwner: PullRequest[]; - }; -}; - -/** - * Normalizes a team reference to a bare lowercase slug. - * - * @param team - The team, e.g. `@MetaMask/Core-Platform`. - * @returns The slug, e.g. `core-platform`. - */ -export function normalizeTeam(team: string): string { - return team - .trim() - .toLowerCase() - .replace(/^@/u, '') - .replace(/^metamask\//u, ''); -} - -/** - * Sorts pull requests into per-team groups and fallback buckets. - * - * Failing CI goes to the fallback bucket first, then PRs with remaining - * requested teams are grouped by team, then approved PRs are ready to merge, - * and anything else needs an owner. - * - * @param pullRequests - The open Dependabot pull requests. - * @param options - Classification options. - * @param options.ownerTeams - If set, only these teams are kept as owners. - * @param options.fallbackTeam - The team that handles the fallback buckets. - * @returns The classified reminder. - */ -export function classifyPullRequests( - pullRequests: PullRequest[], - options: { ownerTeams?: string[]; fallbackTeam: string }, -): Reminder { - const ownerTeams = options.ownerTeams?.map(normalizeTeam); - const reminder: Reminder = { - byTeam: {}, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, - }; - - for (const pullRequest of pullRequests) { - if (pullRequest.ciFailing) { - reminder.fallback.failingCi.push(pullRequest); - continue; - } - - const teams = pullRequest.requestedTeams - .map(normalizeTeam) - .filter((team) => !ownerTeams || ownerTeams.includes(team)); - - if (teams.length > 0) { - for (const team of new Set(teams)) { - (reminder.byTeam[team] ??= []).push(pullRequest); - } - } else if (pullRequest.hasApproval) { - reminder.fallback.readyToMerge.push(pullRequest); - } else { - reminder.fallback.needsOwner.push(pullRequest); - } - } - - return reminder; -} - -export type Topology = Record< - string, - { githubHandle?: string; slackHandle?: { team?: string } } | null ->; - -/** - * Escapes characters that Slack mrkdwn treats as control characters. - * - * @param text - The raw text. - * @returns The escaped text. - */ -function escapeSlack(text: string): string { - return text - .replace(/&/gu, '&') - .replace(//gu, '>'); -} - -/** - * The maximum characters of a section text we emit. Slack rejects 3000+. - */ -const MAX_SECTION_LENGTH = 2800; - -/** - * Formats pull requests as bulleted Slack links, one line each. - * - * @param pullRequests - The pull requests to list. - * @returns The bulleted lines. - */ -function formatPullRequestLines(pullRequests: PullRequest[]): string[] { - return pullRequests.map( - ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, - ); -} - -/** - * Splits a header and lines into section texts that fit Slack's limit. The - * header is repeated on every section. - * - * @param header - The header line. - * @param lines - The lines to list below the header. - * @returns One or more section texts. - */ -function chunkSections(header: string, lines: string[]): string[] { - const budget = Math.max(MAX_SECTION_LENGTH - header.length - 1, 1); - const texts: string[] = []; - let current: string[] = []; - let length = 0; - - for (const rawLine of lines) { - const line = - rawLine.length > budget ? `${rawLine.slice(0, budget - 1)}…` : rawLine; - const added = line.length + (current.length > 0 ? 1 : 0); - if (current.length > 0 && length + added > budget) { - texts.push(`${header}\n${current.join('\n')}`); - current = []; - length = 0; - } - length += line.length + (current.length > 0 ? 1 : 0); - current.push(line); - } - if (current.length > 0) { - texts.push(`${header}\n${current.join('\n')}`); - } - return texts; -} - -/** - * Builds the Slack incoming webhook payload for a reminder. - * - * @param reminder - The classified reminder. - * @param topology - The team topology used to look up Slack user groups. - * @param options - Payload options. - * @param options.fallbackTeam - The team tagged on the fallback sections. - * @param options.repository - The repository name shown in the header. - * @returns The payload, or undefined when there is nothing to post. - */ -export function buildSlackPayload( - reminder: Reminder, - topology: Topology, - options: { fallbackTeam: string; repository: string }, -): - | { - text: string; - // eslint-disable-next-line @typescript-eslint/naming-convention - link_names: boolean; - blocks: { type: string; text: { type: string; text: string } }[]; - } - | undefined { - const teamEntries = Object.entries(reminder.byTeam).filter( - ([, pullRequests]) => pullRequests.length > 0, - ); - const fallbackSections = [ - { label: 'Failing CI', pullRequests: reminder.fallback.failingCi }, - { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, - { label: 'Needs owner', pullRequests: reminder.fallback.needsOwner }, - ].filter(({ pullRequests }) => pullRequests.length > 0); - - if (teamEntries.length === 0 && fallbackSections.length === 0) { - return undefined; - } - - const tag = (team: string): string => { - const slug = normalizeTeam(team); - const entry = Object.values(topology).find( - (candidate) => - typeof candidate?.githubHandle === 'string' && - normalizeTeam(candidate.githubHandle) === slug, - ); - const id = entry?.slackHandle?.team; - return id ? `` : slug; - }; - - const section = (text: string) => ({ - type: 'section', - text: { type: 'mrkdwn', text }, - }); - - const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; - const blocks = [section(headline)]; - const mentions = new Set(); - const mention = (team: string): string => { - const value = tag(team); - if (value.startsWith(' maxBlocks) { - const omitted = blocks.splice(maxBlocks - 1); - const omittedCount = omitted.reduce( - (total, block) => - total + - block.text.text.split('\n').filter((line) => line.startsWith('•')) - .length, - 0, - ); - blocks.push(section(`…and ${omittedCount} more pull request(s) not shown`)); - } - - return { - text: [headline, ...mentions].join(' '), - // eslint-disable-next-line @typescript-eslint/naming-convention - link_names: true, - blocks, - }; -} - -export type GraphQlPullRequestNode = { - number: number; - title: string; - url: string; - isDraft: boolean; - // eslint-disable-next-line @typescript-eslint/naming-convention - author: { __typename: string; login: string } | null; - latestOpinionatedReviews: { nodes: { state: string }[] }; - commits: { - nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; - }; -}; - -/** - * Maps a GraphQL pull request node to a PullRequest. - * - * @param node - The GraphQL node. - * @param requestedTeams - The team slugs requested for review (from REST). - * @returns The pull request, or undefined for drafts and non-Dependabot PRs. - */ -export function toPullRequest( - node: GraphQlPullRequestNode, - requestedTeams: string[], -): PullRequest | undefined { - // GraphQL returns `dependabot` for the Bot actor; REST returns - // `dependabot[bot]`. Accept both, but only for Bot actors. - if ( - node.isDraft || - node.author?.__typename !== 'Bot' || - (node.author.login !== 'dependabot' && - node.author.login !== 'dependabot[bot]') - ) { - return undefined; - } - - const rollupState = - node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; - - return { - number: node.number, - title: node.title, - url: node.url, - requestedTeams, - hasApproval: - node.latestOpinionatedReviews.nodes.some( - ({ state }) => state === 'APPROVED', - ) && - !node.latestOpinionatedReviews.nodes.some( - ({ state }) => state === 'CHANGES_REQUESTED', - ), - ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', - }; -} - -/** - * Builds a map of PR number to requested team slugs from REST pull request - * pages. - * - * @param pages - The paginated REST responses. - * @returns The requested team slugs by PR number. - */ -export function collectRequestedTeams( - pages: { - number: number; - // eslint-disable-next-line @typescript-eslint/naming-convention - requested_teams?: { slug: string }[]; - }[][], -): Map { - const result = new Map(); - for (const restPullRequest of pages.flat()) { - if (restPullRequest.requested_teams) { - result.set( - restPullRequest.number, - restPullRequest.requested_teams.map(({ slug }) => slug), - ); - } - } - return result; -} - -/** - * Builds the REST path to read topology.json at a ref. - * - * @param ref - The git ref. - * @returns The `gh api` path. - */ -export function buildTopologyPath(ref: string): string { - return `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${encodeURIComponent(ref)}`; -} - -/** - * Parses the comma-separated OWNER_TEAMS value. - * - * @param value - The raw value. - * @returns The team list, or undefined when no teams are configured (so that - * no filtering is applied). - */ -export function parseOwnerTeams( - value: string | undefined, -): string[] | undefined { - const teams = (value ?? '') - .split(',') - .map((team) => team.trim()) - .filter(Boolean); - return teams.length > 0 ? teams : undefined; -} - -const PULL_REQUESTS_QUERY = ` -query($owner: String!, $name: String!, $endCursor: String) { - repository(owner: $owner, name: $name) { - pullRequests(states: OPEN, first: 100, after: $endCursor) { - pageInfo { hasNextPage endCursor } - nodes { - number - title - url - isDraft - author { __typename login } - latestOpinionatedReviews(first: 20) { nodes { state } } - commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } - } - } - } -}`; - -/** - * Runs `gh api`, retrying transient failures. - * - * @param argumentsList - Arguments after `gh api`. - * @param token - The token passed as GH_TOKEN, if different from the default. - * @param environment - The base environment. - * @returns The standard output. - */ -async function ghApi( - argumentsList: string[], - token: string | undefined, - environment: NodeJS.ProcessEnv, -): Promise { - return await retry( - async () => { - const { stdout } = await execFileAsync('gh', ['api', ...argumentsList], { - env: token ? { ...environment, GH_TOKEN: token } : environment, - maxBuffer: 100 * 1024 * 1024, - }); - return stdout; - }, - { maxAttempts: 3, delayMilliseconds: 2_000 }, - ); -} - -/** - * Fetches open Dependabot pull requests and writes the Slack payload. - * - * @param environment - The process environment. - */ -export async function main(environment: NodeJS.ProcessEnv): Promise { - const repository = environment.GITHUB_REPOSITORY; - const fallbackTeam = environment.FALLBACK_TEAM; - const planningToken = environment.PLANNING_TOKEN; - const outputPath = environment.GITHUB_OUTPUT; - if (!repository || !fallbackTeam || !planningToken || !outputPath) { - throw new Error( - 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', - ); - } - const [owner, name] = repository.split('/'); - if (!owner || !name) { - throw new Error('GITHUB_REPOSITORY must be in owner/name form'); - } - const ref = environment.TOPOLOGY_REF?.trim() - ? environment.TOPOLOGY_REF.trim() - : 'main'; - - const graphqlOutput = await ghApi( - [ - 'graphql', - '--paginate', - '--slurp', - '-f', - `query=${PULL_REQUESTS_QUERY}`, - '-f', - `owner=${owner}`, - '-f', - `name=${name}`, - ], - undefined, - environment, - ); - const pages = JSON.parse(graphqlOutput) as { - data: { repository: { pullRequests: { nodes: GraphQlPullRequestNode[] } } }; - }[]; - const restOutput = await ghApi( - [ - '--paginate', - '--slurp', - `repos/${owner}/${name}/pulls?state=open&per_page=100`, - ], - undefined, - environment, - ); - const requestedTeamsByNumber = collectRequestedTeams( - JSON.parse(restOutput) as Parameters[0], - ); - const pullRequests = pages - .flatMap((page) => page.data.repository.pullRequests.nodes) - .map((node) => - toPullRequest(node, requestedTeamsByNumber.get(node.number) ?? []), - ) - .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); - - const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); - const reminder = classifyPullRequests(pullRequests, { - ...(ownerTeams ? { ownerTeams } : {}), - fallbackTeam, - }); - - const topology = JSON.parse( - await ghApi( - ['-H', 'Accept: application/vnd.github.raw', buildTopologyPath(ref)], - planningToken, - environment, - ), - ) as Topology; - - const payload = buildSlackPayload(reminder, topology, { - fallbackTeam, - repository, - }); - - if (!payload) { - console.log('No open Dependabot pull requests to report.'); - appendFileSync(outputPath, 'has-prs=false\n'); - return; - } - - const payloadPath = join( - environment.RUNNER_TEMP ?? '.', - 'dependabot-reminder-payload.json', - ); - writeFileSync(payloadPath, JSON.stringify(payload)); - appendFileSync(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); - console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); -} - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - main(process.env).catch((error: unknown) => { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; - }); -} diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts new file mode 100644 index 00000000..319b5c67 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -0,0 +1,49 @@ +import { normalizeTeam } from './teams.mts'; +import type { PullRequest, Reminder } from './types.mts'; + +/** + * Sorts pull requests into per-team groups and fallback buckets. + * + * Failing CI goes to the fallback bucket first, then PRs with remaining + * requested teams are grouped by team, then approved PRs are ready to merge, + * and anything else needs an owner. + * + * @param pullRequests - The open Dependabot pull requests. + * @param options - Classification options. + * @param options.ownerTeams - If set, only these teams are kept as owners. + * @param options.fallbackTeam - The team that handles the fallback buckets. + * @returns The classified reminder. + */ +export function classifyPullRequests( + pullRequests: PullRequest[], + options: { ownerTeams?: string[]; fallbackTeam: string }, +): Reminder { + const ownerTeams = options.ownerTeams?.map(normalizeTeam); + const reminder: Reminder = { + byTeam: {}, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }; + + for (const pullRequest of pullRequests) { + if (pullRequest.ciFailing) { + reminder.fallback.failingCi.push(pullRequest); + continue; + } + + const teams = pullRequest.requestedTeams + .map(normalizeTeam) + .filter((team) => !ownerTeams || ownerTeams.includes(team)); + + if (teams.length > 0) { + for (const team of new Set(teams)) { + (reminder.byTeam[team] ??= []).push(pullRequest); + } + } else if (pullRequest.hasApproval) { + reminder.fallback.readyToMerge.push(pullRequest); + } else { + reminder.fallback.needsOwner.push(pullRequest); + } + } + + return reminder; +} diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts new file mode 100644 index 00000000..f57ac4fc --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -0,0 +1,117 @@ +import { appendFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { classifyPullRequests } from './classify.mts'; +import { + PULL_REQUESTS_QUERY, + buildTopologyPath, + collectRequestedTeams, + ghApi, + toPullRequest, +} from './github-api.mts'; +import type { GraphQlPullRequestNode } from './github-api.mts'; +import { buildSlackPayload } from './slack-payload.mts'; +import { parseOwnerTeams } from './teams.mts'; +import type { PullRequest, Topology } from './types.mts'; + +/** + * Fetches open Dependabot pull requests and writes the Slack payload. + * + * @param environment - The process environment. + */ +export async function main(environment: NodeJS.ProcessEnv): Promise { + const repository = environment.GITHUB_REPOSITORY; + const fallbackTeam = environment.FALLBACK_TEAM; + const planningToken = environment.PLANNING_TOKEN; + const outputPath = environment.GITHUB_OUTPUT; + if (!repository || !fallbackTeam || !planningToken || !outputPath) { + throw new Error( + 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', + ); + } + const [owner, name] = repository.split('/'); + if (!owner || !name) { + throw new Error('GITHUB_REPOSITORY must be in owner/name form'); + } + const ref = environment.TOPOLOGY_REF?.trim() + ? environment.TOPOLOGY_REF.trim() + : 'main'; + + const graphqlOutput = await ghApi( + [ + 'graphql', + '--paginate', + '--slurp', + '-f', + `query=${PULL_REQUESTS_QUERY}`, + '-f', + `owner=${owner}`, + '-f', + `name=${name}`, + ], + undefined, + environment, + ); + const pages = JSON.parse(graphqlOutput) as { + data: { repository: { pullRequests: { nodes: GraphQlPullRequestNode[] } } }; + }[]; + const restOutput = await ghApi( + [ + '--paginate', + '--slurp', + `repos/${owner}/${name}/pulls?state=open&per_page=100`, + ], + undefined, + environment, + ); + const requestedTeamsByNumber = collectRequestedTeams( + JSON.parse(restOutput) as Parameters[0], + ); + const pullRequests = pages + .flatMap((page) => page.data.repository.pullRequests.nodes) + .map((node) => + toPullRequest(node, requestedTeamsByNumber.get(node.number) ?? []), + ) + .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); + + const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); + const reminder = classifyPullRequests(pullRequests, { + ...(ownerTeams ? { ownerTeams } : {}), + fallbackTeam, + }); + + const topology = JSON.parse( + await ghApi( + ['-H', 'Accept: application/vnd.github.raw', buildTopologyPath(ref)], + planningToken, + environment, + ), + ) as Topology; + + const payload = buildSlackPayload(reminder, topology, { + fallbackTeam, + repository, + }); + + if (!payload) { + console.log('No open Dependabot pull requests to report.'); + appendFileSync(outputPath, 'has-prs=false\n'); + return; + } + + const payloadPath = join( + environment.RUNNER_TEMP ?? '.', + 'dependabot-reminder-payload.json', + ); + writeFileSync(payloadPath, JSON.stringify(payload)); + appendFileSync(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); + console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main(process.env).catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts new file mode 100644 index 00000000..277a17ee --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -0,0 +1,140 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +import type { PullRequest } from './types.mts'; +import { retry } from '../shared/retry.mts'; + +const execFileAsync = promisify(execFile); + +export type GraphQlPullRequestNode = { + number: number; + title: string; + url: string; + isDraft: boolean; + // eslint-disable-next-line @typescript-eslint/naming-convention + author: { __typename: string; login: string } | null; + latestOpinionatedReviews: { nodes: { state: string }[] }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; +}; + +/** + * Maps a GraphQL pull request node to a PullRequest. + * + * @param node - The GraphQL node. + * @param requestedTeams - The team slugs requested for review (from REST). + * @returns The pull request, or undefined for drafts and non-Dependabot PRs. + */ +export function toPullRequest( + node: GraphQlPullRequestNode, + requestedTeams: string[], +): PullRequest | undefined { + // GraphQL returns `dependabot` for the Bot actor; REST returns + // `dependabot[bot]`. Accept both, but only for Bot actors. + if ( + node.isDraft || + node.author?.__typename !== 'Bot' || + (node.author.login !== 'dependabot' && + node.author.login !== 'dependabot[bot]') + ) { + return undefined; + } + + const rollupState = + node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; + + return { + number: node.number, + title: node.title, + url: node.url, + requestedTeams, + hasApproval: + node.latestOpinionatedReviews.nodes.some( + ({ state }) => state === 'APPROVED', + ) && + !node.latestOpinionatedReviews.nodes.some( + ({ state }) => state === 'CHANGES_REQUESTED', + ), + ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', + }; +} + +/** + * Builds a map of PR number to requested team slugs from REST pull request + * pages. + * + * @param pages - The paginated REST responses. + * @returns The requested team slugs by PR number. + */ +export function collectRequestedTeams( + pages: { + number: number; + // eslint-disable-next-line @typescript-eslint/naming-convention + requested_teams?: { slug: string }[]; + }[][], +): Map { + const result = new Map(); + for (const restPullRequest of pages.flat()) { + if (restPullRequest.requested_teams) { + result.set( + restPullRequest.number, + restPullRequest.requested_teams.map(({ slug }) => slug), + ); + } + } + return result; +} + +/** + * Builds the REST path to read topology.json at a ref. + * + * @param ref - The git ref. + * @returns The `gh api` path. + */ +export function buildTopologyPath(ref: string): string { + return `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${encodeURIComponent(ref)}`; +} + +export const PULL_REQUESTS_QUERY = ` +query($owner: String!, $name: String!, $endCursor: String) { + repository(owner: $owner, name: $name) { + pullRequests(states: OPEN, first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { + number + title + url + isDraft + author { __typename login } + latestOpinionatedReviews(first: 20) { nodes { state } } + commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } + } + } + } +}`; + +/** + * Runs `gh api`, retrying transient failures. + * + * @param argumentsList - Arguments after `gh api`. + * @param token - The token passed as GH_TOKEN, if different from the default. + * @param environment - The base environment. + * @returns The standard output. + */ +export async function ghApi( + argumentsList: string[], + token: string | undefined, + environment: NodeJS.ProcessEnv, +): Promise { + return await retry( + async () => { + const { stdout } = await execFileAsync('gh', ['api', ...argumentsList], { + env: token ? { ...environment, GH_TOKEN: token } : environment, + maxBuffer: 100 * 1024 * 1024, + }); + return stdout; + }, + { maxAttempts: 3, delayMilliseconds: 2_000 }, + ); +} diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts new file mode 100644 index 00000000..203afed1 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -0,0 +1,163 @@ +import { normalizeTeam } from './teams.mts'; +import type { PullRequest, Reminder, Topology } from './types.mts'; + +/** + * Escapes characters that Slack mrkdwn treats as control characters. + * + * @param text - The raw text. + * @returns The escaped text. + */ +function escapeSlack(text: string): string { + return text + .replace(/&/gu, '&') + .replace(//gu, '>'); +} + +/** + * The maximum characters of a section text we emit. Slack rejects 3000+. + */ +const MAX_SECTION_LENGTH = 2800; + +/** + * Formats pull requests as bulleted Slack links, one line each. + * + * @param pullRequests - The pull requests to list. + * @returns The bulleted lines. + */ +function formatPullRequestLines(pullRequests: PullRequest[]): string[] { + return pullRequests.map( + ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, + ); +} + +/** + * Splits a header and lines into section texts that fit Slack's limit. The + * header is repeated on every section. + * + * @param header - The header line. + * @param lines - The lines to list below the header. + * @returns One or more section texts. + */ +function chunkSections(header: string, lines: string[]): string[] { + const budget = Math.max(MAX_SECTION_LENGTH - header.length - 1, 1); + const texts: string[] = []; + let current: string[] = []; + let length = 0; + + for (const rawLine of lines) { + const line = + rawLine.length > budget ? `${rawLine.slice(0, budget - 1)}…` : rawLine; + const added = line.length + (current.length > 0 ? 1 : 0); + if (current.length > 0 && length + added > budget) { + texts.push(`${header}\n${current.join('\n')}`); + current = []; + length = 0; + } + length += line.length + (current.length > 0 ? 1 : 0); + current.push(line); + } + if (current.length > 0) { + texts.push(`${header}\n${current.join('\n')}`); + } + return texts; +} + +/** + * Builds the Slack incoming webhook payload for a reminder. + * + * @param reminder - The classified reminder. + * @param topology - The team topology used to look up Slack user groups. + * @param options - Payload options. + * @param options.fallbackTeam - The team tagged on the fallback sections. + * @param options.repository - The repository name shown in the header. + * @returns The payload, or undefined when there is nothing to post. + */ +export function buildSlackPayload( + reminder: Reminder, + topology: Topology, + options: { fallbackTeam: string; repository: string }, +): + | { + text: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + link_names: boolean; + blocks: { type: string; text: { type: string; text: string } }[]; + } + | undefined { + const teamEntries = Object.entries(reminder.byTeam).filter( + ([, pullRequests]) => pullRequests.length > 0, + ); + const fallbackSections = [ + { label: 'Failing CI', pullRequests: reminder.fallback.failingCi }, + { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, + { label: 'Needs owner', pullRequests: reminder.fallback.needsOwner }, + ].filter(({ pullRequests }) => pullRequests.length > 0); + + if (teamEntries.length === 0 && fallbackSections.length === 0) { + return undefined; + } + + const tag = (team: string): string => { + const slug = normalizeTeam(team); + const entry = Object.values(topology).find( + (candidate) => + typeof candidate?.githubHandle === 'string' && + normalizeTeam(candidate.githubHandle) === slug, + ); + const id = entry?.slackHandle?.team; + return id ? `` : slug; + }; + + const section = (text: string) => ({ + type: 'section', + text: { type: 'mrkdwn', text }, + }); + + const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; + const blocks = [section(headline)]; + const mentions = new Set(); + const mention = (team: string): string => { + const value = tag(team); + if (value.startsWith(' maxBlocks) { + const omitted = blocks.splice(maxBlocks - 1); + const omittedCount = omitted.reduce( + (total, block) => + total + + block.text.text.split('\n').filter((line) => line.startsWith('•')) + .length, + 0, + ); + blocks.push(section(`…and ${omittedCount} more pull request(s) not shown`)); + } + + return { + text: [headline, ...mentions].join(' '), + // eslint-disable-next-line @typescript-eslint/naming-convention + link_names: true, + blocks, + }; +} diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts new file mode 100644 index 00000000..4b923d90 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -0,0 +1,30 @@ +/** + * Normalizes a team reference to a bare lowercase slug. + * + * @param team - The team, e.g. `@MetaMask/Core-Platform`. + * @returns The slug, e.g. `core-platform`. + */ +export function normalizeTeam(team: string): string { + return team + .trim() + .toLowerCase() + .replace(/^@/u, '') + .replace(/^metamask\//u, ''); +} + +/** + * Parses the comma-separated OWNER_TEAMS value. + * + * @param value - The raw value. + * @returns The team list, or undefined when no teams are configured (so that + * no filtering is applied). + */ +export function parseOwnerTeams( + value: string | undefined, +): string[] | undefined { + const teams = (value ?? '') + .split(',') + .map((team) => team.trim()) + .filter(Boolean); + return teams.length > 0 ? teams : undefined; +} diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts new file mode 100644 index 00000000..58e3d12f --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -0,0 +1,22 @@ +export type PullRequest = { + number: number; + title: string; + url: string; + requestedTeams: string[]; + hasApproval: boolean; + ciFailing: boolean; +}; + +export type Reminder = { + byTeam: Record; + fallback: { + failingCi: PullRequest[]; + readyToMerge: PullRequest[]; + needsOwner: PullRequest[]; + }; +}; + +export type Topology = Record< + string, + { githubHandle?: string; slackHandle?: { team?: string } } | null +>; diff --git a/.github/scripts/tests/dependabot-pr-reminder.test.mts b/.github/scripts/tests/dependabot-pr-reminder.test.mts deleted file mode 100644 index 476258a5..00000000 --- a/.github/scripts/tests/dependabot-pr-reminder.test.mts +++ /dev/null @@ -1,414 +0,0 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; - -import { - buildSlackPayload, - buildTopologyPath, - classifyPullRequests, - collectRequestedTeams, - normalizeTeam, - parseOwnerTeams, - toPullRequest, -} from '../dependabot-pr-reminder.mts'; -import type { - GraphQlPullRequestNode, - PullRequest, - Reminder, - Topology, -} from '../dependabot-pr-reminder.mts'; - -/** - * Builds a pull request for tests. - * - * @param overrides - Fields to override on the default pull request. - * @returns The pull request. - */ -function pr(overrides: Partial = {}): PullRequest { - return { - number: 1, - title: 'Bump foo from 1.0.0 to 1.0.1', - url: 'https://github.com/MetaMask/example/pull/1', - requestedTeams: [], - hasApproval: false, - ciFailing: false, - ...overrides, - }; -} - -describe('normalizeTeam', () => { - it('lowercases and strips the @ and metamask/ prefixes', () => { - assert.equal(normalizeTeam('@MetaMask/Core-Platform'), 'core-platform'); - }); -}); - -describe('classifyPullRequests', () => { - it('groups a PR under each remaining requested team', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.byTeam.a, [pullRequest]); - assert.deepEqual(result.byTeam.b, [pullRequest]); - }); - - it('lists failing CI PRs under fallback only', () => { - const pullRequest = pr({ ciFailing: true, requestedTeams: ['a'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.failingCi, [pullRequest]); - assert.deepEqual(result.byTeam, {}); - }); - - it('lists approved PRs with no teams left as ready to merge', () => { - const pullRequest = pr({ requestedTeams: [], hasApproval: true }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); - }); - - it('lists PRs with no teams and no approval as needs owner', () => { - const pullRequest = pr(); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.needsOwner, [pullRequest]); - }); - - it('filters other teams out when ownerTeams is set', () => { - const pullRequest = pr({ requestedTeams: ['ui', 'extension-platform'] }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['extension-platform'], - fallbackTeam: 'f', - }); - assert.deepEqual(Object.keys(result.byTeam), ['extension-platform']); - assert.deepEqual(result.byTeam['extension-platform'], [pullRequest]); - }); - - it('lists approved PRs as ready to merge when ownerTeams leaves nothing', () => { - const pullRequest = pr({ requestedTeams: ['ui'], hasApproval: true }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['extension-platform'], - fallbackTeam: 'f', - }); - assert.deepEqual(result.byTeam, {}); - assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); - }); - - it('normalizes team names before comparing and grouping', () => { - const pullRequest = pr({ requestedTeams: ['MetaMask/UI', 'Core'] }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['@metamask/core'], - fallbackTeam: 'f', - }); - assert.deepEqual(Object.keys(result.byTeam), ['core']); - }); -}); - -describe('buildSlackPayload', () => { - const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; - const emptyReminder = (): Reminder => ({ - byTeam: {}, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, - }); - const allText = (payload: { text: string; blocks: unknown[] }): string => - `${payload.text}\n${JSON.stringify(payload.blocks)}`; - - it('returns undefined for an empty reminder', () => { - assert.equal(buildSlackPayload(emptyReminder(), {}, options), undefined); - }); - - it('tags a team using slackHandle.team', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr({ number: 7 })]; - const payload = buildSlackPayload( - reminder, - { - 'core-platform': { - githubHandle: 'MetaMask/core-platform', - slackHandle: { team: 'S123' }, - }, - }, - options, - ); - assert.ok(payload); - assert.match(allText(payload), //u); - assert.match(allText(payload), /#7/u); - assert.match(payload.text, //u); - assert.doesNotMatch(allText(payload), /:dependabot:/u); - }); - - it('matches githubHandle regardless of case or @ prefix', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr()]; - const payload = buildSlackPayload( - reminder, - { - key: { - githubHandle: '@MetaMask/Core-Platform', - slackHandle: { team: 'S9' }, - }, - }, - options, - ); - assert.ok(payload); - assert.match(allText(payload), //u); - }); - - it('falls back to the plain team name when topology has no match', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr()]; - const payload = buildSlackPayload(reminder, {}, options); - assert.ok(payload); - assert.match(allText(payload), /core-platform/u); - assert.doesNotMatch(allText(payload), /subteam\^/u); - }); - - it('escapes &, <, > in PR titles', () => { - const reminder = emptyReminder(); - reminder.byTeam.a = [pr({ title: 'Bump & b > c' })]; - const payload = buildSlackPayload(reminder, {}, options); - assert.ok(payload); - assert.match(allText(payload), /Bump <a> & b > c/u); - }); - - it('renders fallback sections under the fallback team', () => { - const reminder = emptyReminder(); - reminder.fallback.failingCi = [pr({ number: 1 })]; - reminder.fallback.readyToMerge = [pr({ number: 2 })]; - reminder.fallback.needsOwner = [pr({ number: 3 })]; - const payload = buildSlackPayload( - reminder, - { - platform: { - githubHandle: 'MetaMask/platform', - slackHandle: { team: 'SF' }, - }, - }, - options, - ); - assert.ok(payload); - const text = allText(payload); - assert.match(text, //u); - assert.match(text, /[Ff]ailing CI/u); - assert.match(text, /[Rr]eady to merge/u); - assert.match(text, /[Nn]eeds owner/u); - assert.match(text, /#1/u); - assert.match(text, /#2/u); - assert.match(text, /#3/u); - }); -}); - -/** - * Builds a GraphQL node for tests. - * - * @param overrides - Fields to override. - * @returns The node. - */ -function node( - overrides: Partial = {}, -): GraphQlPullRequestNode { - return { - number: 7, - title: 'Bump foo', - url: 'https://github.com/MetaMask/example/pull/7', - isDraft: false, - // eslint-disable-next-line @typescript-eslint/naming-convention - author: { __typename: 'Bot', login: 'dependabot' }, - latestOpinionatedReviews: { nodes: [] }, - commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, - ...overrides, - }; -} - -describe('toPullRequest', () => { - it('returns undefined for drafts', () => { - assert.equal(toPullRequest(node({ isDraft: true }), []), undefined); - }); - - it('returns undefined for non-Dependabot authors', () => { - assert.equal( - toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention - node({ author: { __typename: 'Bot', login: 'someone-else' } }), - [], - ), - undefined, - ); - }); - - it('rejects a User named dependabot', () => { - assert.equal( - toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention - node({ author: { __typename: 'User', login: 'dependabot' } }), - [], - ), - undefined, - ); - }); - - it('accepts a Bot named dependabot[bot]', () => { - assert.equal( - toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention - node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), - [], - )?.number, - 7, - ); - }); - - it('returns undefined when the author is missing', () => { - assert.equal(toPullRequest(node({ author: null }), []), undefined); - }); - - it('maps a Dependabot PR', () => { - assert.deepEqual(toPullRequest(node(), []), { - number: 7, - title: 'Bump foo', - url: 'https://github.com/MetaMask/example/pull/7', - requestedTeams: [], - hasApproval: false, - ciFailing: false, - }); - }); - - it('uses the given requested teams', () => { - assert.deepEqual(toPullRequest(node(), ['wallet'])?.requestedTeams, [ - 'wallet', - ]); - }); - - it('sets hasApproval when approved and nothing requests changes', () => { - const result = (states: string[]) => - toPullRequest( - node({ - latestOpinionatedReviews: { - nodes: states.map((state) => ({ state })), - }, - }), - [], - )?.hasApproval; - assert.equal(result(['APPROVED']), true); - assert.equal(result(['APPROVED', 'CHANGES_REQUESTED']), false); - assert.equal(result(['CHANGES_REQUESTED']), false); - assert.equal(result([]), false); - }); - - it('sets ciFailing only for FAILURE and ERROR', () => { - const rollup = (state: string | null) => - toPullRequest( - node({ - commits: { - nodes: [ - { commit: { statusCheckRollup: state ? { state } : null } }, - ], - }, - }), - [], - )?.ciFailing; - assert.equal(rollup('FAILURE'), true); - assert.equal(rollup('ERROR'), true); - assert.equal(rollup('PENDING'), false); - assert.equal(rollup('SUCCESS'), false); - assert.equal(rollup(null), false); - }); -}); - -describe('parseOwnerTeams', () => { - it('returns undefined for undefined, empty, and whitespace input', () => { - assert.equal(parseOwnerTeams(undefined), undefined); - assert.equal(parseOwnerTeams(''), undefined); - assert.equal(parseOwnerTeams(' \n '), undefined); - assert.equal(parseOwnerTeams(' , ,'), undefined); - }); - - it('splits, trims, and drops empty entries', () => { - assert.deepEqual(parseOwnerTeams(' a, b ,,c '), ['a', 'b', 'c']); - }); -}); - -describe('buildSlackPayload chunking', () => { - it('splits a long team list into sections under the Slack limit', () => { - const pullRequests = Array.from({ length: 60 }, (_, index) => - pr({ - number: index + 1, - title: `Bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, - url: `https://github.com/MetaMask/example/pull/${index + 1}`, - }), - ); - const reminder: Reminder = { - byTeam: { wallet: pullRequests }, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, - }; - const payload = buildSlackPayload( - reminder, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, - ); - assert.ok(payload); - const texts = payload.blocks.map((block) => block.text.text); - assert.ok(texts.length > 3); - for (const text of texts) { - assert.ok(text.length <= 3000, `section has ${text.length} characters`); - } - const joined = texts.join('\n'); - for (const { number } of pullRequests) { - assert.ok(joined.includes(`#${number} `), `PR #${number} is missing`); - } - }); -}); - -describe('buildSlackPayload limits and lookup', () => { - const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - - it('caps blocks at 50 and appends an overflow line', () => { - const byTeam: Reminder['byTeam'] = {}; - for (let index = 0; index < 80; index++) { - byTeam[`team-${index}`] = [pr({ number: index + 1 })]; - } - const payload = buildSlackPayload( - { byTeam, fallback: { failingCi: [], readyToMerge: [], needsOwner: [] } }, - {}, - options, - ); - assert.ok(payload); - assert.ok(payload.blocks.length <= 50); - const last = payload.blocks[payload.blocks.length - 1]; - assert.match(last?.text.text ?? '', /…and \d+ more/u); - }); - - it('does not throw on null topology entries', () => { - const payload = buildSlackPayload( - { - byTeam: { a: [pr()] }, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, - }, - { - bad: null, - good: { githubHandle: 'MetaMask/a', slackHandle: { team: 'S1' } }, - } as unknown as Topology, - options, - ); - assert.match(payload?.text ?? '', //u); - }); -}); - -/* eslint-disable @typescript-eslint/naming-convention */ -describe('collectRequestedTeams', () => { - it('maps PR numbers to requested team slugs across pages', () => { - const map = collectRequestedTeams([ - [{ number: 1, requested_teams: [{ slug: 'a' }, { slug: 'b' }] }], - [{ number: 2, requested_teams: [] }, { number: 3 }], - ]); - assert.deepEqual(map.get(1), ['a', 'b']); - assert.deepEqual(map.get(2), []); - assert.equal(map.get(3), undefined); - assert.equal(map.get(4), undefined); - }); -}); - -/* eslint-enable @typescript-eslint/naming-convention */ - -describe('buildTopologyPath', () => { - it('encodes the ref', () => { - assert.equal( - buildTopologyPath('feat/a b#c'), - 'repos/MetaMask/MetaMask-planning/contents/topology.json?ref=feat%2Fa%20b%23c', - ); - }); -}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts new file mode 100644 index 00000000..4dea1732 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { pr } from './fixtures.mts'; +import { classifyPullRequests } from '../../dependabot-pr-reminder/classify.mts'; + +describe('classifyPullRequests', () => { + it('groups a PR under each remaining requested team', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.byTeam.a, [pullRequest]); + assert.deepEqual(result.byTeam.b, [pullRequest]); + }); + + it('lists failing CI PRs under fallback only', () => { + const pullRequest = pr({ ciFailing: true, requestedTeams: ['a'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.failingCi, [pullRequest]); + assert.deepEqual(result.byTeam, {}); + }); + + it('lists approved PRs with no teams left as ready to merge', () => { + const pullRequest = pr({ requestedTeams: [], hasApproval: true }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + }); + + it('lists PRs with no teams and no approval as needs owner', () => { + const pullRequest = pr(); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + assert.deepEqual(result.fallback.needsOwner, [pullRequest]); + }); + + it('filters other teams out when ownerTeams is set', () => { + const pullRequest = pr({ requestedTeams: ['ui', 'extension-platform'] }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['extension-platform'], + fallbackTeam: 'f', + }); + assert.deepEqual(Object.keys(result.byTeam), ['extension-platform']); + assert.deepEqual(result.byTeam['extension-platform'], [pullRequest]); + }); + + it('lists approved PRs as ready to merge when ownerTeams leaves nothing', () => { + const pullRequest = pr({ requestedTeams: ['ui'], hasApproval: true }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['extension-platform'], + fallbackTeam: 'f', + }); + assert.deepEqual(result.byTeam, {}); + assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + }); + + it('normalizes team names before comparing and grouping', () => { + const pullRequest = pr({ requestedTeams: ['MetaMask/UI', 'Core'] }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['@metamask/core'], + fallbackTeam: 'f', + }); + assert.deepEqual(Object.keys(result.byTeam), ['core']); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts new file mode 100644 index 00000000..ca0baaaa --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -0,0 +1,19 @@ +import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; + +/** + * Builds a pull request for tests. + * + * @param overrides - Fields to override on the default pull request. + * @returns The pull request. + */ +export function pr(overrides: Partial = {}): PullRequest { + return { + number: 1, + title: 'Bump foo from 1.0.0 to 1.0.1', + url: 'https://github.com/MetaMask/example/pull/1', + requestedTeams: [], + hasApproval: false, + ciFailing: false, + ...overrides, + }; +} diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts new file mode 100644 index 00000000..567df000 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -0,0 +1,151 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + buildTopologyPath, + collectRequestedTeams, + toPullRequest, +} from '../../dependabot-pr-reminder/github-api.mts'; +import type { GraphQlPullRequestNode } from '../../dependabot-pr-reminder/github-api.mts'; + +/** + * Builds a GraphQL node for tests. + * + * @param overrides - Fields to override. + * @returns The node. + */ +function node( + overrides: Partial = {}, +): GraphQlPullRequestNode { + return { + number: 7, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + isDraft: false, + // eslint-disable-next-line @typescript-eslint/naming-convention + author: { __typename: 'Bot', login: 'dependabot' }, + latestOpinionatedReviews: { nodes: [] }, + commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, + ...overrides, + }; +} + +describe('toPullRequest', () => { + it('returns undefined for drafts', () => { + assert.equal(toPullRequest(node({ isDraft: true }), []), undefined); + }); + + it('returns undefined for non-Dependabot authors', () => { + assert.equal( + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'Bot', login: 'someone-else' } }), + [], + ), + undefined, + ); + }); + + it('rejects a User named dependabot', () => { + assert.equal( + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'User', login: 'dependabot' } }), + [], + ), + undefined, + ); + }); + + it('accepts a Bot named dependabot[bot]', () => { + assert.equal( + toPullRequest( + // eslint-disable-next-line @typescript-eslint/naming-convention + node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), + [], + )?.number, + 7, + ); + }); + + it('returns undefined when the author is missing', () => { + assert.equal(toPullRequest(node({ author: null }), []), undefined); + }); + + it('maps a Dependabot PR', () => { + assert.deepEqual(toPullRequest(node(), []), { + number: 7, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + requestedTeams: [], + hasApproval: false, + ciFailing: false, + }); + }); + + it('uses the given requested teams', () => { + assert.deepEqual(toPullRequest(node(), ['wallet'])?.requestedTeams, [ + 'wallet', + ]); + }); + + it('sets hasApproval when approved and nothing requests changes', () => { + const result = (states: string[]) => + toPullRequest( + node({ + latestOpinionatedReviews: { + nodes: states.map((state) => ({ state })), + }, + }), + [], + )?.hasApproval; + assert.equal(result(['APPROVED']), true); + assert.equal(result(['APPROVED', 'CHANGES_REQUESTED']), false); + assert.equal(result(['CHANGES_REQUESTED']), false); + assert.equal(result([]), false); + }); + + it('sets ciFailing only for FAILURE and ERROR', () => { + const rollup = (state: string | null) => + toPullRequest( + node({ + commits: { + nodes: [ + { commit: { statusCheckRollup: state ? { state } : null } }, + ], + }, + }), + [], + )?.ciFailing; + assert.equal(rollup('FAILURE'), true); + assert.equal(rollup('ERROR'), true); + assert.equal(rollup('PENDING'), false); + assert.equal(rollup('SUCCESS'), false); + assert.equal(rollup(null), false); + }); +}); + +/* eslint-disable @typescript-eslint/naming-convention */ +describe('collectRequestedTeams', () => { + it('maps PR numbers to requested team slugs across pages', () => { + const map = collectRequestedTeams([ + [{ number: 1, requested_teams: [{ slug: 'a' }, { slug: 'b' }] }], + [{ number: 2, requested_teams: [] }, { number: 3 }], + ]); + assert.deepEqual(map.get(1), ['a', 'b']); + assert.deepEqual(map.get(2), []); + assert.equal(map.get(3), undefined); + assert.equal(map.get(4), undefined); + }); +}); + +/* eslint-enable @typescript-eslint/naming-convention */ + +describe('buildTopologyPath', () => { + it('encodes the ref', () => { + assert.equal( + buildTopologyPath('feat/a b#c'), + 'repos/MetaMask/MetaMask-planning/contents/topology.json?ref=feat%2Fa%20b%23c', + ); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts new file mode 100644 index 00000000..e508ba12 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -0,0 +1,169 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { pr } from './fixtures.mts'; +import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; +import type { + Reminder, + Topology, +} from '../../dependabot-pr-reminder/types.mts'; + +describe('buildSlackPayload', () => { + const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; + const emptyReminder = (): Reminder => ({ + byTeam: {}, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }); + const allText = (payload: { text: string; blocks: unknown[] }): string => + `${payload.text}\n${JSON.stringify(payload.blocks)}`; + + it('returns undefined for an empty reminder', () => { + assert.equal(buildSlackPayload(emptyReminder(), {}, options), undefined); + }); + + it('tags a team using slackHandle.team', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr({ number: 7 })]; + const payload = buildSlackPayload( + reminder, + { + 'core-platform': { + githubHandle: 'MetaMask/core-platform', + slackHandle: { team: 'S123' }, + }, + }, + options, + ); + assert.ok(payload); + assert.match(allText(payload), //u); + assert.match(allText(payload), /#7/u); + assert.match(payload.text, //u); + assert.doesNotMatch(allText(payload), /:dependabot:/u); + }); + + it('matches githubHandle regardless of case or @ prefix', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr()]; + const payload = buildSlackPayload( + reminder, + { + key: { + githubHandle: '@MetaMask/Core-Platform', + slackHandle: { team: 'S9' }, + }, + }, + options, + ); + assert.ok(payload); + assert.match(allText(payload), //u); + }); + + it('falls back to the plain team name when topology has no match', () => { + const reminder = emptyReminder(); + reminder.byTeam['core-platform'] = [pr()]; + const payload = buildSlackPayload(reminder, {}, options); + assert.ok(payload); + assert.match(allText(payload), /core-platform/u); + assert.doesNotMatch(allText(payload), /subteam\^/u); + }); + + it('escapes &, <, > in PR titles', () => { + const reminder = emptyReminder(); + reminder.byTeam.a = [pr({ title: 'Bump & b > c' })]; + const payload = buildSlackPayload(reminder, {}, options); + assert.ok(payload); + assert.match(allText(payload), /Bump <a> & b > c/u); + }); + + it('renders fallback sections under the fallback team', () => { + const reminder = emptyReminder(); + reminder.fallback.failingCi = [pr({ number: 1 })]; + reminder.fallback.readyToMerge = [pr({ number: 2 })]; + reminder.fallback.needsOwner = [pr({ number: 3 })]; + const payload = buildSlackPayload( + reminder, + { + platform: { + githubHandle: 'MetaMask/platform', + slackHandle: { team: 'SF' }, + }, + }, + options, + ); + assert.ok(payload); + const text = allText(payload); + assert.match(text, //u); + assert.match(text, /[Ff]ailing CI/u); + assert.match(text, /[Rr]eady to merge/u); + assert.match(text, /[Nn]eeds owner/u); + assert.match(text, /#1/u); + assert.match(text, /#2/u); + assert.match(text, /#3/u); + }); +}); + +describe('buildSlackPayload chunking', () => { + it('splits a long team list into sections under the Slack limit', () => { + const pullRequests = Array.from({ length: 60 }, (_, index) => + pr({ + number: index + 1, + title: `Bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, + url: `https://github.com/MetaMask/example/pull/${index + 1}`, + }), + ); + const reminder: Reminder = { + byTeam: { wallet: pullRequests }, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }; + const payload = buildSlackPayload( + reminder, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + const texts = payload.blocks.map((block) => block.text.text); + assert.ok(texts.length > 3); + for (const text of texts) { + assert.ok(text.length <= 3000, `section has ${text.length} characters`); + } + const joined = texts.join('\n'); + for (const { number } of pullRequests) { + assert.ok(joined.includes(`#${number} `), `PR #${number} is missing`); + } + }); +}); + +describe('buildSlackPayload limits and lookup', () => { + const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; + + it('caps blocks at 50 and appends an overflow line', () => { + const byTeam: Reminder['byTeam'] = {}; + for (let index = 0; index < 80; index++) { + byTeam[`team-${index}`] = [pr({ number: index + 1 })]; + } + const payload = buildSlackPayload( + { byTeam, fallback: { failingCi: [], readyToMerge: [], needsOwner: [] } }, + {}, + options, + ); + assert.ok(payload); + assert.ok(payload.blocks.length <= 50); + const last = payload.blocks[payload.blocks.length - 1]; + assert.match(last?.text.text ?? '', /…and \d+ more/u); + }); + + it('does not throw on null topology entries', () => { + const payload = buildSlackPayload( + { + byTeam: { a: [pr()] }, + fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + }, + { + bad: null, + good: { githubHandle: 'MetaMask/a', slackHandle: { team: 'S1' } }, + } as unknown as Topology, + options, + ); + assert.match(payload?.text ?? '', //u); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts new file mode 100644 index 00000000..99ade821 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + normalizeTeam, + parseOwnerTeams, +} from '../../dependabot-pr-reminder/teams.mts'; + +describe('normalizeTeam', () => { + it('lowercases and strips the @ and metamask/ prefixes', () => { + assert.equal(normalizeTeam('@MetaMask/Core-Platform'), 'core-platform'); + }); +}); + +describe('parseOwnerTeams', () => { + it('returns undefined for undefined, empty, and whitespace input', () => { + assert.equal(parseOwnerTeams(undefined), undefined); + assert.equal(parseOwnerTeams(''), undefined); + assert.equal(parseOwnerTeams(' \n '), undefined); + assert.equal(parseOwnerTeams(' , ,'), undefined); + }); + + it('splits, trims, and drops empty entries', () => { + assert.deepEqual(parseOwnerTeams(' a, b ,,c '), ['a', 'b', 'c']); + }); +}); From d50c4e31d455b94878317173f904d3d09047ed1d Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 17 Nov 2026 13:18:35 +0100 Subject: [PATCH 10/61] test: port dependabot reminder tests to vitest and fix lint Converts the node:test assertions to vitest, uses async fs in the CLI, and adds the process.env suppression the other scripts use. Coverage thresholds were bumped by the vitest autoUpdate ratchet. --- .../scripts/dependabot-pr-reminder/cli.mts | 8 +-- .../dependabot-pr-reminder/github-api.mts | 2 +- .../dependabot-pr-reminder/slack-payload.mts | 6 +- .../dependabot-pr-reminder/classify.test.mts | 27 ++++---- .../github-api.test.mts | 67 ++++++++++--------- .../slack-payload.test.mts | 53 +++++++-------- .../dependabot-pr-reminder/teams.test.mts | 15 ++--- oxlint-suppressions.json | 5 ++ 8 files changed, 92 insertions(+), 91 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index f57ac4fc..d00f4cb7 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -1,4 +1,4 @@ -import { appendFileSync, writeFileSync } from 'node:fs'; +import { appendFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -96,7 +96,7 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { if (!payload) { console.log('No open Dependabot pull requests to report.'); - appendFileSync(outputPath, 'has-prs=false\n'); + await appendFile(outputPath, 'has-prs=false\n'); return; } @@ -104,8 +104,8 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { environment.RUNNER_TEMP ?? '.', 'dependabot-reminder-payload.json', ); - writeFileSync(payloadPath, JSON.stringify(payload)); - appendFileSync(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); + await writeFile(payloadPath, JSON.stringify(payload)); + await appendFile(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); } diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 277a17ee..f8b88b66 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -1,8 +1,8 @@ import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import type { PullRequest } from './types.mts'; import { retry } from '../shared/retry.mts'; +import type { PullRequest } from './types.mts'; const execFileAsync = promisify(execFile); diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 203afed1..b24327b5 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,6 +1,8 @@ import { normalizeTeam } from './teams.mts'; import type { PullRequest, Reminder, Topology } from './types.mts'; +type SlackBlock = { type: string; text: { type: string; text: string } }; + /** * Escapes characters that Slack mrkdwn treats as control characters. * @@ -82,7 +84,7 @@ export function buildSlackPayload( text: string; // eslint-disable-next-line @typescript-eslint/naming-convention link_names: boolean; - blocks: { type: string; text: { type: string; text: string } }[]; + blocks: SlackBlock[]; } | undefined { const teamEntries = Object.entries(reminder.byTeam).filter( @@ -109,7 +111,7 @@ export function buildSlackPayload( return id ? `` : slug; }; - const section = (text: string) => ({ + const section = (text: string): SlackBlock => ({ type: 'section', text: { type: 'mrkdwn', text }, }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 4dea1732..60cf5027 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -1,34 +1,33 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { describe, expect, it } from 'vitest'; -import { pr } from './fixtures.mts'; import { classifyPullRequests } from '../../dependabot-pr-reminder/classify.mts'; +import { pr } from './fixtures.mts'; describe('classifyPullRequests', () => { it('groups a PR under each remaining requested team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b'] }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.byTeam.a, [pullRequest]); - assert.deepEqual(result.byTeam.b, [pullRequest]); + expect(result.byTeam.a).toStrictEqual([pullRequest]); + expect(result.byTeam.b).toStrictEqual([pullRequest]); }); it('lists failing CI PRs under fallback only', () => { const pullRequest = pr({ ciFailing: true, requestedTeams: ['a'] }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.failingCi, [pullRequest]); - assert.deepEqual(result.byTeam, {}); + expect(result.fallback.failingCi).toStrictEqual([pullRequest]); + expect(result.byTeam).toStrictEqual({}); }); it('lists approved PRs with no teams left as ready to merge', () => { const pullRequest = pr({ requestedTeams: [], hasApproval: true }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + expect(result.fallback.readyToMerge).toStrictEqual([pullRequest]); }); it('lists PRs with no teams and no approval as needs owner', () => { const pullRequest = pr(); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - assert.deepEqual(result.fallback.needsOwner, [pullRequest]); + expect(result.fallback.needsOwner).toStrictEqual([pullRequest]); }); it('filters other teams out when ownerTeams is set', () => { @@ -37,8 +36,8 @@ describe('classifyPullRequests', () => { ownerTeams: ['extension-platform'], fallbackTeam: 'f', }); - assert.deepEqual(Object.keys(result.byTeam), ['extension-platform']); - assert.deepEqual(result.byTeam['extension-platform'], [pullRequest]); + expect(Object.keys(result.byTeam)).toStrictEqual(['extension-platform']); + expect(result.byTeam['extension-platform']).toStrictEqual([pullRequest]); }); it('lists approved PRs as ready to merge when ownerTeams leaves nothing', () => { @@ -47,8 +46,8 @@ describe('classifyPullRequests', () => { ownerTeams: ['extension-platform'], fallbackTeam: 'f', }); - assert.deepEqual(result.byTeam, {}); - assert.deepEqual(result.fallback.readyToMerge, [pullRequest]); + expect(result.byTeam).toStrictEqual({}); + expect(result.fallback.readyToMerge).toStrictEqual([pullRequest]); }); it('normalizes team names before comparing and grouping', () => { @@ -57,6 +56,6 @@ describe('classifyPullRequests', () => { ownerTeams: ['@metamask/core'], fallbackTeam: 'f', }); - assert.deepEqual(Object.keys(result.byTeam), ['core']); + expect(Object.keys(result.byTeam)).toStrictEqual(['core']); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index 567df000..b8b94dba 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { describe, expect, it } from 'vitest'; import { buildTopologyPath, @@ -32,48 +31,45 @@ function node( describe('toPullRequest', () => { it('returns undefined for drafts', () => { - assert.equal(toPullRequest(node({ isDraft: true }), []), undefined); + expect(toPullRequest(node({ isDraft: true }), [])).toBeUndefined(); }); it('returns undefined for non-Dependabot authors', () => { - assert.equal( + expect( toPullRequest( // eslint-disable-next-line @typescript-eslint/naming-convention node({ author: { __typename: 'Bot', login: 'someone-else' } }), [], ), - undefined, - ); + ).toBeUndefined(); }); it('rejects a User named dependabot', () => { - assert.equal( + expect( toPullRequest( // eslint-disable-next-line @typescript-eslint/naming-convention node({ author: { __typename: 'User', login: 'dependabot' } }), [], ), - undefined, - ); + ).toBeUndefined(); }); it('accepts a Bot named dependabot[bot]', () => { - assert.equal( + expect( toPullRequest( // eslint-disable-next-line @typescript-eslint/naming-convention node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), [], )?.number, - 7, - ); + ).toBe(7); }); it('returns undefined when the author is missing', () => { - assert.equal(toPullRequest(node({ author: null }), []), undefined); + expect(toPullRequest(node({ author: null }), [])).toBeUndefined(); }); it('maps a Dependabot PR', () => { - assert.deepEqual(toPullRequest(node(), []), { + expect(toPullRequest(node(), [])).toStrictEqual({ number: 7, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', @@ -84,13 +80,13 @@ describe('toPullRequest', () => { }); it('uses the given requested teams', () => { - assert.deepEqual(toPullRequest(node(), ['wallet'])?.requestedTeams, [ + expect(toPullRequest(node(), ['wallet'])?.requestedTeams).toStrictEqual([ 'wallet', ]); }); it('sets hasApproval when approved and nothing requests changes', () => { - const result = (states: string[]) => + const result = (states: string[]): boolean | undefined => toPullRequest( node({ latestOpinionatedReviews: { @@ -99,29 +95,35 @@ describe('toPullRequest', () => { }), [], )?.hasApproval; - assert.equal(result(['APPROVED']), true); - assert.equal(result(['APPROVED', 'CHANGES_REQUESTED']), false); - assert.equal(result(['CHANGES_REQUESTED']), false); - assert.equal(result([]), false); + expect(result(['APPROVED'])).toBe(true); + expect(result(['APPROVED', 'CHANGES_REQUESTED'])).toBe(false); + expect(result(['CHANGES_REQUESTED'])).toBe(false); + expect(result([])).toBe(false); }); it('sets ciFailing only for FAILURE and ERROR', () => { - const rollup = (state: string | null) => + const rollup = ( + statusCheckRollup: { state: string } | null, + ): boolean | undefined => toPullRequest( node({ commits: { nodes: [ - { commit: { statusCheckRollup: state ? { state } : null } }, + { + commit: { + statusCheckRollup, + }, + }, ], }, }), [], )?.ciFailing; - assert.equal(rollup('FAILURE'), true); - assert.equal(rollup('ERROR'), true); - assert.equal(rollup('PENDING'), false); - assert.equal(rollup('SUCCESS'), false); - assert.equal(rollup(null), false); + expect(rollup({ state: 'FAILURE' })).toBe(true); + expect(rollup({ state: 'ERROR' })).toBe(true); + expect(rollup({ state: 'PENDING' })).toBe(false); + expect(rollup({ state: 'SUCCESS' })).toBe(false); + expect(rollup(null)).toBe(false); }); }); @@ -132,10 +134,10 @@ describe('collectRequestedTeams', () => { [{ number: 1, requested_teams: [{ slug: 'a' }, { slug: 'b' }] }], [{ number: 2, requested_teams: [] }, { number: 3 }], ]); - assert.deepEqual(map.get(1), ['a', 'b']); - assert.deepEqual(map.get(2), []); - assert.equal(map.get(3), undefined); - assert.equal(map.get(4), undefined); + expect(map.get(1)).toStrictEqual(['a', 'b']); + expect(map.get(2)).toStrictEqual([]); + expect(map.get(3)).toBeUndefined(); + expect(map.get(4)).toBeUndefined(); }); }); @@ -143,8 +145,7 @@ describe('collectRequestedTeams', () => { describe('buildTopologyPath', () => { it('encodes the ref', () => { - assert.equal( - buildTopologyPath('feat/a b#c'), + expect(buildTopologyPath('feat/a b#c')).toBe( 'repos/MetaMask/MetaMask-planning/contents/topology.json?ref=feat%2Fa%20b%23c', ); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index e508ba12..d298f6e1 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -1,12 +1,8 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { assert, describe, expect, it } from 'vitest'; -import { pr } from './fixtures.mts'; import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; -import type { - Reminder, - Topology, -} from '../../dependabot-pr-reminder/types.mts'; +import type { Reminder } from '../../dependabot-pr-reminder/types.mts'; +import { pr } from './fixtures.mts'; describe('buildSlackPayload', () => { const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; @@ -18,7 +14,7 @@ describe('buildSlackPayload', () => { `${payload.text}\n${JSON.stringify(payload.blocks)}`; it('returns undefined for an empty reminder', () => { - assert.equal(buildSlackPayload(emptyReminder(), {}, options), undefined); + expect(buildSlackPayload(emptyReminder(), {}, options)).toBeUndefined(); }); it('tags a team using slackHandle.team', () => { @@ -35,10 +31,10 @@ describe('buildSlackPayload', () => { options, ); assert.ok(payload); - assert.match(allText(payload), //u); - assert.match(allText(payload), /#7/u); - assert.match(payload.text, //u); - assert.doesNotMatch(allText(payload), /:dependabot:/u); + expect(allText(payload)).toMatch(//u); + expect(allText(payload)).toMatch(/#7/u); + expect(payload.text).toMatch(//u); + expect(allText(payload)).not.toMatch(/:dependabot:/u); }); it('matches githubHandle regardless of case or @ prefix', () => { @@ -55,7 +51,7 @@ describe('buildSlackPayload', () => { options, ); assert.ok(payload); - assert.match(allText(payload), //u); + expect(allText(payload)).toMatch(//u); }); it('falls back to the plain team name when topology has no match', () => { @@ -63,8 +59,8 @@ describe('buildSlackPayload', () => { reminder.byTeam['core-platform'] = [pr()]; const payload = buildSlackPayload(reminder, {}, options); assert.ok(payload); - assert.match(allText(payload), /core-platform/u); - assert.doesNotMatch(allText(payload), /subteam\^/u); + expect(allText(payload)).toMatch(/core-platform/u); + expect(allText(payload)).not.toMatch(/subteam\^/u); }); it('escapes &, <, > in PR titles', () => { @@ -72,7 +68,7 @@ describe('buildSlackPayload', () => { reminder.byTeam.a = [pr({ title: 'Bump & b > c' })]; const payload = buildSlackPayload(reminder, {}, options); assert.ok(payload); - assert.match(allText(payload), /Bump <a> & b > c/u); + expect(allText(payload)).toMatch(/Bump <a> & b > c/u); }); it('renders fallback sections under the fallback team', () => { @@ -92,13 +88,13 @@ describe('buildSlackPayload', () => { ); assert.ok(payload); const text = allText(payload); - assert.match(text, //u); - assert.match(text, /[Ff]ailing CI/u); - assert.match(text, /[Rr]eady to merge/u); - assert.match(text, /[Nn]eeds owner/u); - assert.match(text, /#1/u); - assert.match(text, /#2/u); - assert.match(text, /#3/u); + expect(text).toMatch(//u); + expect(text).toMatch(/[Ff]ailing CI/u); + expect(text).toMatch(/[Rr]eady to merge/u); + expect(text).toMatch(/[Nn]eeds owner/u); + expect(text).toMatch(/#1/u); + expect(text).toMatch(/#2/u); + expect(text).toMatch(/#3/u); }); }); @@ -122,7 +118,7 @@ describe('buildSlackPayload chunking', () => { ); assert.ok(payload); const texts = payload.blocks.map((block) => block.text.text); - assert.ok(texts.length > 3); + expect(texts.length).toBeGreaterThan(3); for (const text of texts) { assert.ok(text.length <= 3000, `section has ${text.length} characters`); } @@ -147,9 +143,8 @@ describe('buildSlackPayload limits and lookup', () => { options, ); assert.ok(payload); - assert.ok(payload.blocks.length <= 50); - const last = payload.blocks[payload.blocks.length - 1]; - assert.match(last?.text.text ?? '', /…and \d+ more/u); + expect(payload.blocks.length).toBeLessThanOrEqual(50); + expect(payload.blocks.at(-1)?.text.text).toMatch(/…and \d+ more/u); }); it('does not throw on null topology entries', () => { @@ -161,9 +156,9 @@ describe('buildSlackPayload limits and lookup', () => { { bad: null, good: { githubHandle: 'MetaMask/a', slackHandle: { team: 'S1' } }, - } as unknown as Topology, + }, options, ); - assert.match(payload?.text ?? '', //u); + expect(payload?.text).toMatch(//u); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts index 99ade821..b05c5f35 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { describe, expect, it } from 'vitest'; import { normalizeTeam, @@ -8,19 +7,19 @@ import { describe('normalizeTeam', () => { it('lowercases and strips the @ and metamask/ prefixes', () => { - assert.equal(normalizeTeam('@MetaMask/Core-Platform'), 'core-platform'); + expect(normalizeTeam('@MetaMask/Core-Platform')).toBe('core-platform'); }); }); describe('parseOwnerTeams', () => { it('returns undefined for undefined, empty, and whitespace input', () => { - assert.equal(parseOwnerTeams(undefined), undefined); - assert.equal(parseOwnerTeams(''), undefined); - assert.equal(parseOwnerTeams(' \n '), undefined); - assert.equal(parseOwnerTeams(' , ,'), undefined); + expect(parseOwnerTeams(undefined)).toBeUndefined(); + expect(parseOwnerTeams('')).toBeUndefined(); + expect(parseOwnerTeams(' \n ')).toBeUndefined(); + expect(parseOwnerTeams(' , ,')).toBeUndefined(); }); it('splits, trims, and drops empty entries', () => { - assert.deepEqual(parseOwnerTeams(' a, b ,,c '), ['a', 'b', 'c']); + expect(parseOwnerTeams(' a, b ,,c ')).toStrictEqual(['a', 'b', 'c']); }); }); diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 9d795aba..e8bd94e7 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -9,6 +9,11 @@ "count": 1 } }, + ".github/scripts/dependabot-pr-reminder/cli.mts": { + "node/no-process-env": { + "count": 1 + } + }, ".github/scripts/generate-rc-commits.mjs": { "import/no-named-as-default": { "count": 1 From 8dab76ce376d703c46844f965dec766288352a98 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 17 Nov 2026 13:40:02 +0100 Subject: [PATCH 11/61] docs: drop Dependabot reminder section from README Other workflows aren't listed there. --- README.md | 35 ----------------------------------- 1 file changed, 35 deletions(-) diff --git a/README.md b/README.md index e7b09580..5418480e 100644 --- a/README.md +++ b/README.md @@ -13,41 +13,6 @@ This repository holds a collection of scripts which are intended to be run local - `yarn segment-schema:draft-pr`: Local CLI for the Segment schema draft. See the [CLI](src/segment-schema-draft-pr/README.md) and the [action](.github/actions/draft-segment-schema-pr/README.md). -### Dependabot PR reminder - -`.github/workflows/remind-dependabot-prs.yml` posts a Slack thread of open Dependabot PRs grouped by owning team. Owners are the teams still requested as reviewers; Slack tags come from `MetaMask-planning/topology.json`. PRs with failing CI or no owning team are listed under `fallback-team`. Nothing is posted when no PRs are open. - -| Input | Default | Description | -| ------------------- | --------------- | ---------------------------------------------------------------- | -| `owner-teams` | | Comma-separated team slugs that count as owners. Unset means all | -| `fallback-team` | `core-platform` | Team that gets PRs with no owner or failing CI | -| `topology-ref` | `main` | Ref of `MetaMask-planning` to read `topology.json` from | -| `slack-webhook-url` | | Required secret, one per repo and channel | - -The caller must be named `remind-dependabot-prs.yml`, grant the permissions below, have a `default-branch` environment and a `TOKEN_EXCHANGE_URL` variable, and have a token-exchange-service policy allowing `contents: read` on `MetaMask/MetaMask-planning`. Example for `metamask-extension` (`core` omits `with`): - -```yaml -on: - schedule: - - cron: '0 14 * * 1' - workflow_dispatch: - -jobs: - remind: - permissions: - contents: read - pull-requests: read - checks: read - statuses: read - id-token: write - uses: MetaMask/github-tools/.github/workflows/remind-dependabot-prs.yml@v1 - with: - owner-teams: extension-platform - fallback-team: extension-platform - secrets: - slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} -``` - ### Authentication Some scripts require a GitHub token in order to run fully. From cffaa3ee76ebe772f688b40b1fe8473b9079c445 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 17 Nov 2026 15:27:24 +0100 Subject: [PATCH 12/61] refactor: use shared helpers and one GraphQL search in the Dependabot reminder Requested teams now come from the same query, so a run needs one request per 100 PRs instead of two paginated fetches. Also drops link_names, shortens titles before wrapping, only pings teams that are shown, posts without tags if topology fails, documents caller requirements, and adds an environment input. --- .../dependabot-pr-reminder/classify.mts | 6 +- .../scripts/dependabot-pr-reminder/cli.mts | 81 +++----- .../dependabot-pr-reminder/github-api.mts | 179 +++++++++--------- .../dependabot-pr-reminder/slack-payload.mts | 163 ++++++---------- .../scripts/dependabot-pr-reminder/teams.mts | 14 -- .../scripts/dependabot-pr-reminder/types.mts | 5 - .../github-api.test.mts | 122 +++++++----- .../slack-payload.test.mts | 46 +++++ .../dependabot-pr-reminder/teams.test.mts | 11 +- .github/workflows/remind-dependabot-prs.yml | 38 ++-- 10 files changed, 317 insertions(+), 348 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 319b5c67..95fb2225 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -1,4 +1,4 @@ -import { normalizeTeam } from './teams.mts'; +import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; /** @@ -18,7 +18,7 @@ export function classifyPullRequests( pullRequests: PullRequest[], options: { ownerTeams?: string[]; fallbackTeam: string }, ): Reminder { - const ownerTeams = options.ownerTeams?.map(normalizeTeam); + const ownerTeams = options.ownerTeams?.map(normalizeTeamSlug); const reminder: Reminder = { byTeam: {}, fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, @@ -31,7 +31,7 @@ export function classifyPullRequests( } const teams = pullRequest.requestedTeams - .map(normalizeTeam) + .map(normalizeTeamSlug) .filter((team) => !ownerTeams || ownerTeams.includes(team)); if (teams.length > 0) { diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index d00f4cb7..0e352029 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -2,18 +2,12 @@ import { appendFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { fetchTopology } from '../shared/topology.mts'; +import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; -import { - PULL_REQUESTS_QUERY, - buildTopologyPath, - collectRequestedTeams, - ghApi, - toPullRequest, -} from './github-api.mts'; -import type { GraphQlPullRequestNode } from './github-api.mts'; +import { fetchDependabotPullRequests } from './github-api.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams } from './teams.mts'; -import type { PullRequest, Topology } from './types.mts'; /** * Fetches open Dependabot pull requests and writes the Slack payload. @@ -30,50 +24,22 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } - const [owner, name] = repository.split('/'); - if (!owner || !name) { + if (repository.split('/').filter(Boolean).length !== 2) { throw new Error('GITHUB_REPOSITORY must be in owner/name form'); } const ref = environment.TOPOLOGY_REF?.trim() ? environment.TOPOLOGY_REF.trim() : 'main'; - const graphqlOutput = await ghApi( - [ - 'graphql', - '--paginate', - '--slurp', - '-f', - `query=${PULL_REQUESTS_QUERY}`, - '-f', - `owner=${owner}`, - '-f', - `name=${name}`, - ], - undefined, + const pullRequests = await fetchDependabotPullRequests(repository, { environment, - ); - const pages = JSON.parse(graphqlOutput) as { - data: { repository: { pullRequests: { nodes: GraphQlPullRequestNode[] } } }; - }[]; - const restOutput = await ghApi( - [ - '--paginate', - '--slurp', - `repos/${owner}/${name}/pulls?state=open&per_page=100`, - ], - undefined, - environment, - ); - const requestedTeamsByNumber = collectRequestedTeams( - JSON.parse(restOutput) as Parameters[0], - ); - const pullRequests = pages - .flatMap((page) => page.data.repository.pullRequests.nodes) - .map((node) => - toPullRequest(node, requestedTeamsByNumber.get(node.number) ?? []), - ) - .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); + }); + // Skip the topology request entirely when there is nothing to report. + if (pullRequests.length === 0) { + console.log('No open Dependabot pull requests to report.'); + await appendFile(outputPath, 'has-prs=false\n'); + return; + } const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); const reminder = classifyPullRequests(pullRequests, { @@ -81,19 +47,26 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { fallbackTeam, }); - const topology = JSON.parse( - await ghApi( - ['-H', 'Accept: application/vnd.github.raw', buildTopologyPath(ref)], - planningToken, - environment, - ), - ) as Topology; + // Tags are a nicety. If topology is unavailable, still post, with team names + // as plain text. + let topology: Topology = {}; + try { + topology = await fetchTopology({ + ref, + gh: { environment, token: planningToken }, + }); + } catch (error) { + console.log( + `::warning::Could not read topology.json, posting without Slack tags: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } const payload = buildSlackPayload(reminder, topology, { fallbackTeam, repository, }); - if (!payload) { console.log('No open Dependabot pull requests to report.'); await appendFile(outputPath, 'has-prs=false\n'); diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index f8b88b66..196fac34 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -1,35 +1,81 @@ -import { execFile } from 'node:child_process'; -import { promisify } from 'node:util'; - -import { retry } from '../shared/retry.mts'; +import { ghGraphqlPages } from '../shared/github-cli.mts'; +import type { GhOptions } from '../shared/github-cli.mts'; import type { PullRequest } from './types.mts'; -const execFileAsync = promisify(execFile); - export type GraphQlPullRequestNode = { number: number; title: string; url: string; isDraft: boolean; - // eslint-disable-next-line @typescript-eslint/naming-convention author: { __typename: string; login: string } | null; + reviewRequests: { + nodes: { + requestedReviewer: { __typename: string; slug?: string } | null; + }[]; + }; latestOpinionatedReviews: { nodes: { state: string }[] }; commits: { nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; }; }; +/** A page of search results. Nodes that are not pull requests come back empty. */ +export type SearchPage = { + data: { + search: { nodes: (GraphQlPullRequestNode | Record)[] }; + }; +}; + /** - * Maps a GraphQL pull request node to a PullRequest. + * One query returns every field the reminder needs, including the requested + * teams, so a run costs a single request per 100 pull requests. The search + * filter keeps drafts and non Dependabot authors out on the server side. + */ +export const PULL_REQUESTS_QUERY = ` +query($searchQuery: String!, $endCursor: String) { + search(query: $searchQuery, type: ISSUE, first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { + ... on PullRequest { + number + title + url + isDraft + author { __typename login } + reviewRequests(first: 20) { + nodes { requestedReviewer { __typename ... on Team { slug } } } + } + latestOpinionatedReviews(first: 20) { nodes { state } } + commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } + } + } + } +}`; + +/** + * Builds the search string for open, non draft Dependabot pull requests. * - * @param node - The GraphQL node. - * @param requestedTeams - The team slugs requested for review (from REST). - * @returns The pull request, or undefined for drafts and non-Dependabot PRs. + * @param repository - The repository in `owner/name` form. + * @returns The GitHub search query. + */ +export function buildSearchQuery(repository: string): string { + return `repo:${repository} is:pr is:open draft:false author:app/dependabot`; +} + +/** + * Maps a search node to a PullRequest. + * + * @param node - The search node. + * @returns The pull request, or undefined for non pull requests, drafts and + * non Dependabot PRs. The server side search already filters those, this is a + * safety net. */ export function toPullRequest( - node: GraphQlPullRequestNode, - requestedTeams: string[], + node: GraphQlPullRequestNode | Record, ): PullRequest | undefined { + if (!('number' in node)) { + return undefined; + } // GraphQL returns `dependabot` for the Bot actor; REST returns // `dependabot[bot]`. Accept both, but only for Bot actors. if ( @@ -43,98 +89,55 @@ export function toPullRequest( const rollupState = node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; + const reviewStates = node.latestOpinionatedReviews.nodes.map( + ({ state }) => state, + ); return { number: node.number, title: node.title, url: node.url, - requestedTeams, + requestedTeams: node.reviewRequests.nodes.flatMap( + ({ requestedReviewer }) => + requestedReviewer?.__typename === 'Team' && requestedReviewer.slug + ? [requestedReviewer.slug] + : [], + ), hasApproval: - node.latestOpinionatedReviews.nodes.some( - ({ state }) => state === 'APPROVED', - ) && - !node.latestOpinionatedReviews.nodes.some( - ({ state }) => state === 'CHANGES_REQUESTED', - ), + reviewStates.includes('APPROVED') && + !reviewStates.includes('CHANGES_REQUESTED'), ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', }; } /** - * Builds a map of PR number to requested team slugs from REST pull request - * pages. - * - * @param pages - The paginated REST responses. - * @returns The requested team slugs by PR number. - */ -export function collectRequestedTeams( - pages: { - number: number; - // eslint-disable-next-line @typescript-eslint/naming-convention - requested_teams?: { slug: string }[]; - }[][], -): Map { - const result = new Map(); - for (const restPullRequest of pages.flat()) { - if (restPullRequest.requested_teams) { - result.set( - restPullRequest.number, - restPullRequest.requested_teams.map(({ slug }) => slug), - ); - } - } - return result; -} - -/** - * Builds the REST path to read topology.json at a ref. + * Maps search pages to pull requests. * - * @param ref - The git ref. - * @returns The `gh api` path. + * @param pages - The paginated search responses. + * @returns The Dependabot pull requests. */ -export function buildTopologyPath(ref: string): string { - return `repos/MetaMask/MetaMask-planning/contents/topology.json?ref=${encodeURIComponent(ref)}`; +export function toPullRequests(pages: SearchPage[]): PullRequest[] { + return pages + .flatMap((page) => page.data.search.nodes) + .map(toPullRequest) + .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); } -export const PULL_REQUESTS_QUERY = ` -query($owner: String!, $name: String!, $endCursor: String) { - repository(owner: $owner, name: $name) { - pullRequests(states: OPEN, first: 100, after: $endCursor) { - pageInfo { hasNextPage endCursor } - nodes { - number - title - url - isDraft - author { __typename login } - latestOpinionatedReviews(first: 20) { nodes { state } } - commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } - } - } - } -}`; - /** - * Runs `gh api`, retrying transient failures. + * Fetches the open Dependabot pull requests of a repository. * - * @param argumentsList - Arguments after `gh api`. - * @param token - The token passed as GH_TOKEN, if different from the default. - * @param environment - The base environment. - * @returns The standard output. + * @param repository - The repository in `owner/name` form. + * @param gh - Options for the underlying `gh api` calls. + * @returns The pull requests. */ -export async function ghApi( - argumentsList: string[], - token: string | undefined, - environment: NodeJS.ProcessEnv, -): Promise { - return await retry( - async () => { - const { stdout } = await execFileAsync('gh', ['api', ...argumentsList], { - env: token ? { ...environment, GH_TOKEN: token } : environment, - maxBuffer: 100 * 1024 * 1024, - }); - return stdout; - }, - { maxAttempts: 3, delayMilliseconds: 2_000 }, +export async function fetchDependabotPullRequests( + repository: string, + gh: GhOptions, +): Promise { + const pages = await ghGraphqlPages( + PULL_REQUESTS_QUERY, + { searchQuery: buildSearchQuery(repository) }, + gh, ); + return toPullRequests(pages); } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index b24327b5..2a302c2f 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,25 +1,18 @@ -import { normalizeTeam } from './teams.mts'; -import type { PullRequest, Reminder, Topology } from './types.mts'; +import { + capBlocks, + chunkSections, + escapeSlack, + section, + subteamMention, + truncateText, +} from '../shared/slack-blocks.mts'; +import type { SlackBlock } from '../shared/slack-blocks.mts'; +import { getSlackSubteamId, normalizeTeamSlug } from '../shared/topology.mts'; +import type { Topology } from '../shared/topology.mts'; +import type { PullRequest, Reminder } from './types.mts'; -type SlackBlock = { type: string; text: { type: string; text: string } }; - -/** - * Escapes characters that Slack mrkdwn treats as control characters. - * - * @param text - The raw text. - * @returns The escaped text. - */ -function escapeSlack(text: string): string { - return text - .replace(/&/gu, '&') - .replace(//gu, '>'); -} - -/** - * The maximum characters of a section text we emit. Slack rejects 3000+. - */ -const MAX_SECTION_LENGTH = 2800; +/** Long titles are cut before escaping so a cut can't split a link or entity. */ +const MAX_TITLE_LENGTH = 200; /** * Formats pull requests as bulleted Slack links, one line each. @@ -29,42 +22,11 @@ const MAX_SECTION_LENGTH = 2800; */ function formatPullRequestLines(pullRequests: PullRequest[]): string[] { return pullRequests.map( - ({ url, number, title }) => `• <${url}|#${number} ${escapeSlack(title)}>`, + ({ url, number, title }) => + `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, ); } -/** - * Splits a header and lines into section texts that fit Slack's limit. The - * header is repeated on every section. - * - * @param header - The header line. - * @param lines - The lines to list below the header. - * @returns One or more section texts. - */ -function chunkSections(header: string, lines: string[]): string[] { - const budget = Math.max(MAX_SECTION_LENGTH - header.length - 1, 1); - const texts: string[] = []; - let current: string[] = []; - let length = 0; - - for (const rawLine of lines) { - const line = - rawLine.length > budget ? `${rawLine.slice(0, budget - 1)}…` : rawLine; - const added = line.length + (current.length > 0 ? 1 : 0); - if (current.length > 0 && length + added > budget) { - texts.push(`${header}\n${current.join('\n')}`); - current = []; - length = 0; - } - length += line.length + (current.length > 0 ? 1 : 0); - current.push(line); - } - if (current.length > 0) { - texts.push(`${header}\n${current.join('\n')}`); - } - return texts; -} - /** * Builds the Slack incoming webhook payload for a reminder. * @@ -82,8 +44,6 @@ export function buildSlackPayload( ): | { text: string; - // eslint-disable-next-line @typescript-eslint/naming-convention - link_names: boolean; blocks: SlackBlock[]; } | undefined { @@ -100,66 +60,57 @@ export function buildSlackPayload( return undefined; } - const tag = (team: string): string => { - const slug = normalizeTeam(team); - const entry = Object.values(topology).find( - (candidate) => - typeof candidate?.githubHandle === 'string' && - normalizeTeam(candidate.githubHandle) === slug, - ); - const id = entry?.slackHandle?.team; - return id ? `` : slug; + const tag = (team: string): { text: string; subteamId?: string } => { + const subteamId = getSlackSubteamId(topology, team); + return subteamId + ? { text: subteamMention(subteamId), subteamId } + : { text: escapeSlack(normalizeTeamSlug(team)) }; }; - const section = (text: string): SlackBlock => ({ - type: 'section', - text: { type: 'mrkdwn', text }, - }); - const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; - const blocks = [section(headline)]; - const mentions = new Set(); - const mention = (team: string): string => { - const value = tag(team); - if (value.startsWith(' { + const fullHeader = label ? `${header.text} *${label}*` : header.text; for (const text of chunkSections( - mention(team), + fullHeader, formatPullRequestLines(pullRequests), )) { - blocks.push(section(text)); + entries.push({ block: section(text), subteamId: header.subteamId }); } + }; + for (const [team, pullRequests] of teamEntries) { + addSections(tag(team), pullRequests); } for (const { label, pullRequests } of fallbackSections) { - for (const text of chunkSections( - `${mention(options.fallbackTeam)} *${label}*`, - formatPullRequestLines(pullRequests), - )) { - blocks.push(section(text)); - } + addSections(tag(options.fallbackTeam), pullRequests, label); } - const maxBlocks = 50; - if (blocks.length > maxBlocks) { - const omitted = blocks.splice(maxBlocks - 1); - const omittedCount = omitted.reduce( - (total, block) => - total + - block.text.text.split('\n').filter((line) => line.startsWith('•')) - .length, - 0, - ); - blocks.push(section(`…and ${omittedCount} more pull request(s) not shown`)); - } + const { blocks, omitted } = capBlocks( + entries.map(({ block }) => block), + (omittedBlocks) => + `…and ${omittedBlocks.reduce( + (total, block) => + total + + block.text.text.split('\n').filter((line) => line.startsWith('•')) + .length, + 0, + )} more pull request(s) not shown`, + ); + const shownEntries = + omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; + const mentions = new Set( + shownEntries.flatMap(({ subteamId }) => + subteamId ? [subteamMention(subteamId)] : [], + ), + ); - return { - text: [headline, ...mentions].join(' '), - // eslint-disable-next-line @typescript-eslint/naming-convention - link_names: true, - blocks, - }; + return { text: [headline, ...mentions].join(' '), blocks }; } diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts index 4b923d90..07bb7834 100644 --- a/.github/scripts/dependabot-pr-reminder/teams.mts +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -1,17 +1,3 @@ -/** - * Normalizes a team reference to a bare lowercase slug. - * - * @param team - The team, e.g. `@MetaMask/Core-Platform`. - * @returns The slug, e.g. `core-platform`. - */ -export function normalizeTeam(team: string): string { - return team - .trim() - .toLowerCase() - .replace(/^@/u, '') - .replace(/^metamask\//u, ''); -} - /** * Parses the comma-separated OWNER_TEAMS value. * diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 58e3d12f..2e90e0f4 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -15,8 +15,3 @@ export type Reminder = { needsOwner: PullRequest[]; }; }; - -export type Topology = Record< - string, - { githubHandle?: string; slackHandle?: { team?: string } } | null ->; diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index b8b94dba..7c733c8a 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -1,14 +1,18 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { - buildTopologyPath, - collectRequestedTeams, + buildSearchQuery, + fetchDependabotPullRequests, toPullRequest, + toPullRequests, +} from '../../dependabot-pr-reminder/github-api.mts'; +import type { + GraphQlPullRequestNode, + SearchPage, } from '../../dependabot-pr-reminder/github-api.mts'; -import type { GraphQlPullRequestNode } from '../../dependabot-pr-reminder/github-api.mts'; /** - * Builds a GraphQL node for tests. + * Builds a search node for tests. * * @param overrides - Fields to override. * @returns The node. @@ -21,8 +25,8 @@ function node( title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', isDraft: false, - // eslint-disable-next-line @typescript-eslint/naming-convention author: { __typename: 'Bot', login: 'dependabot' }, + reviewRequests: { nodes: [] }, latestOpinionatedReviews: { nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, ...overrides, @@ -30,26 +34,24 @@ function node( } describe('toPullRequest', () => { + it('returns undefined for search nodes that are not pull requests', () => { + expect(toPullRequest({})).toBeUndefined(); + }); + it('returns undefined for drafts', () => { - expect(toPullRequest(node({ isDraft: true }), [])).toBeUndefined(); + expect(toPullRequest(node({ isDraft: true }))).toBeUndefined(); }); it('returns undefined for non-Dependabot authors', () => { expect( - toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention - node({ author: { __typename: 'Bot', login: 'someone-else' } }), - [], - ), + toPullRequest(node({ author: { __typename: 'Bot', login: 'other' } })), ).toBeUndefined(); }); it('rejects a User named dependabot', () => { expect( toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention node({ author: { __typename: 'User', login: 'dependabot' } }), - [], ), ).toBeUndefined(); }); @@ -57,19 +59,17 @@ describe('toPullRequest', () => { it('accepts a Bot named dependabot[bot]', () => { expect( toPullRequest( - // eslint-disable-next-line @typescript-eslint/naming-convention node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), - [], )?.number, ).toBe(7); }); it('returns undefined when the author is missing', () => { - expect(toPullRequest(node({ author: null }), [])).toBeUndefined(); + expect(toPullRequest(node({ author: null }))).toBeUndefined(); }); it('maps a Dependabot PR', () => { - expect(toPullRequest(node(), [])).toStrictEqual({ + expect(toPullRequest(node())).toStrictEqual({ number: 7, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', @@ -79,10 +79,19 @@ describe('toPullRequest', () => { }); }); - it('uses the given requested teams', () => { - expect(toPullRequest(node(), ['wallet'])?.requestedTeams).toStrictEqual([ - 'wallet', - ]); + it('keeps requested teams and ignores requested users', () => { + const pullRequest = toPullRequest( + node({ + reviewRequests: { + nodes: [ + { requestedReviewer: { __typename: 'Team', slug: 'wallet' } }, + { requestedReviewer: { __typename: 'User' } }, + { requestedReviewer: null }, + ], + }, + }), + ); + expect(pullRequest?.requestedTeams).toStrictEqual(['wallet']); }); it('sets hasApproval when approved and nothing requests changes', () => { @@ -93,7 +102,6 @@ describe('toPullRequest', () => { nodes: states.map((state) => ({ state })), }, }), - [], )?.hasApproval; expect(result(['APPROVED'])).toBe(true); expect(result(['APPROVED', 'CHANGES_REQUESTED'])).toBe(false); @@ -106,18 +114,7 @@ describe('toPullRequest', () => { statusCheckRollup: { state: string } | null, ): boolean | undefined => toPullRequest( - node({ - commits: { - nodes: [ - { - commit: { - statusCheckRollup, - }, - }, - ], - }, - }), - [], + node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), )?.ciFailing; expect(rollup({ state: 'FAILURE' })).toBe(true); expect(rollup({ state: 'ERROR' })).toBe(true); @@ -127,26 +124,49 @@ describe('toPullRequest', () => { }); }); -/* eslint-disable @typescript-eslint/naming-convention */ -describe('collectRequestedTeams', () => { - it('maps PR numbers to requested team slugs across pages', () => { - const map = collectRequestedTeams([ - [{ number: 1, requested_teams: [{ slug: 'a' }, { slug: 'b' }] }], - [{ number: 2, requested_teams: [] }, { number: 3 }], +describe('toPullRequests', () => { + it('flattens pages and drops nodes that do not qualify', () => { + const pages: SearchPage[] = [ + { data: { search: { nodes: [node({ number: 1 }), {}] } } }, + { data: { search: { nodes: [node({ number: 2, isDraft: true })] } } }, + { data: { search: { nodes: [node({ number: 3 })] } } }, + ]; + expect(toPullRequests(pages).map(({ number }) => number)).toStrictEqual([ + 1, 3, ]); - expect(map.get(1)).toStrictEqual(['a', 'b']); - expect(map.get(2)).toStrictEqual([]); - expect(map.get(3)).toBeUndefined(); - expect(map.get(4)).toBeUndefined(); }); }); -/* eslint-enable @typescript-eslint/naming-convention */ - -describe('buildTopologyPath', () => { - it('encodes the ref', () => { - expect(buildTopologyPath('feat/a b#c')).toBe( - 'repos/MetaMask/MetaMask-planning/contents/topology.json?ref=feat%2Fa%20b%23c', +describe('buildSearchQuery', () => { + it('filters to open, non draft Dependabot pull requests', () => { + expect(buildSearchQuery('MetaMask/core')).toBe( + 'repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', ); }); }); + +describe('fetchDependabotPullRequests', () => { + it('needs a single gh call for a repository with one page of PRs', async () => { + const page: SearchPage = { + data: { search: { nodes: [node({ number: 11 })] } }, + }; + const run = vi + .fn<() => Promise>() + .mockResolvedValue(JSON.stringify([page])); + const pullRequests = await fetchDependabotPullRequests('MetaMask/core', { + environment: {}, + run, + }); + expect(pullRequests.map(({ number }) => number)).toStrictEqual([11]); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]).toStrictEqual([ + expect.arrayContaining([ + 'graphql', + '--paginate', + '--slurp', + `searchQuery=${buildSearchQuery('MetaMask/core')}`, + ]), + {}, + ]); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index d298f6e1..a1945219 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -162,3 +162,49 @@ describe('buildSlackPayload limits and lookup', () => { expect(payload?.text).toMatch(//u); }); }); + +describe('buildSlackPayload mentions and titles', () => { + const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; + const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + + it('does not turn @ text in titles into mentions', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr({ title: 'Bump @here/x' })] }, fallback }, + {}, + options, + ); + assert.ok(payload); + expect(payload).not.toHaveProperty('link_names'); + }); + + it('shortens long titles before wrapping them in a link', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr({ title: `${'x'.repeat(500)} & more` })] }, fallback }, + {}, + options, + ); + assert.ok(payload); + expect(payload.blocks[1]?.text.text).toMatch(/x…>$/u); + expect(payload.blocks[1]?.text.text).not.toContain('&'); + }); + + it('only pings teams whose section is shown', () => { + const byTeam: Reminder['byTeam'] = {}; + const topology: Record< + string, + { githubHandle: string; slackHandle: { team: string } } + > = {}; + for (let index = 0; index < 80; index++) { + byTeam[`team-${index}`] = [pr({ number: index + 1 })]; + topology[`t${index}`] = { + githubHandle: `MetaMask/team-${index}`, + slackHandle: { team: `S${index}` }, + }; + } + const payload = buildSlackPayload({ byTeam, fallback }, topology, options); + assert.ok(payload); + expect(payload.blocks).toHaveLength(50); + expect(payload.text).toContain(''); + expect(payload.text).not.toContain(''); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts index b05c5f35..ef19b528 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -1,15 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { - normalizeTeam, - parseOwnerTeams, -} from '../../dependabot-pr-reminder/teams.mts'; - -describe('normalizeTeam', () => { - it('lowercases and strips the @ and metamask/ prefixes', () => { - expect(normalizeTeam('@MetaMask/Core-Platform')).toBe('core-platform'); - }); -}); +import { parseOwnerTeams } from '../../dependabot-pr-reminder/teams.mts'; describe('parseOwnerTeams', () => { it('returns undefined for undefined, empty, and whitespace input', () => { diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 14c6e0b4..d85c40fd 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -1,5 +1,18 @@ name: Remind Dependabot PRs +# Posts a Slack message listing open Dependabot PRs grouped by owning team. +# +# Caller requirements: +# - Name the calling workflow `remind-dependabot-prs.yml`. +# - Grant the job `contents`, `pull-requests`, `checks` and `statuses` read +# and `id-token: write`. A reusable workflow's permissions are capped by +# the caller's. +# - Have the environment named by `environment` (default `default-branch`). +# Protection rules or required reviewers on it will block scheduled runs. +# - Define the `TOKEN_EXCHANGE_URL` variable, with a token exchange policy +# allowing `contents: read` on MetaMask/MetaMask-planning. +# - Pass the `slack-webhook-url` secret. +# # Note: the `@v1` references below only resolve after a github-tools release. # Pointing a caller at a branch ref is not enough for a pre-release smoke test: # this workflow also references `get-token@v1` and `remind-dependabot-prs@v1` @@ -23,6 +36,11 @@ on: type: string default: 'main' description: 'Git ref of MetaMask-planning to read topology.json from' + environment: + required: false + type: string + default: 'default-branch' + description: 'Environment the job runs in, used for the token exchange' secrets: slack-webhook-url: required: true @@ -32,7 +50,7 @@ jobs: remind: name: Remind Dependabot PRs runs-on: ubuntu-latest - environment: default-branch + environment: ${{ inputs.environment }} permissions: contents: read pull-requests: read @@ -59,24 +77,10 @@ jobs: fallback-team: ${{ inputs.fallback-team }} topology-ref: ${{ inputs.topology-ref }} - - name: Read Slack payload - if: steps.remind.outputs.has-prs == 'true' - id: payload - shell: bash - env: - PAYLOAD_PATH: ${{ steps.remind.outputs.payload-path }} - run: | - { - echo "payload<> "$GITHUB_OUTPUT" - - name: Send Slack notification if: steps.remind.outputs.has-prs == 'true' - uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 + uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1 with: webhook: ${{ secrets.slack-webhook-url }} webhook-type: incoming-webhook - payload: ${{ steps.payload.outputs.payload }} + payload-file-path: ${{ steps.remind.outputs.payload-path }} From 26c86be91245f65e9e0cda5d668f50b2326cbcd4 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 12:58:04 +0100 Subject: [PATCH 13/61] fix: tag teams with their Slack handle from topology Uses the handle in slackHandle.team as the mention, and no longer adds link_names. Tests use handles instead of made up IDs. --- .../dependabot-pr-reminder/slack-payload.mts | 23 ++++++++-------- .../slack-payload.test.mts | 26 +++++++++---------- 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 2a302c2f..722bda20 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -3,11 +3,10 @@ import { chunkSections, escapeSlack, section, - subteamMention, truncateText, } from '../shared/slack-blocks.mts'; import type { SlackBlock } from '../shared/slack-blocks.mts'; -import { getSlackSubteamId, normalizeTeamSlug } from '../shared/topology.mts'; +import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; @@ -60,21 +59,23 @@ export function buildSlackPayload( return undefined; } - const tag = (team: string): { text: string; subteamId?: string } => { - const subteamId = getSlackSubteamId(topology, team); - return subteamId - ? { text: subteamMention(subteamId), subteamId } + // A handle like `@core-platform-team` in message text becomes a mention. A + // team without one is shown as a plain name. + const tag = (team: string): { text: string; handle?: string } => { + const handle = getSlackHandle(topology, team); + return handle + ? { text: handle, handle } : { text: escapeSlack(normalizeTeamSlug(team)) }; }; const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; // Each section remembers its team mention, so only teams whose section is // actually sent get pinged. - const entries: { block: SlackBlock; subteamId?: string | undefined }[] = [ + const entries: { block: SlackBlock; handle?: string | undefined }[] = [ { block: section(headline) }, ]; const addSections = ( - header: { text: string; subteamId?: string }, + header: { text: string; handle?: string }, pullRequests: PullRequest[], label?: string, ): void => { @@ -83,7 +84,7 @@ export function buildSlackPayload( fullHeader, formatPullRequestLines(pullRequests), )) { - entries.push({ block: section(text), subteamId: header.subteamId }); + entries.push({ block: section(text), handle: header.handle }); } }; for (const [team, pullRequests] of teamEntries) { @@ -107,9 +108,7 @@ export function buildSlackPayload( const shownEntries = omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; const mentions = new Set( - shownEntries.flatMap(({ subteamId }) => - subteamId ? [subteamMention(subteamId)] : [], - ), + shownEntries.flatMap(({ handle }) => (handle ? [handle] : [])), ); return { text: [headline, ...mentions].join(' '), blocks }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index a1945219..0d1e2892 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -25,15 +25,15 @@ describe('buildSlackPayload', () => { { 'core-platform': { githubHandle: 'MetaMask/core-platform', - slackHandle: { team: 'S123' }, + slackHandle: { team: '@core-platform-team' }, }, }, options, ); assert.ok(payload); - expect(allText(payload)).toMatch(//u); + expect(allText(payload)).toMatch(/@core-platform-team/u); expect(allText(payload)).toMatch(/#7/u); - expect(payload.text).toMatch(//u); + expect(payload.text).toMatch(/@core-platform-team/u); expect(allText(payload)).not.toMatch(/:dependabot:/u); }); @@ -45,13 +45,13 @@ describe('buildSlackPayload', () => { { key: { githubHandle: '@MetaMask/Core-Platform', - slackHandle: { team: 'S9' }, + slackHandle: { team: '@nine-team' }, }, }, options, ); assert.ok(payload); - expect(allText(payload)).toMatch(//u); + expect(allText(payload)).toMatch(/@nine-team/u); }); it('falls back to the plain team name when topology has no match', () => { @@ -60,7 +60,7 @@ describe('buildSlackPayload', () => { const payload = buildSlackPayload(reminder, {}, options); assert.ok(payload); expect(allText(payload)).toMatch(/core-platform/u); - expect(allText(payload)).not.toMatch(/subteam\^/u); + expect(allText(payload)).not.toMatch(/@core-platform-team/u); }); it('escapes &, <, > in PR titles', () => { @@ -81,14 +81,14 @@ describe('buildSlackPayload', () => { { platform: { githubHandle: 'MetaMask/platform', - slackHandle: { team: 'SF' }, + slackHandle: { team: '@platform-team' }, }, }, options, ); assert.ok(payload); const text = allText(payload); - expect(text).toMatch(//u); + expect(text).toMatch(/@platform-team/u); expect(text).toMatch(/[Ff]ailing CI/u); expect(text).toMatch(/[Rr]eady to merge/u); expect(text).toMatch(/[Nn]eeds owner/u); @@ -155,11 +155,11 @@ describe('buildSlackPayload limits and lookup', () => { }, { bad: null, - good: { githubHandle: 'MetaMask/a', slackHandle: { team: 'S1' } }, + good: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, }, options, ); - expect(payload?.text).toMatch(//u); + expect(payload?.text).toMatch(/@a-team/u); }); }); @@ -198,13 +198,13 @@ describe('buildSlackPayload mentions and titles', () => { byTeam[`team-${index}`] = [pr({ number: index + 1 })]; topology[`t${index}`] = { githubHandle: `MetaMask/team-${index}`, - slackHandle: { team: `S${index}` }, + slackHandle: { team: `@g${index}` }, }; } const payload = buildSlackPayload({ byTeam, fallback }, topology, options); assert.ok(payload); expect(payload.blocks).toHaveLength(50); - expect(payload.text).toContain(''); - expect(payload.text).not.toContain(''); + expect(payload.text).toContain('@g0'); + expect(payload.text).not.toContain('@g79'); }); }); From ee081e85f86dd246ace04c3247c478802fa7d207 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 13:48:02 +0100 Subject: [PATCH 14/61] chore: drop the unused suppression and raise coverage thresholds --- oxlint-suppressions.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index e8bd94e7..9d795aba 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -9,11 +9,6 @@ "count": 1 } }, - ".github/scripts/dependabot-pr-reminder/cli.mts": { - "node/no-process-env": { - "count": 1 - } - }, ".github/scripts/generate-rc-commits.mjs": { "import/no-named-as-default": { "count": 1 From 831f226a8d80f1c67ed4ea67f2432640bab28aad Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:01:16 +0100 Subject: [PATCH 15/61] feat: list teams that share the same PRs once A PR requested from several teams was repeated under each of them. Teams with the same PR list now share one section with all of them tagged. --- .../dependabot-pr-reminder/slack-payload.mts | 54 ++++++++++++++---- .../slack-payload.test.mts | 57 +++++++++++++++++++ 2 files changed, 100 insertions(+), 11 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 722bda20..b3d379bc 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -26,6 +26,36 @@ function formatPullRequestLines(pullRequests: PullRequest[]): string[] { ); } +/** + * Merges teams that have the same pull requests, so a PR requested from + * several teams is listed once with all of them tagged. Groups keep the order + * in which their first team appears. + * + * @param teamEntries - Each team with its pull requests. + * @returns The groups of teams and the pull requests they share. + */ +function groupTeamsByPullRequests( + teamEntries: [string, PullRequest[]][], +): { teams: string[]; pullRequests: PullRequest[] }[] { + const groups = new Map< + string, + { teams: string[]; pullRequests: PullRequest[] } + >(); + for (const [team, pullRequests] of teamEntries) { + const key = pullRequests + .map(({ number }) => number) + .sort((left, right) => left - right) + .join(','); + const group = groups.get(key); + if (group) { + group.teams.push(team); + } else { + groups.set(key, { teams: [team], pullRequests }); + } + } + return [...groups.values()]; +} + /** * Builds the Slack incoming webhook payload for a reminder. * @@ -49,6 +79,7 @@ export function buildSlackPayload( const teamEntries = Object.entries(reminder.byTeam).filter( ([, pullRequests]) => pullRequests.length > 0, ); + const teamGroups = groupTeamsByPullRequests(teamEntries); const fallbackSections = [ { label: 'Failing CI', pullRequests: reminder.fallback.failingCi }, { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, @@ -71,27 +102,30 @@ export function buildSlackPayload( const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; // Each section remembers its team mention, so only teams whose section is // actually sent get pinged. - const entries: { block: SlackBlock; handle?: string | undefined }[] = [ - { block: section(headline) }, + const entries: { block: SlackBlock; handles: string[] }[] = [ + { block: section(headline), handles: [] }, ]; const addSections = ( - header: { text: string; handle?: string }, + teams: string[], pullRequests: PullRequest[], label?: string, ): void => { - const fullHeader = label ? `${header.text} *${label}*` : header.text; + const tags = teams.map(tag); + const header = tags.map(({ text }) => text).join(' '); + const fullHeader = label ? `${header} *${label}*` : header; + const handles = tags.flatMap(({ handle }) => (handle ? [handle] : [])); for (const text of chunkSections( fullHeader, formatPullRequestLines(pullRequests), )) { - entries.push({ block: section(text), handle: header.handle }); + entries.push({ block: section(text), handles }); } }; - for (const [team, pullRequests] of teamEntries) { - addSections(tag(team), pullRequests); + for (const { teams, pullRequests } of teamGroups) { + addSections(teams, pullRequests); } for (const { label, pullRequests } of fallbackSections) { - addSections(tag(options.fallbackTeam), pullRequests, label); + addSections([options.fallbackTeam], pullRequests, label); } const { blocks, omitted } = capBlocks( @@ -107,9 +141,7 @@ export function buildSlackPayload( ); const shownEntries = omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; - const mentions = new Set( - shownEntries.flatMap(({ handle }) => (handle ? [handle] : [])), - ); + const mentions = new Set(shownEntries.flatMap(({ handles }) => handles)); return { text: [headline, ...mentions].join(' '), blocks }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 0d1e2892..5bb7a7f7 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -208,3 +208,60 @@ describe('buildSlackPayload mentions and titles', () => { expect(payload.text).not.toContain('@g79'); }); }); + +describe('buildSlackPayload grouping', () => { + const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; + const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + const topology = { + a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, + b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, + }; + + it('lists a shared set of PRs once under all of its teams', () => { + const shared = [pr({ number: 1 }), pr({ number: 2 })]; + const payload = buildSlackPayload( + { + byTeam: { a: shared, b: [pr({ number: 2 }), pr({ number: 1 })] }, + fallback, + }, + topology, + options, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(2); + const [, sharedBlock] = payload.blocks; + expect(sharedBlock?.text.text.split('\n')[0]).toBe('@a-team @b-team'); + expect(sharedBlock?.text.text.match(/#1 /gu)).toHaveLength(1); + expect(payload.text).toContain('@a-team @b-team'); + }); + + it('keeps teams with different PRs in separate sections', () => { + const payload = buildSlackPayload( + { + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 2 })], + }, + fallback, + }, + topology, + options, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(3); + expect(payload.blocks[1]?.text.text.startsWith('@a-team\n')).toBe(true); + expect(payload.blocks[2]?.text.text.startsWith('@b-team\n')).toBe(true); + }); + + it('shows a team without a handle as plain text next to tagged teams', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr()], plain: [pr()] }, fallback }, + topology, + options, + ); + assert.ok(payload); + expect(payload.blocks[1]?.text.text.split('\n')[0]).toBe('@a-team plain'); + expect(payload.text).toContain('@a-team'); + expect(payload.text).not.toContain('plain'); + }); +}); From b1f0057043ea9da370558e4d2724d2045e13d24a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:23:37 +0100 Subject: [PATCH 16/61] feat: add a closing note to the Dependabot reminder A reminder-note input (workflow and action) sets a small note at the end of the message, so teams see what they own each time. It has a generic default, empty turns it off, and one block slot is kept free for it. --- .../actions/remind-dependabot-prs/action.yml | 5 ++ .../scripts/dependabot-pr-reminder/cli.mts | 2 + .../dependabot-pr-reminder/slack-payload.mts | 38 +++++++- .../tests/dependabot-pr-reminder/fixtures.mts | 11 +++ .../slack-payload.test.mts | 86 ++++++++++++++++--- .github/workflows/remind-dependabot-prs.yml | 6 ++ 6 files changed, 135 insertions(+), 13 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 15d0a995..ea02ac00 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -20,6 +20,10 @@ inputs: description: 'Git ref of MetaMask-planning to read topology.json from.' required: false default: 'main' + reminder-note: + description: 'Note shown at the end of the message, as Slack mrkdwn. Empty for none.' + required: false + default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' outputs: has-prs: @@ -48,6 +52,7 @@ runs: OWNER_TEAMS: ${{ inputs.owner-teams }} FALLBACK_TEAM: ${{ inputs.fallback-team }} TOPOLOGY_REF: ${{ inputs.topology-ref }} + REMINDER_NOTE: ${{ inputs.reminder-note }} run: | set -euo pipefail node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 0e352029..784ed2d5 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -63,9 +63,11 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { ); } + const note = environment.REMINDER_NOTE?.trim(); const payload = buildSlackPayload(reminder, topology, { fallbackTeam, repository, + ...(note ? { note } : {}), }); if (!payload) { console.log('No open Dependabot pull requests to report.'); diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index b3d379bc..1225943c 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,4 +1,6 @@ import { + MAX_BLOCKS, + MAX_SECTION_LENGTH, capBlocks, chunkSections, escapeSlack, @@ -10,6 +12,15 @@ import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; +/** A small grey Slack block, used for the closing note. */ +export type ContextBlock = { + type: 'context'; + elements: { type: 'mrkdwn'; text: string }[]; +}; + +/** Any block in the payload. */ +export type ReminderBlock = SlackBlock | ContextBlock; + /** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; @@ -64,16 +75,18 @@ function groupTeamsByPullRequests( * @param options - Payload options. * @param options.fallbackTeam - The team tagged on the fallback sections. * @param options.repository - The repository name shown in the header. + * @param options.note - Text shown in a closing note, as Slack mrkdwn. Left out + * when empty. * @returns The payload, or undefined when there is nothing to post. */ export function buildSlackPayload( reminder: Reminder, topology: Topology, - options: { fallbackTeam: string; repository: string }, + options: { fallbackTeam: string; repository: string; note?: string }, ): | { text: string; - blocks: SlackBlock[]; + blocks: ReminderBlock[]; } | undefined { const teamEntries = Object.entries(reminder.byTeam).filter( @@ -138,10 +151,29 @@ export function buildSlackPayload( .length, 0, )} more pull request(s) not shown`, + // Keep a slot free for the closing note, so the cap can't cut it off. + options.note ? MAX_BLOCKS - 1 : MAX_BLOCKS, ); const shownEntries = omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; const mentions = new Set(shownEntries.flatMap(({ handles }) => handles)); - return { text: [headline, ...mentions].join(' '), blocks }; + const noteBlock: ContextBlock[] = options.note + ? [ + { + type: 'context', + elements: [ + { + type: 'mrkdwn', + text: truncateText(options.note, MAX_SECTION_LENGTH), + }, + ], + }, + ] + : []; + + return { + text: [headline, ...mentions].join(' '), + blocks: [...blocks, ...noteBlock], + }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index ca0baaaa..b9ef311f 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -1,3 +1,4 @@ +import type { ReminderBlock } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; /** @@ -17,3 +18,13 @@ export function pr(overrides: Partial = {}): PullRequest { ...overrides, }; } + +/** + * Reads the text of a section block. + * + * @param block - The block, if any. + * @returns The text, or an empty string for other kinds of block. + */ +export function sectionText(block: ReminderBlock | undefined): string { + return block && 'text' in block ? block.text.text : ''; +} diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 5bb7a7f7..214ffa5e 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -2,7 +2,7 @@ import { assert, describe, expect, it } from 'vitest'; import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { Reminder } from '../../dependabot-pr-reminder/types.mts'; -import { pr } from './fixtures.mts'; +import { pr, sectionText } from './fixtures.mts'; describe('buildSlackPayload', () => { const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; @@ -117,7 +117,7 @@ describe('buildSlackPayload chunking', () => { { fallbackTeam: 'f', repository: 'MetaMask/example' }, ); assert.ok(payload); - const texts = payload.blocks.map((block) => block.text.text); + const texts = payload.blocks.map(sectionText); expect(texts.length).toBeGreaterThan(3); for (const text of texts) { assert.ok(text.length <= 3000, `section has ${text.length} characters`); @@ -144,7 +144,7 @@ describe('buildSlackPayload limits and lookup', () => { ); assert.ok(payload); expect(payload.blocks.length).toBeLessThanOrEqual(50); - expect(payload.blocks.at(-1)?.text.text).toMatch(/…and \d+ more/u); + expect(sectionText(payload.blocks.at(-1))).toMatch(/…and \d+ more/u); }); it('does not throw on null topology entries', () => { @@ -184,8 +184,8 @@ describe('buildSlackPayload mentions and titles', () => { options, ); assert.ok(payload); - expect(payload.blocks[1]?.text.text).toMatch(/x…>$/u); - expect(payload.blocks[1]?.text.text).not.toContain('&'); + expect(sectionText(payload.blocks[1])).toMatch(/x…>$/u); + expect(sectionText(payload.blocks[1])).not.toContain('&'); }); it('only pings teams whose section is shown', () => { @@ -230,8 +230,8 @@ describe('buildSlackPayload grouping', () => { assert.ok(payload); expect(payload.blocks).toHaveLength(2); const [, sharedBlock] = payload.blocks; - expect(sharedBlock?.text.text.split('\n')[0]).toBe('@a-team @b-team'); - expect(sharedBlock?.text.text.match(/#1 /gu)).toHaveLength(1); + expect(sectionText(sharedBlock).split('\n')[0]).toBe('@a-team @b-team'); + expect(sectionText(sharedBlock).match(/#1 /gu)).toHaveLength(1); expect(payload.text).toContain('@a-team @b-team'); }); @@ -249,8 +249,8 @@ describe('buildSlackPayload grouping', () => { ); assert.ok(payload); expect(payload.blocks).toHaveLength(3); - expect(payload.blocks[1]?.text.text.startsWith('@a-team\n')).toBe(true); - expect(payload.blocks[2]?.text.text.startsWith('@b-team\n')).toBe(true); + expect(sectionText(payload.blocks[1]).startsWith('@a-team\n')).toBe(true); + expect(sectionText(payload.blocks[2]).startsWith('@b-team\n')).toBe(true); }); it('shows a team without a handle as plain text next to tagged teams', () => { @@ -260,8 +260,74 @@ describe('buildSlackPayload grouping', () => { options, ); assert.ok(payload); - expect(payload.blocks[1]?.text.text.split('\n')[0]).toBe('@a-team plain'); + expect(sectionText(payload.blocks[1]).split('\n')[0]).toBe('@a-team plain'); expect(payload.text).toContain('@a-team'); expect(payload.text).not.toContain('plain'); }); }); + +describe('buildSlackPayload closing note', () => { + const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + + it('adds the note as a last context block', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr()] }, fallback }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example', note: 'Own it.' }, + ); + assert.ok(payload); + expect(payload.blocks.at(-1)).toStrictEqual({ + type: 'context', + elements: [{ type: 'mrkdwn', text: 'Own it.' }], + }); + }); + + it('leaves the note out when there is none', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr()] }, fallback }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + expect(payload.blocks.map(({ type }) => type)).toStrictEqual([ + 'section', + 'section', + ]); + }); + + it('keeps the note when the block cap is hit', () => { + const byTeam: Reminder['byTeam'] = {}; + for (let index = 0; index < 80; index++) { + byTeam[`team-${index}`] = [pr({ number: index + 1 })]; + } + const payload = buildSlackPayload( + { byTeam, fallback }, + {}, + { + fallbackTeam: 'f', + repository: 'MetaMask/example', + note: 'Own it.', + }, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(50); + expect(payload.blocks.at(-1)?.type).toBe('context'); + expect(sectionText(payload.blocks.at(-2))).toMatch(/…and \d+ more/u); + }); + + it('cuts a very long note to fit Slack', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr()] }, fallback }, + {}, + { + fallbackTeam: 'f', + repository: 'MetaMask/example', + note: 'x'.repeat(5000), + }, + ); + assert.ok(payload); + const serialized = JSON.stringify(payload.blocks.at(-1)); + expect(serialized).toContain('…'); + expect(serialized.length).toBeLessThan(2900); + }); +}); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index d85c40fd..4cd58e4b 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -36,6 +36,11 @@ on: type: string default: 'main' description: 'Git ref of MetaMask-planning to read topology.json from' + reminder-note: + required: false + type: string + default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' + description: 'Note shown at the end of the message, as Slack mrkdwn. Empty for none' environment: required: false type: string @@ -76,6 +81,7 @@ jobs: owner-teams: ${{ inputs.owner-teams }} fallback-team: ${{ inputs.fallback-team }} topology-ref: ${{ inputs.topology-ref }} + reminder-note: ${{ inputs.reminder-note }} - name: Send Slack notification if: steps.remind.outputs.has-prs == 'true' From 20b1ba0aae7e0fea4507aceafa27a6d535ff517a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:28:45 +0100 Subject: [PATCH 17/61] fix: show the reminder note at normal size Context blocks render small and grey in Slack, so use a section block. --- .../dependabot-pr-reminder/slack-payload.mts | 25 +++---------------- .../tests/dependabot-pr-reminder/fixtures.mts | 8 +++--- .../slack-payload.test.mts | 8 +++--- 3 files changed, 11 insertions(+), 30 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 1225943c..aeb6042b 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -12,15 +12,6 @@ import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; -/** A small grey Slack block, used for the closing note. */ -export type ContextBlock = { - type: 'context'; - elements: { type: 'mrkdwn'; text: string }[]; -}; - -/** Any block in the payload. */ -export type ReminderBlock = SlackBlock | ContextBlock; - /** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; @@ -86,7 +77,7 @@ export function buildSlackPayload( ): | { text: string; - blocks: ReminderBlock[]; + blocks: SlackBlock[]; } | undefined { const teamEntries = Object.entries(reminder.byTeam).filter( @@ -158,18 +149,8 @@ export function buildSlackPayload( omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; const mentions = new Set(shownEntries.flatMap(({ handles }) => handles)); - const noteBlock: ContextBlock[] = options.note - ? [ - { - type: 'context', - elements: [ - { - type: 'mrkdwn', - text: truncateText(options.note, MAX_SECTION_LENGTH), - }, - ], - }, - ] + const noteBlock = options.note + ? [section(truncateText(options.note, MAX_SECTION_LENGTH))] : []; return { diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index b9ef311f..3d524526 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -1,5 +1,5 @@ -import type { ReminderBlock } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; +import type { SlackBlock } from '../../shared/slack-blocks.mts'; /** * Builds a pull request for tests. @@ -23,8 +23,8 @@ export function pr(overrides: Partial = {}): PullRequest { * Reads the text of a section block. * * @param block - The block, if any. - * @returns The text, or an empty string for other kinds of block. + * @returns The text, or an empty string when there is no block. */ -export function sectionText(block: ReminderBlock | undefined): string { - return block && 'text' in block ? block.text.text : ''; +export function sectionText(block: SlackBlock | undefined): string { + return block?.text.text ?? ''; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 214ffa5e..9364f59f 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -269,7 +269,7 @@ describe('buildSlackPayload grouping', () => { describe('buildSlackPayload closing note', () => { const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; - it('adds the note as a last context block', () => { + it('adds the note as a last section block', () => { const payload = buildSlackPayload( { byTeam: { a: [pr()] }, fallback }, {}, @@ -277,8 +277,8 @@ describe('buildSlackPayload closing note', () => { ); assert.ok(payload); expect(payload.blocks.at(-1)).toStrictEqual({ - type: 'context', - elements: [{ type: 'mrkdwn', text: 'Own it.' }], + type: 'section', + text: { type: 'mrkdwn', text: 'Own it.' }, }); }); @@ -311,7 +311,7 @@ describe('buildSlackPayload closing note', () => { ); assert.ok(payload); expect(payload.blocks).toHaveLength(50); - expect(payload.blocks.at(-1)?.type).toBe('context'); + expect(sectionText(payload.blocks.at(-1))).toBe('Own it.'); expect(sectionText(payload.blocks.at(-2))).toMatch(/…and \d+ more/u); }); From 67719e6ec6a0db2106a224554df6195ba117089b Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:31:04 +0100 Subject: [PATCH 18/61] feat: show the reminder note under the headline It is read first there, and the block cap can no longer cut it off. --- .../actions/remind-dependabot-prs/action.yml | 2 +- .../dependabot-pr-reminder/slack-payload.mts | 21 +++++++++++-------- .../slack-payload.test.mts | 12 +++++------ .github/workflows/remind-dependabot-prs.yml | 2 +- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index ea02ac00..e33a1cb2 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -21,7 +21,7 @@ inputs: required: false default: 'main' reminder-note: - description: 'Note shown at the end of the message, as Slack mrkdwn. Empty for none.' + description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none.' required: false default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index aeb6042b..11f6d471 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,5 +1,4 @@ import { - MAX_BLOCKS, MAX_SECTION_LENGTH, capBlocks, chunkSections, @@ -66,7 +65,7 @@ function groupTeamsByPullRequests( * @param options - Payload options. * @param options.fallbackTeam - The team tagged on the fallback sections. * @param options.repository - The repository name shown in the header. - * @param options.note - Text shown in a closing note, as Slack mrkdwn. Left out + * @param options.note - Text shown right under the headline, as Slack mrkdwn. Left out * when empty. * @returns The payload, or undefined when there is nothing to post. */ @@ -106,8 +105,18 @@ export function buildSlackPayload( const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; // Each section remembers its team mention, so only teams whose section is // actually sent get pinged. + // The note goes right under the headline. The block cap only cuts from the + // end, so it is always shown. const entries: { block: SlackBlock; handles: string[] }[] = [ { block: section(headline), handles: [] }, + ...(options.note + ? [ + { + block: section(truncateText(options.note, MAX_SECTION_LENGTH)), + handles: [], + }, + ] + : []), ]; const addSections = ( teams: string[], @@ -142,19 +151,13 @@ export function buildSlackPayload( .length, 0, )} more pull request(s) not shown`, - // Keep a slot free for the closing note, so the cap can't cut it off. - options.note ? MAX_BLOCKS - 1 : MAX_BLOCKS, ); const shownEntries = omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; const mentions = new Set(shownEntries.flatMap(({ handles }) => handles)); - const noteBlock = options.note - ? [section(truncateText(options.note, MAX_SECTION_LENGTH))] - : []; - return { text: [headline, ...mentions].join(' '), - blocks: [...blocks, ...noteBlock], + blocks, }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 9364f59f..1b7ca53b 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -266,17 +266,17 @@ describe('buildSlackPayload grouping', () => { }); }); -describe('buildSlackPayload closing note', () => { +describe('buildSlackPayload note', () => { const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; - it('adds the note as a last section block', () => { + it('adds the note as a section right under the headline', () => { const payload = buildSlackPayload( { byTeam: { a: [pr()] }, fallback }, {}, { fallbackTeam: 'f', repository: 'MetaMask/example', note: 'Own it.' }, ); assert.ok(payload); - expect(payload.blocks.at(-1)).toStrictEqual({ + expect(payload.blocks[1]).toStrictEqual({ type: 'section', text: { type: 'mrkdwn', text: 'Own it.' }, }); @@ -311,8 +311,8 @@ describe('buildSlackPayload closing note', () => { ); assert.ok(payload); expect(payload.blocks).toHaveLength(50); - expect(sectionText(payload.blocks.at(-1))).toBe('Own it.'); - expect(sectionText(payload.blocks.at(-2))).toMatch(/…and \d+ more/u); + expect(sectionText(payload.blocks[1])).toBe('Own it.'); + expect(sectionText(payload.blocks.at(-1))).toMatch(/…and \d+ more/u); }); it('cuts a very long note to fit Slack', () => { @@ -326,7 +326,7 @@ describe('buildSlackPayload closing note', () => { }, ); assert.ok(payload); - const serialized = JSON.stringify(payload.blocks.at(-1)); + const serialized = JSON.stringify(payload.blocks[1]); expect(serialized).toContain('…'); expect(serialized.length).toBeLessThan(2900); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 4cd58e4b..ce3aeece 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -40,7 +40,7 @@ on: required: false type: string default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' - description: 'Note shown at the end of the message, as Slack mrkdwn. Empty for none' + description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none' environment: required: false type: string From 6b5f80cbb3613b2892953cd411924c54198d3d17 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:33:09 +0100 Subject: [PATCH 19/61] feat: keep failing CI PRs with their teams and show a CI icon on each PR Teams fix their own failing CI, so those PRs are no longer moved to the fallback team. Each PR gets a green, red, yellow or white circle for its CI state instead. --- .../dependabot-pr-reminder/classify.mts | 13 ++--- .../dependabot-pr-reminder/github-api.mts | 22 +++++++- .../dependabot-pr-reminder/slack-payload.mts | 13 ++++- .../scripts/dependabot-pr-reminder/types.mts | 3 +- .../dependabot-pr-reminder/classify.test.mts | 14 +++-- .../tests/dependabot-pr-reminder/fixtures.mts | 2 +- .../github-api.test.mts | 19 ++++--- .../slack-payload.test.mts | 56 +++++++++++++++---- 8 files changed, 103 insertions(+), 39 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 95fb2225..deb8824d 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -4,9 +4,9 @@ import type { PullRequest, Reminder } from './types.mts'; /** * Sorts pull requests into per-team groups and fallback buckets. * - * Failing CI goes to the fallback bucket first, then PRs with remaining - * requested teams are grouped by team, then approved PRs are ready to merge, - * and anything else needs an owner. + * PRs with remaining requested teams are grouped by team, whatever their CI + * state, since the owning team is the one that fixes it. PRs with no team left + * are ready to merge when approved, and otherwise need an owner. * * @param pullRequests - The open Dependabot pull requests. * @param options - Classification options. @@ -21,15 +21,10 @@ export function classifyPullRequests( const ownerTeams = options.ownerTeams?.map(normalizeTeamSlug); const reminder: Reminder = { byTeam: {}, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + fallback: { readyToMerge: [], needsOwner: [] }, }; for (const pullRequest of pullRequests) { - if (pullRequest.ciFailing) { - reminder.fallback.failingCi.push(pullRequest); - continue; - } - const teams = pullRequest.requestedTeams .map(normalizeTeamSlug) .filter((team) => !ownerTeams || ownerTeams.includes(team)); diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 196fac34..f689acb1 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -62,6 +62,26 @@ export function buildSearchQuery(repository: string): string { return `repo:${repository} is:pr is:open draft:false author:app/dependabot`; } +/** + * Maps a commit status rollup to a CI state. + * + * @param rollupState - The GraphQL rollup state, or null when there are no + * checks. + * @returns The CI state. + */ +function toCiState(rollupState: string | null): PullRequest['ciState'] { + if (rollupState === 'SUCCESS') { + return 'passing'; + } + if (rollupState === 'FAILURE' || rollupState === 'ERROR') { + return 'failing'; + } + if (rollupState === 'PENDING' || rollupState === 'EXPECTED') { + return 'pending'; + } + return 'unknown'; +} + /** * Maps a search node to a PullRequest. * @@ -106,7 +126,7 @@ export function toPullRequest( hasApproval: reviewStates.includes('APPROVED') && !reviewStates.includes('CHANGES_REQUESTED'), - ciFailing: rollupState === 'FAILURE' || rollupState === 'ERROR', + ciState: toCiState(rollupState), }; } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 11f6d471..f47bffd3 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -14,6 +14,14 @@ import type { PullRequest, Reminder } from './types.mts'; /** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; +/** Shown in front of each PR to tell its CI state at a glance. */ +const CI_ICONS: Record = { + passing: ':large_green_circle:', + failing: ':red_circle:', + pending: ':large_yellow_circle:', + unknown: ':white_circle:', +}; + /** * Formats pull requests as bulleted Slack links, one line each. * @@ -22,8 +30,8 @@ const MAX_TITLE_LENGTH = 200; */ function formatPullRequestLines(pullRequests: PullRequest[]): string[] { return pullRequests.map( - ({ url, number, title }) => - `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, + ({ url, number, title, ciState }) => + `• ${CI_ICONS[ciState]} <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, ); } @@ -84,7 +92,6 @@ export function buildSlackPayload( ); const teamGroups = groupTeamsByPullRequests(teamEntries); const fallbackSections = [ - { label: 'Failing CI', pullRequests: reminder.fallback.failingCi }, { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, { label: 'Needs owner', pullRequests: reminder.fallback.needsOwner }, ].filter(({ pullRequests }) => pullRequests.length > 0); diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 2e90e0f4..59d789da 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -4,13 +4,12 @@ export type PullRequest = { url: string; requestedTeams: string[]; hasApproval: boolean; - ciFailing: boolean; + ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; export type Reminder = { byTeam: Record; fallback: { - failingCi: PullRequest[]; readyToMerge: PullRequest[]; needsOwner: PullRequest[]; }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 60cf5027..6aa66b55 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -11,11 +11,17 @@ describe('classifyPullRequests', () => { expect(result.byTeam.b).toStrictEqual([pullRequest]); }); - it('lists failing CI PRs under fallback only', () => { - const pullRequest = pr({ ciFailing: true, requestedTeams: ['a'] }); + it('keeps a failing CI PR under its team, since the team fixes it', () => { + const pullRequest = pr({ ciState: 'failing', requestedTeams: ['a'] }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.fallback.failingCi).toStrictEqual([pullRequest]); - expect(result.byTeam).toStrictEqual({}); + expect(result.byTeam.a).toStrictEqual([pullRequest]); + expect(result.fallback.needsOwner).toStrictEqual([]); + }); + + it('lists a failing CI PR with no team as needs owner', () => { + const pullRequest = pr({ ciState: 'failing' }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + expect(result.fallback.needsOwner).toStrictEqual([pullRequest]); }); it('lists approved PRs with no teams left as ready to merge', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index 3d524526..2321f902 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -14,7 +14,7 @@ export function pr(overrides: Partial = {}): PullRequest { url: 'https://github.com/MetaMask/example/pull/1', requestedTeams: [], hasApproval: false, - ciFailing: false, + ciState: 'unknown', ...overrides, }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index 7c733c8a..ccf894ac 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -75,7 +75,7 @@ describe('toPullRequest', () => { url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], hasApproval: false, - ciFailing: false, + ciState: 'unknown', }); }); @@ -109,18 +109,19 @@ describe('toPullRequest', () => { expect(result([])).toBe(false); }); - it('sets ciFailing only for FAILURE and ERROR', () => { + it('maps the status rollup to a CI state', () => { const rollup = ( statusCheckRollup: { state: string } | null, - ): boolean | undefined => + ): string | undefined => toPullRequest( node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), - )?.ciFailing; - expect(rollup({ state: 'FAILURE' })).toBe(true); - expect(rollup({ state: 'ERROR' })).toBe(true); - expect(rollup({ state: 'PENDING' })).toBe(false); - expect(rollup({ state: 'SUCCESS' })).toBe(false); - expect(rollup(null)).toBe(false); + )?.ciState; + expect(rollup({ state: 'SUCCESS' })).toBe('passing'); + expect(rollup({ state: 'FAILURE' })).toBe('failing'); + expect(rollup({ state: 'ERROR' })).toBe('failing'); + expect(rollup({ state: 'PENDING' })).toBe('pending'); + expect(rollup({ state: 'EXPECTED' })).toBe('pending'); + expect(rollup(null)).toBe('unknown'); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 1b7ca53b..23ada2a8 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -8,7 +8,7 @@ describe('buildSlackPayload', () => { const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; const emptyReminder = (): Reminder => ({ byTeam: {}, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + fallback: { readyToMerge: [], needsOwner: [] }, }); const allText = (payload: { text: string; blocks: unknown[] }): string => `${payload.text}\n${JSON.stringify(payload.blocks)}`; @@ -73,7 +73,6 @@ describe('buildSlackPayload', () => { it('renders fallback sections under the fallback team', () => { const reminder = emptyReminder(); - reminder.fallback.failingCi = [pr({ number: 1 })]; reminder.fallback.readyToMerge = [pr({ number: 2 })]; reminder.fallback.needsOwner = [pr({ number: 3 })]; const payload = buildSlackPayload( @@ -89,10 +88,8 @@ describe('buildSlackPayload', () => { assert.ok(payload); const text = allText(payload); expect(text).toMatch(/@platform-team/u); - expect(text).toMatch(/[Ff]ailing CI/u); expect(text).toMatch(/[Rr]eady to merge/u); expect(text).toMatch(/[Nn]eeds owner/u); - expect(text).toMatch(/#1/u); expect(text).toMatch(/#2/u); expect(text).toMatch(/#3/u); }); @@ -109,7 +106,7 @@ describe('buildSlackPayload chunking', () => { ); const reminder: Reminder = { byTeam: { wallet: pullRequests }, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + fallback: { readyToMerge: [], needsOwner: [] }, }; const payload = buildSlackPayload( reminder, @@ -138,7 +135,7 @@ describe('buildSlackPayload limits and lookup', () => { byTeam[`team-${index}`] = [pr({ number: index + 1 })]; } const payload = buildSlackPayload( - { byTeam, fallback: { failingCi: [], readyToMerge: [], needsOwner: [] } }, + { byTeam, fallback: { readyToMerge: [], needsOwner: [] } }, {}, options, ); @@ -151,7 +148,7 @@ describe('buildSlackPayload limits and lookup', () => { const payload = buildSlackPayload( { byTeam: { a: [pr()] }, - fallback: { failingCi: [], readyToMerge: [], needsOwner: [] }, + fallback: { readyToMerge: [], needsOwner: [] }, }, { bad: null, @@ -165,7 +162,7 @@ describe('buildSlackPayload limits and lookup', () => { describe('buildSlackPayload mentions and titles', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + const fallback = { readyToMerge: [], needsOwner: [] }; it('does not turn @ text in titles into mentions', () => { const payload = buildSlackPayload( @@ -211,7 +208,7 @@ describe('buildSlackPayload mentions and titles', () => { describe('buildSlackPayload grouping', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + const fallback = { readyToMerge: [], needsOwner: [] }; const topology = { a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, @@ -267,7 +264,7 @@ describe('buildSlackPayload grouping', () => { }); describe('buildSlackPayload note', () => { - const fallback = { failingCi: [], readyToMerge: [], needsOwner: [] }; + const fallback = { readyToMerge: [], needsOwner: [] }; it('adds the note as a section right under the headline', () => { const payload = buildSlackPayload( @@ -331,3 +328,42 @@ describe('buildSlackPayload note', () => { expect(serialized.length).toBeLessThan(2900); }); }); + +describe('buildSlackPayload CI icons', () => { + const fallback = { readyToMerge: [], needsOwner: [] }; + + it('puts an icon for the CI state in front of each PR', () => { + const payload = buildSlackPayload( + { + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'pending' }), + pr({ number: 4, ciState: 'unknown' }), + ], + }, + fallback, + }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + const lines = sectionText(payload.blocks[1]).split('\n'); + expect(lines[1]).toMatch(/^• :large_green_circle: .*#1 /u); + expect(lines[2]).toMatch(/^• :red_circle: .*#2 /u); + expect(lines[3]).toMatch(/^• :large_yellow_circle: .*#3 /u); + expect(lines[4]).toMatch(/^• :white_circle: .*#4 /u); + }); + + it('lists a failing CI PR under its own team and not under the fallback', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr({ ciState: 'failing' })] }, fallback }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(2); + expect(sectionText(payload.blocks[1]).startsWith('a\n')).toBe(true); + }); +}); From 344650e22fbdeb1132ab452206837280b21a67bb Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:43:43 +0100 Subject: [PATCH 20/61] refactor: drop CI status from the Dependabot reminder Teams check CI themselves, so the reminder no longer reads or shows it. This also removes the commit status field from the GraphQL query. --- .../dependabot-pr-reminder/github-api.mts | 27 ------------- .../dependabot-pr-reminder/slack-payload.mts | 12 +----- .../scripts/dependabot-pr-reminder/types.mts | 1 - .../dependabot-pr-reminder/classify.test.mts | 13 ------- .../tests/dependabot-pr-reminder/fixtures.mts | 1 - .../github-api.test.mts | 17 -------- .../slack-payload.test.mts | 39 ------------------- 7 files changed, 2 insertions(+), 108 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index f689acb1..c9fe4fc0 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -14,9 +14,6 @@ export type GraphQlPullRequestNode = { }[]; }; latestOpinionatedReviews: { nodes: { state: string }[] }; - commits: { - nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; - }; }; /** A page of search results. Nodes that are not pull requests come back empty. */ @@ -46,7 +43,6 @@ query($searchQuery: String!, $endCursor: String) { nodes { requestedReviewer { __typename ... on Team { slug } } } } latestOpinionatedReviews(first: 20) { nodes { state } } - commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } } } } @@ -62,26 +58,6 @@ export function buildSearchQuery(repository: string): string { return `repo:${repository} is:pr is:open draft:false author:app/dependabot`; } -/** - * Maps a commit status rollup to a CI state. - * - * @param rollupState - The GraphQL rollup state, or null when there are no - * checks. - * @returns The CI state. - */ -function toCiState(rollupState: string | null): PullRequest['ciState'] { - if (rollupState === 'SUCCESS') { - return 'passing'; - } - if (rollupState === 'FAILURE' || rollupState === 'ERROR') { - return 'failing'; - } - if (rollupState === 'PENDING' || rollupState === 'EXPECTED') { - return 'pending'; - } - return 'unknown'; -} - /** * Maps a search node to a PullRequest. * @@ -107,8 +83,6 @@ export function toPullRequest( return undefined; } - const rollupState = - node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; const reviewStates = node.latestOpinionatedReviews.nodes.map( ({ state }) => state, ); @@ -126,7 +100,6 @@ export function toPullRequest( hasApproval: reviewStates.includes('APPROVED') && !reviewStates.includes('CHANGES_REQUESTED'), - ciState: toCiState(rollupState), }; } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index f47bffd3..49b6e8ab 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -14,14 +14,6 @@ import type { PullRequest, Reminder } from './types.mts'; /** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; -/** Shown in front of each PR to tell its CI state at a glance. */ -const CI_ICONS: Record = { - passing: ':large_green_circle:', - failing: ':red_circle:', - pending: ':large_yellow_circle:', - unknown: ':white_circle:', -}; - /** * Formats pull requests as bulleted Slack links, one line each. * @@ -30,8 +22,8 @@ const CI_ICONS: Record = { */ function formatPullRequestLines(pullRequests: PullRequest[]): string[] { return pullRequests.map( - ({ url, number, title, ciState }) => - `• ${CI_ICONS[ciState]} <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, + ({ url, number, title }) => + `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, ); } diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 59d789da..0b70e1af 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -4,7 +4,6 @@ export type PullRequest = { url: string; requestedTeams: string[]; hasApproval: boolean; - ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; export type Reminder = { diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 6aa66b55..90774548 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -11,19 +11,6 @@ describe('classifyPullRequests', () => { expect(result.byTeam.b).toStrictEqual([pullRequest]); }); - it('keeps a failing CI PR under its team, since the team fixes it', () => { - const pullRequest = pr({ ciState: 'failing', requestedTeams: ['a'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.byTeam.a).toStrictEqual([pullRequest]); - expect(result.fallback.needsOwner).toStrictEqual([]); - }); - - it('lists a failing CI PR with no team as needs owner', () => { - const pullRequest = pr({ ciState: 'failing' }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.fallback.needsOwner).toStrictEqual([pullRequest]); - }); - it('lists approved PRs with no teams left as ready to merge', () => { const pullRequest = pr({ requestedTeams: [], hasApproval: true }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index 2321f902..b4dffcaa 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -14,7 +14,6 @@ export function pr(overrides: Partial = {}): PullRequest { url: 'https://github.com/MetaMask/example/pull/1', requestedTeams: [], hasApproval: false, - ciState: 'unknown', ...overrides, }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index ccf894ac..d94e349f 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -28,7 +28,6 @@ function node( author: { __typename: 'Bot', login: 'dependabot' }, reviewRequests: { nodes: [] }, latestOpinionatedReviews: { nodes: [] }, - commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, ...overrides, }; } @@ -75,7 +74,6 @@ describe('toPullRequest', () => { url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], hasApproval: false, - ciState: 'unknown', }); }); @@ -108,21 +106,6 @@ describe('toPullRequest', () => { expect(result(['CHANGES_REQUESTED'])).toBe(false); expect(result([])).toBe(false); }); - - it('maps the status rollup to a CI state', () => { - const rollup = ( - statusCheckRollup: { state: string } | null, - ): string | undefined => - toPullRequest( - node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), - )?.ciState; - expect(rollup({ state: 'SUCCESS' })).toBe('passing'); - expect(rollup({ state: 'FAILURE' })).toBe('failing'); - expect(rollup({ state: 'ERROR' })).toBe('failing'); - expect(rollup({ state: 'PENDING' })).toBe('pending'); - expect(rollup({ state: 'EXPECTED' })).toBe('pending'); - expect(rollup(null)).toBe('unknown'); - }); }); describe('toPullRequests', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 23ada2a8..4289096f 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -328,42 +328,3 @@ describe('buildSlackPayload note', () => { expect(serialized.length).toBeLessThan(2900); }); }); - -describe('buildSlackPayload CI icons', () => { - const fallback = { readyToMerge: [], needsOwner: [] }; - - it('puts an icon for the CI state in front of each PR', () => { - const payload = buildSlackPayload( - { - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'pending' }), - pr({ number: 4, ciState: 'unknown' }), - ], - }, - fallback, - }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, - ); - assert.ok(payload); - const lines = sectionText(payload.blocks[1]).split('\n'); - expect(lines[1]).toMatch(/^• :large_green_circle: .*#1 /u); - expect(lines[2]).toMatch(/^• :red_circle: .*#2 /u); - expect(lines[3]).toMatch(/^• :large_yellow_circle: .*#3 /u); - expect(lines[4]).toMatch(/^• :white_circle: .*#4 /u); - }); - - it('lists a failing CI PR under its own team and not under the fallback', () => { - const payload = buildSlackPayload( - { byTeam: { a: [pr({ ciState: 'failing' })] }, fallback }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, - ); - assert.ok(payload); - expect(payload.blocks).toHaveLength(2); - expect(sectionText(payload.blocks[1]).startsWith('a\n')).toBe(true); - }); -}); From 7526b944da67df4e239c8d6fcb1eb3eef5db2a96 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:49:57 +0100 Subject: [PATCH 21/61] feat: list PRs requested from many teams under the fallback team A PR requested from more than shared-team-threshold teams (default 3) is not owned by any one team, so it goes under the fallback team with its team count instead of being repeated under every team. --- .../actions/remind-dependabot-prs/action.yml | 5 ++ .../dependabot-pr-reminder/classify.mts | 30 ++++++-- .../scripts/dependabot-pr-reminder/cli.mts | 6 +- .../dependabot-pr-reminder/slack-payload.mts | 40 ++++++++--- .../scripts/dependabot-pr-reminder/teams.mts | 21 ++++++ .../scripts/dependabot-pr-reminder/types.mts | 1 + .../dependabot-pr-reminder/classify.test.mts | 35 ++++++++++ .../slack-payload.test.mts | 69 +++++++++++++++++-- .../dependabot-pr-reminder/teams.test.mts | 22 +++++- .github/workflows/remind-dependabot-prs.yml | 6 ++ 10 files changed, 210 insertions(+), 25 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index e33a1cb2..e9d32fc3 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -20,6 +20,10 @@ inputs: description: 'Git ref of MetaMask-planning to read topology.json from.' required: false default: 'main' + shared-team-threshold: + description: 'A PR requested from more than this many teams is listed under the fallback team.' + required: false + default: '3' reminder-note: description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none.' required: false @@ -52,6 +56,7 @@ runs: OWNER_TEAMS: ${{ inputs.owner-teams }} FALLBACK_TEAM: ${{ inputs.fallback-team }} TOPOLOGY_REF: ${{ inputs.topology-ref }} + SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} REMINDER_NOTE: ${{ inputs.reminder-note }} run: | set -euo pipefail diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index deb8824d..9646d686 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -1,27 +1,39 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; +/** A PR requested from more than this many teams goes to the fallback team. */ +export const DEFAULT_SHARED_TEAM_THRESHOLD = 3; + /** * Sorts pull requests into per-team groups and fallback buckets. * - * PRs with remaining requested teams are grouped by team, whatever their CI - * state, since the owning team is the one that fixes it. PRs with no team left - * are ready to merge when approved, and otherwise need an owner. + * PRs with remaining requested teams are grouped by team. When more than + * `sharedTeamThreshold` teams remain, no single team owns the PR, so it goes to + * the fallback team instead. PRs with no team left are ready to merge when + * approved, and otherwise need an owner. * * @param pullRequests - The open Dependabot pull requests. * @param options - Classification options. * @param options.ownerTeams - If set, only these teams are kept as owners. * @param options.fallbackTeam - The team that handles the fallback buckets. + * @param options.sharedTeamThreshold - The most teams a PR can have and still + * be listed under each of them. Defaults to 3. * @returns The classified reminder. */ export function classifyPullRequests( pullRequests: PullRequest[], - options: { ownerTeams?: string[]; fallbackTeam: string }, + options: { + ownerTeams?: string[]; + fallbackTeam: string; + sharedTeamThreshold?: number; + }, ): Reminder { const ownerTeams = options.ownerTeams?.map(normalizeTeamSlug); + const sharedTeamThreshold = + options.sharedTeamThreshold ?? DEFAULT_SHARED_TEAM_THRESHOLD; const reminder: Reminder = { byTeam: {}, - fallback: { readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, }; for (const pullRequest of pullRequests) { @@ -29,8 +41,12 @@ export function classifyPullRequests( .map(normalizeTeamSlug) .filter((team) => !ownerTeams || ownerTeams.includes(team)); - if (teams.length > 0) { - for (const team of new Set(teams)) { + const uniqueTeams = new Set(teams); + + if (uniqueTeams.size > sharedTeamThreshold) { + reminder.fallback.sharedByManyTeams.push(pullRequest); + } else if (uniqueTeams.size > 0) { + for (const team of uniqueTeams) { (reminder.byTeam[team] ??= []).push(pullRequest); } } else if (pullRequest.hasApproval) { diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 784ed2d5..d255d01d 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -7,7 +7,7 @@ import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; import { fetchDependabotPullRequests } from './github-api.mts'; import { buildSlackPayload } from './slack-payload.mts'; -import { parseOwnerTeams } from './teams.mts'; +import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; /** * Fetches open Dependabot pull requests and writes the Slack payload. @@ -42,8 +42,12 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { } const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); + const sharedTeamThreshold = parseSharedTeamThreshold( + environment.SHARED_TEAM_THRESHOLD, + ); const reminder = classifyPullRequests(pullRequests, { ...(ownerTeams ? { ownerTeams } : {}), + ...(sharedTeamThreshold === undefined ? {} : { sharedTeamThreshold }), fallbackTeam, }); diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 49b6e8ab..425cfc40 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -18,12 +18,18 @@ const MAX_TITLE_LENGTH = 200; * Formats pull requests as bulleted Slack links, one line each. * * @param pullRequests - The pull requests to list. + * @param showTeamCount - Whether to add how many teams were requested. * @returns The bulleted lines. */ -function formatPullRequestLines(pullRequests: PullRequest[]): string[] { +function formatPullRequestLines( + pullRequests: PullRequest[], + showTeamCount: boolean, +): string[] { return pullRequests.map( - ({ url, number, title }) => - `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>`, + ({ url, number, title, requestedTeams }) => + `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>${ + showTeamCount ? ` (${requestedTeams.length} teams)` : '' + }`, ); } @@ -84,8 +90,21 @@ export function buildSlackPayload( ); const teamGroups = groupTeamsByPullRequests(teamEntries); const fallbackSections = [ - { label: 'Ready to merge', pullRequests: reminder.fallback.readyToMerge }, - { label: 'Needs owner', pullRequests: reminder.fallback.needsOwner }, + { + label: 'Shared by many teams', + pullRequests: reminder.fallback.sharedByManyTeams, + showTeamCount: true, + }, + { + label: 'Ready to merge', + pullRequests: reminder.fallback.readyToMerge, + showTeamCount: false, + }, + { + label: 'Needs owner', + pullRequests: reminder.fallback.needsOwner, + showTeamCount: false, + }, ].filter(({ pullRequests }) => pullRequests.length > 0); if (teamEntries.length === 0 && fallbackSections.length === 0) { @@ -120,7 +139,10 @@ export function buildSlackPayload( const addSections = ( teams: string[], pullRequests: PullRequest[], - label?: string, + { + label, + showTeamCount = false, + }: { label?: string; showTeamCount?: boolean } = {}, ): void => { const tags = teams.map(tag); const header = tags.map(({ text }) => text).join(' '); @@ -128,7 +150,7 @@ export function buildSlackPayload( const handles = tags.flatMap(({ handle }) => (handle ? [handle] : [])); for (const text of chunkSections( fullHeader, - formatPullRequestLines(pullRequests), + formatPullRequestLines(pullRequests, showTeamCount), )) { entries.push({ block: section(text), handles }); } @@ -136,8 +158,8 @@ export function buildSlackPayload( for (const { teams, pullRequests } of teamGroups) { addSections(teams, pullRequests); } - for (const { label, pullRequests } of fallbackSections) { - addSections([options.fallbackTeam], pullRequests, label); + for (const { label, pullRequests, showTeamCount } of fallbackSections) { + addSections([options.fallbackTeam], pullRequests, { label, showTeamCount }); } const { blocks, omitted } = capBlocks( diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts index 07bb7834..2e8edacb 100644 --- a/.github/scripts/dependabot-pr-reminder/teams.mts +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -14,3 +14,24 @@ export function parseOwnerTeams( .filter(Boolean); return teams.length > 0 ? teams : undefined; } + +/** + * Parses the SHARED_TEAM_THRESHOLD value. + * + * @param value - The raw value. + * @returns The threshold, or undefined to use the default. + * @throws If the value is set but is not a positive whole number. + */ +export function parseSharedTeamThreshold( + value: string | undefined, +): number | undefined { + const trimmed = (value ?? '').trim(); + if (!trimmed) { + return undefined; + } + const threshold = Number(trimmed); + if (!Number.isInteger(threshold) || threshold < 1) { + throw new Error('SHARED_TEAM_THRESHOLD must be a positive whole number'); + } + return threshold; +} diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 0b70e1af..2019850e 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -9,6 +9,7 @@ export type PullRequest = { export type Reminder = { byTeam: Record; fallback: { + sharedByManyTeams: PullRequest[]; readyToMerge: PullRequest[]; needsOwner: PullRequest[]; }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 90774548..b4a7f9a3 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -51,4 +51,39 @@ describe('classifyPullRequests', () => { }); expect(Object.keys(result.byTeam)).toStrictEqual(['core']); }); + + it('keeps a PR under its teams when it has exactly the threshold', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b', 'c']); + expect(result.fallback.sharedByManyTeams).toStrictEqual([]); + }); + + it('moves a PR with more teams than the threshold to the fallback', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); + const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); + expect(result.byTeam).toStrictEqual({}); + expect(result.fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + }); + + it('uses a custom threshold', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b'] }); + const result = classifyPullRequests([pullRequest], { + fallbackTeam: 'f', + sharedTeamThreshold: 1, + }); + expect(result.fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + }); + + it('counts only the owner teams and ignores repeats', () => { + const pullRequest = pr({ + requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], + }); + const result = classifyPullRequests([pullRequest], { + ownerTeams: ['a', 'b'], + fallbackTeam: 'f', + }); + expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b']); + expect(result.fallback.sharedByManyTeams).toStrictEqual([]); + }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 4289096f..bc3c679f 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -8,7 +8,7 @@ describe('buildSlackPayload', () => { const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; const emptyReminder = (): Reminder => ({ byTeam: {}, - fallback: { readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, }); const allText = (payload: { text: string; blocks: unknown[] }): string => `${payload.text}\n${JSON.stringify(payload.blocks)}`; @@ -106,7 +106,7 @@ describe('buildSlackPayload chunking', () => { ); const reminder: Reminder = { byTeam: { wallet: pullRequests }, - fallback: { readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, }; const payload = buildSlackPayload( reminder, @@ -135,7 +135,10 @@ describe('buildSlackPayload limits and lookup', () => { byTeam[`team-${index}`] = [pr({ number: index + 1 })]; } const payload = buildSlackPayload( - { byTeam, fallback: { readyToMerge: [], needsOwner: [] } }, + { + byTeam, + fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + }, {}, options, ); @@ -148,7 +151,7 @@ describe('buildSlackPayload limits and lookup', () => { const payload = buildSlackPayload( { byTeam: { a: [pr()] }, - fallback: { readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, }, { bad: null, @@ -162,7 +165,7 @@ describe('buildSlackPayload limits and lookup', () => { describe('buildSlackPayload mentions and titles', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; it('does not turn @ text in titles into mentions', () => { const payload = buildSlackPayload( @@ -208,7 +211,7 @@ describe('buildSlackPayload mentions and titles', () => { describe('buildSlackPayload grouping', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; const topology = { a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, @@ -264,7 +267,7 @@ describe('buildSlackPayload grouping', () => { }); describe('buildSlackPayload note', () => { - const fallback = { readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; it('adds the note as a section right under the headline', () => { const payload = buildSlackPayload( @@ -328,3 +331,55 @@ describe('buildSlackPayload note', () => { expect(serialized.length).toBeLessThan(2900); }); }); + +describe('buildSlackPayload shared by many teams', () => { + const fallback = { + sharedByManyTeams: [ + pr({ number: 9, requestedTeams: ['a', 'b', 'c', 'd'] }), + ], + readyToMerge: [], + needsOwner: [], + }; + const topology = { + platform: { + githubHandle: 'MetaMask/platform', + slackHandle: { team: '@platform-team' }, + }, + }; + + it('lists the PR under the fallback team with how many teams it has', () => { + const payload = buildSlackPayload({ byTeam: {}, fallback }, topology, { + fallbackTeam: 'platform', + repository: 'MetaMask/example', + }); + assert.ok(payload); + const text = sectionText(payload.blocks[1]); + expect(text.split('\n')[0]).toBe('@platform-team *Shared by many teams*'); + expect(text).toMatch(/#9 .*\(4 teams\)$/u); + expect(payload.text).toContain('@platform-team'); + }); + + it('puts the shared section before ready to merge and needs owner', () => { + const payload = buildSlackPayload( + { + byTeam: {}, + fallback: { + ...fallback, + readyToMerge: [pr({ number: 2 })], + needsOwner: [pr({ number: 3 })], + }, + }, + topology, + { fallbackTeam: 'platform', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + const headers = payload.blocks + .slice(1) + .map((block) => sectionText(block).split('\n')[0]); + expect(headers).toStrictEqual([ + '@platform-team *Shared by many teams*', + '@platform-team *Ready to merge*', + '@platform-team *Needs owner*', + ]); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts index ef19b528..f84f3847 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { parseOwnerTeams } from '../../dependabot-pr-reminder/teams.mts'; +import { + parseOwnerTeams, + parseSharedTeamThreshold, +} from '../../dependabot-pr-reminder/teams.mts'; describe('parseOwnerTeams', () => { it('returns undefined for undefined, empty, and whitespace input', () => { @@ -14,3 +17,20 @@ describe('parseOwnerTeams', () => { expect(parseOwnerTeams(' a, b ,,c ')).toStrictEqual(['a', 'b', 'c']); }); }); + +describe('parseSharedTeamThreshold', () => { + it('returns undefined when unset or blank', () => { + expect(parseSharedTeamThreshold(undefined)).toBeUndefined(); + expect(parseSharedTeamThreshold(' ')).toBeUndefined(); + }); + + it('parses a positive whole number', () => { + expect(parseSharedTeamThreshold(' 4 ')).toBe(4); + }); + + it.each(['0', '-1', '2.5', 'many'])('rejects %s', (value) => { + expect(() => parseSharedTeamThreshold(value)).toThrow( + 'SHARED_TEAM_THRESHOLD', + ); + }); +}); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index ce3aeece..ab1c5fbd 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -36,6 +36,11 @@ on: type: string default: 'main' description: 'Git ref of MetaMask-planning to read topology.json from' + shared-team-threshold: + required: false + type: number + default: 3 + description: 'A PR requested from more than this many teams is listed under the fallback team' reminder-note: required: false type: string @@ -81,6 +86,7 @@ jobs: owner-teams: ${{ inputs.owner-teams }} fallback-team: ${{ inputs.fallback-team }} topology-ref: ${{ inputs.topology-ref }} + shared-team-threshold: ${{ inputs.shared-team-threshold }} reminder-note: ${{ inputs.reminder-note }} - name: Send Slack notification From ecdff8a1eaacc4aae10188aaa211c32d66de597b Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:52:26 +0100 Subject: [PATCH 22/61] feat: set the default shared team threshold to 5 --- .github/actions/remind-dependabot-prs/action.yml | 2 +- .github/scripts/dependabot-pr-reminder/classify.mts | 4 ++-- .../scripts/tests/dependabot-pr-reminder/classify.test.mts | 6 +++--- .github/workflows/remind-dependabot-prs.yml | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index e9d32fc3..918602c3 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -23,7 +23,7 @@ inputs: shared-team-threshold: description: 'A PR requested from more than this many teams is listed under the fallback team.' required: false - default: '3' + default: '5' reminder-note: description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none.' required: false diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 9646d686..a66cf20c 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -2,7 +2,7 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; /** A PR requested from more than this many teams goes to the fallback team. */ -export const DEFAULT_SHARED_TEAM_THRESHOLD = 3; +export const DEFAULT_SHARED_TEAM_THRESHOLD = 5; /** * Sorts pull requests into per-team groups and fallback buckets. @@ -17,7 +17,7 @@ export const DEFAULT_SHARED_TEAM_THRESHOLD = 3; * @param options.ownerTeams - If set, only these teams are kept as owners. * @param options.fallbackTeam - The team that handles the fallback buckets. * @param options.sharedTeamThreshold - The most teams a PR can have and still - * be listed under each of them. Defaults to 3. + * be listed under each of them. Defaults to 5. * @returns The classified reminder. */ export function classifyPullRequests( diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index b4a7f9a3..f79f477e 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -53,14 +53,14 @@ describe('classifyPullRequests', () => { }); it('keeps a PR under its teams when it has exactly the threshold', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd', 'e'] }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b', 'c']); + expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b', 'c', 'd', 'e']); expect(result.fallback.sharedByManyTeams).toStrictEqual([]); }); it('moves a PR with more teams than the threshold to the fallback', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'] }); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); expect(result.byTeam).toStrictEqual({}); expect(result.fallback.sharedByManyTeams).toStrictEqual([pullRequest]); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index ab1c5fbd..449422c2 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -39,7 +39,7 @@ on: shared-team-threshold: required: false type: number - default: 3 + default: 5 description: 'A PR requested from more than this many teams is listed under the fallback team' reminder-note: required: false From 1985cf601726f59bad2e40eb13bf0345d7e13e15 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:54:12 +0100 Subject: [PATCH 23/61] docs: mention the changelog in the default reminder note --- .github/actions/remind-dependabot-prs/action.yml | 2 +- .github/workflows/remind-dependabot-prs.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 918602c3..bd6d9408 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -27,7 +27,7 @@ inputs: reminder-note: description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none.' required: false - default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' + default: 'Tagged teams own these PRs: read the changelog, test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' outputs: has-prs: diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 449422c2..7bea1b07 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -44,7 +44,7 @@ on: reminder-note: required: false type: string - default: 'Tagged teams own these PRs: test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' + default: 'Tagged teams own these PRs: read the changelog, test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none' environment: required: false From f2be3dacc00f56d9f673c2865d4b3eabba27a766 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 15:57:42 +0100 Subject: [PATCH 24/61] feat: list each PR once under all of its teams Teams that share a PR are now shown together in one header above it, so a PR is no longer repeated under every team it was requested from. --- .../dependabot-pr-reminder/slack-payload.mts | 43 +++++++++++++------ .../slack-payload.test.mts | 29 +++++++++++-- 2 files changed, 55 insertions(+), 17 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 425cfc40..b43ef07e 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -34,30 +34,45 @@ function formatPullRequestLines( } /** - * Merges teams that have the same pull requests, so a PR requested from - * several teams is listed once with all of them tagged. Groups keep the order - * in which their first team appears. + * Groups pull requests by the teams they were requested from, so each PR is + * listed once, under all of its teams. PRs with the same set of teams share a + * group. Groups and teams keep the order in which they first appear. * - * @param teamEntries - Each team with its pull requests. + * @param byTeam - Each team with its pull requests. * @returns The groups of teams and the pull requests they share. */ -function groupTeamsByPullRequests( - teamEntries: [string, PullRequest[]][], +function groupPullRequestsByTeams( + byTeam: Reminder['byTeam'], ): { teams: string[]; pullRequests: PullRequest[] }[] { + const teamsByPullRequest = new Map< + number, + { pullRequest: PullRequest; teams: string[] } + >(); + for (const [team, pullRequests] of Object.entries(byTeam)) { + for (const pullRequest of pullRequests) { + const entry = teamsByPullRequest.get(pullRequest.number); + if (entry) { + entry.teams.push(team); + } else { + teamsByPullRequest.set(pullRequest.number, { + pullRequest, + teams: [team], + }); + } + } + } + const groups = new Map< string, { teams: string[]; pullRequests: PullRequest[] } >(); - for (const [team, pullRequests] of teamEntries) { - const key = pullRequests - .map(({ number }) => number) - .sort((left, right) => left - right) - .join(','); + for (const { pullRequest, teams } of teamsByPullRequest.values()) { + const key = [...teams].sort().join(','); const group = groups.get(key); if (group) { - group.teams.push(team); + group.pullRequests.push(pullRequest); } else { - groups.set(key, { teams: [team], pullRequests }); + groups.set(key, { teams, pullRequests: [pullRequest] }); } } return [...groups.values()]; @@ -88,7 +103,7 @@ export function buildSlackPayload( const teamEntries = Object.entries(reminder.byTeam).filter( ([, pullRequests]) => pullRequests.length > 0, ); - const teamGroups = groupTeamsByPullRequests(teamEntries); + const teamGroups = groupPullRequestsByTeams(reminder.byTeam); const fallbackSections = [ { label: 'Shared by many teams', diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index bc3c679f..b95c6d52 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -235,12 +235,13 @@ describe('buildSlackPayload grouping', () => { expect(payload.text).toContain('@a-team @b-team'); }); - it('keeps teams with different PRs in separate sections', () => { + it('lists each PR once, under all of its teams', () => { const payload = buildSlackPayload( { byTeam: { a: [pr({ number: 1 }), pr({ number: 2 })], b: [pr({ number: 2 })], + c: [pr({ number: 2 })], }, fallback, }, @@ -249,8 +250,30 @@ describe('buildSlackPayload grouping', () => { ); assert.ok(payload); expect(payload.blocks).toHaveLength(3); - expect(sectionText(payload.blocks[1]).startsWith('@a-team\n')).toBe(true); - expect(sectionText(payload.blocks[2]).startsWith('@b-team\n')).toBe(true); + expect(sectionText(payload.blocks[1]).split('\n')[0]).toBe('@a-team'); + expect(sectionText(payload.blocks[1])).toMatch(/#1 /u); + expect(sectionText(payload.blocks[2]).split('\n')[0]).toBe( + '@a-team @b-team c', + ); + expect(sectionText(payload.blocks[2])).toMatch(/#2 /u); + expect(JSON.stringify(payload.blocks).match(/#2 /gu)).toHaveLength(1); + }); + + it('puts PRs with the same teams together', () => { + const payload = buildSlackPayload( + { + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 2 }), pr({ number: 1 })], + }, + fallback, + }, + topology, + options, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(2); + expect(sectionText(payload.blocks[1]).split('\n')).toHaveLength(3); }); it('shows a team without a handle as plain text next to tagged teams', () => { From cf11d156421774a7ad30027ef6991ca22f57765a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 20:17:11 +0100 Subject: [PATCH 25/61] refactor: send PRs with no team to the fallback team, whatever their approval The Ready to merge and Needs owner sections are gone, so the review state is no longer read. Also resets the coverage thresholds to the current values. --- .../dependabot-pr-reminder/classify.mts | 9 ++---- .../dependabot-pr-reminder/github-api.mts | 9 ------ .../dependabot-pr-reminder/slack-payload.mts | 11 ++----- .../scripts/dependabot-pr-reminder/types.mts | 4 +-- .../dependabot-pr-reminder/classify.test.mts | 16 +++------- .../tests/dependabot-pr-reminder/fixtures.mts | 1 - .../github-api.test.mts | 17 ---------- .../slack-payload.test.mts | 31 +++++++------------ 8 files changed, 24 insertions(+), 74 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index a66cf20c..386684f9 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -9,8 +9,7 @@ export const DEFAULT_SHARED_TEAM_THRESHOLD = 5; * * PRs with remaining requested teams are grouped by team. When more than * `sharedTeamThreshold` teams remain, no single team owns the PR, so it goes to - * the fallback team instead. PRs with no team left are ready to merge when - * approved, and otherwise need an owner. + * the fallback team instead. PRs with no team left go to the fallback team too. * * @param pullRequests - The open Dependabot pull requests. * @param options - Classification options. @@ -33,7 +32,7 @@ export function classifyPullRequests( options.sharedTeamThreshold ?? DEFAULT_SHARED_TEAM_THRESHOLD; const reminder: Reminder = { byTeam: {}, - fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], noTeam: [] }, }; for (const pullRequest of pullRequests) { @@ -49,10 +48,8 @@ export function classifyPullRequests( for (const team of uniqueTeams) { (reminder.byTeam[team] ??= []).push(pullRequest); } - } else if (pullRequest.hasApproval) { - reminder.fallback.readyToMerge.push(pullRequest); } else { - reminder.fallback.needsOwner.push(pullRequest); + reminder.fallback.noTeam.push(pullRequest); } } diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index c9fe4fc0..ea8b06be 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -13,7 +13,6 @@ export type GraphQlPullRequestNode = { requestedReviewer: { __typename: string; slug?: string } | null; }[]; }; - latestOpinionatedReviews: { nodes: { state: string }[] }; }; /** A page of search results. Nodes that are not pull requests come back empty. */ @@ -42,7 +41,6 @@ query($searchQuery: String!, $endCursor: String) { reviewRequests(first: 20) { nodes { requestedReviewer { __typename ... on Team { slug } } } } - latestOpinionatedReviews(first: 20) { nodes { state } } } } } @@ -83,10 +81,6 @@ export function toPullRequest( return undefined; } - const reviewStates = node.latestOpinionatedReviews.nodes.map( - ({ state }) => state, - ); - return { number: node.number, title: node.title, @@ -97,9 +91,6 @@ export function toPullRequest( ? [requestedReviewer.slug] : [], ), - hasApproval: - reviewStates.includes('APPROVED') && - !reviewStates.includes('CHANGES_REQUESTED'), }; } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index b43ef07e..9260baff 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -111,13 +111,8 @@ export function buildSlackPayload( showTeamCount: true, }, { - label: 'Ready to merge', - pullRequests: reminder.fallback.readyToMerge, - showTeamCount: false, - }, - { - label: 'Needs owner', - pullRequests: reminder.fallback.needsOwner, + label: undefined, + pullRequests: reminder.fallback.noTeam, showTeamCount: false, }, ].filter(({ pullRequests }) => pullRequests.length > 0); @@ -157,7 +152,7 @@ export function buildSlackPayload( { label, showTeamCount = false, - }: { label?: string; showTeamCount?: boolean } = {}, + }: { label?: string | undefined; showTeamCount?: boolean } = {}, ): void => { const tags = teams.map(tag); const header = tags.map(({ text }) => text).join(' '); diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 2019850e..780dfc16 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -3,14 +3,12 @@ export type PullRequest = { title: string; url: string; requestedTeams: string[]; - hasApproval: boolean; }; export type Reminder = { byTeam: Record; fallback: { sharedByManyTeams: PullRequest[]; - readyToMerge: PullRequest[]; - needsOwner: PullRequest[]; + noTeam: PullRequest[]; }; }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index f79f477e..006525ae 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -11,16 +11,10 @@ describe('classifyPullRequests', () => { expect(result.byTeam.b).toStrictEqual([pullRequest]); }); - it('lists approved PRs with no teams left as ready to merge', () => { - const pullRequest = pr({ requestedTeams: [], hasApproval: true }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.fallback.readyToMerge).toStrictEqual([pullRequest]); - }); - - it('lists PRs with no teams and no approval as needs owner', () => { + it('lists PRs with no teams under the fallback, approved or not', () => { const pullRequest = pr(); const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.fallback.needsOwner).toStrictEqual([pullRequest]); + expect(result.fallback.noTeam).toStrictEqual([pullRequest]); }); it('filters other teams out when ownerTeams is set', () => { @@ -33,14 +27,14 @@ describe('classifyPullRequests', () => { expect(result.byTeam['extension-platform']).toStrictEqual([pullRequest]); }); - it('lists approved PRs as ready to merge when ownerTeams leaves nothing', () => { - const pullRequest = pr({ requestedTeams: ['ui'], hasApproval: true }); + it('lists a PR under the fallback when ownerTeams leaves nothing', () => { + const pullRequest = pr({ requestedTeams: ['ui'] }); const result = classifyPullRequests([pullRequest], { ownerTeams: ['extension-platform'], fallbackTeam: 'f', }); expect(result.byTeam).toStrictEqual({}); - expect(result.fallback.readyToMerge).toStrictEqual([pullRequest]); + expect(result.fallback.noTeam).toStrictEqual([pullRequest]); }); it('normalizes team names before comparing and grouping', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index b4dffcaa..b5ef43b5 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -13,7 +13,6 @@ export function pr(overrides: Partial = {}): PullRequest { title: 'Bump foo from 1.0.0 to 1.0.1', url: 'https://github.com/MetaMask/example/pull/1', requestedTeams: [], - hasApproval: false, ...overrides, }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index d94e349f..62f68ebe 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -27,7 +27,6 @@ function node( isDraft: false, author: { __typename: 'Bot', login: 'dependabot' }, reviewRequests: { nodes: [] }, - latestOpinionatedReviews: { nodes: [] }, ...overrides, }; } @@ -73,7 +72,6 @@ describe('toPullRequest', () => { title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], - hasApproval: false, }); }); @@ -91,21 +89,6 @@ describe('toPullRequest', () => { ); expect(pullRequest?.requestedTeams).toStrictEqual(['wallet']); }); - - it('sets hasApproval when approved and nothing requests changes', () => { - const result = (states: string[]): boolean | undefined => - toPullRequest( - node({ - latestOpinionatedReviews: { - nodes: states.map((state) => ({ state })), - }, - }), - )?.hasApproval; - expect(result(['APPROVED'])).toBe(true); - expect(result(['APPROVED', 'CHANGES_REQUESTED'])).toBe(false); - expect(result(['CHANGES_REQUESTED'])).toBe(false); - expect(result([])).toBe(false); - }); }); describe('toPullRequests', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index b95c6d52..6ded92da 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -8,7 +8,7 @@ describe('buildSlackPayload', () => { const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; const emptyReminder = (): Reminder => ({ byTeam: {}, - fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], noTeam: [] }, }); const allText = (payload: { text: string; blocks: unknown[] }): string => `${payload.text}\n${JSON.stringify(payload.blocks)}`; @@ -73,8 +73,7 @@ describe('buildSlackPayload', () => { it('renders fallback sections under the fallback team', () => { const reminder = emptyReminder(); - reminder.fallback.readyToMerge = [pr({ number: 2 })]; - reminder.fallback.needsOwner = [pr({ number: 3 })]; + reminder.fallback.noTeam = [pr({ number: 3 })]; const payload = buildSlackPayload( reminder, { @@ -88,9 +87,6 @@ describe('buildSlackPayload', () => { assert.ok(payload); const text = allText(payload); expect(text).toMatch(/@platform-team/u); - expect(text).toMatch(/[Rr]eady to merge/u); - expect(text).toMatch(/[Nn]eeds owner/u); - expect(text).toMatch(/#2/u); expect(text).toMatch(/#3/u); }); }); @@ -106,7 +102,7 @@ describe('buildSlackPayload chunking', () => { ); const reminder: Reminder = { byTeam: { wallet: pullRequests }, - fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], noTeam: [] }, }; const payload = buildSlackPayload( reminder, @@ -137,7 +133,7 @@ describe('buildSlackPayload limits and lookup', () => { const payload = buildSlackPayload( { byTeam, - fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], noTeam: [] }, }, {}, options, @@ -151,7 +147,7 @@ describe('buildSlackPayload limits and lookup', () => { const payload = buildSlackPayload( { byTeam: { a: [pr()] }, - fallback: { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }, + fallback: { sharedByManyTeams: [], noTeam: [] }, }, { bad: null, @@ -165,7 +161,7 @@ describe('buildSlackPayload limits and lookup', () => { describe('buildSlackPayload mentions and titles', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], noTeam: [] }; it('does not turn @ text in titles into mentions', () => { const payload = buildSlackPayload( @@ -211,7 +207,7 @@ describe('buildSlackPayload mentions and titles', () => { describe('buildSlackPayload grouping', () => { const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], noTeam: [] }; const topology = { a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, @@ -290,7 +286,7 @@ describe('buildSlackPayload grouping', () => { }); describe('buildSlackPayload note', () => { - const fallback = { sharedByManyTeams: [], readyToMerge: [], needsOwner: [] }; + const fallback = { sharedByManyTeams: [], noTeam: [] }; it('adds the note as a section right under the headline', () => { const payload = buildSlackPayload( @@ -360,8 +356,7 @@ describe('buildSlackPayload shared by many teams', () => { sharedByManyTeams: [ pr({ number: 9, requestedTeams: ['a', 'b', 'c', 'd'] }), ], - readyToMerge: [], - needsOwner: [], + noTeam: [], }; const topology = { platform: { @@ -382,14 +377,13 @@ describe('buildSlackPayload shared by many teams', () => { expect(payload.text).toContain('@platform-team'); }); - it('puts the shared section before ready to merge and needs owner', () => { + it('puts the shared section before the PRs with no team', () => { const payload = buildSlackPayload( { byTeam: {}, fallback: { ...fallback, - readyToMerge: [pr({ number: 2 })], - needsOwner: [pr({ number: 3 })], + noTeam: [pr({ number: 3 })], }, }, topology, @@ -401,8 +395,7 @@ describe('buildSlackPayload shared by many teams', () => { .map((block) => sectionText(block).split('\n')[0]); expect(headers).toStrictEqual([ '@platform-team *Shared by many teams*', - '@platform-team *Ready to merge*', - '@platform-team *Needs owner*', + '@platform-team', ]); }); }); From 1c7aa1d61a36e4c67c0d732e9f9d3e9376d969de Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 20:21:19 +0100 Subject: [PATCH 26/61] feat: show a CI status icon on each PR again Green, red, yellow or white for passing, failing, pending or no checks. It is only an icon, failing PRs stay under their own teams. --- .../dependabot-pr-reminder/github-api.mts | 28 +++++++++++++ .../dependabot-pr-reminder/slack-payload.mts | 12 +++++- .../scripts/dependabot-pr-reminder/types.mts | 1 + .../tests/dependabot-pr-reminder/fixtures.mts | 1 + .../github-api.test.mts | 17 ++++++++ .../slack-payload.test.mts | 39 +++++++++++++++++++ 6 files changed, 96 insertions(+), 2 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index ea8b06be..4dfe0419 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -13,6 +13,9 @@ export type GraphQlPullRequestNode = { requestedReviewer: { __typename: string; slug?: string } | null; }[]; }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; }; /** A page of search results. Nodes that are not pull requests come back empty. */ @@ -41,6 +44,7 @@ query($searchQuery: String!, $endCursor: String) { reviewRequests(first: 20) { nodes { requestedReviewer { __typename ... on Team { slug } } } } + commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } } } } @@ -56,6 +60,26 @@ export function buildSearchQuery(repository: string): string { return `repo:${repository} is:pr is:open draft:false author:app/dependabot`; } +/** + * Maps a commit status rollup to a CI state. + * + * @param rollupState - The GraphQL rollup state, or null when there are no + * checks. + * @returns The CI state. + */ +function toCiState(rollupState: string | null): PullRequest['ciState'] { + if (rollupState === 'SUCCESS') { + return 'passing'; + } + if (rollupState === 'FAILURE' || rollupState === 'ERROR') { + return 'failing'; + } + if (rollupState === 'PENDING' || rollupState === 'EXPECTED') { + return 'pending'; + } + return 'unknown'; +} + /** * Maps a search node to a PullRequest. * @@ -81,6 +105,9 @@ export function toPullRequest( return undefined; } + const rollupState = + node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; + return { number: node.number, title: node.title, @@ -91,6 +118,7 @@ export function toPullRequest( ? [requestedReviewer.slug] : [], ), + ciState: toCiState(rollupState), }; } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 9260baff..efc848ee 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -14,6 +14,14 @@ import type { PullRequest, Reminder } from './types.mts'; /** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; +/** Shown in front of each PR to tell its CI state at a glance. */ +const CI_ICONS: Record = { + passing: ':large_green_circle:', + failing: ':red_circle:', + pending: ':large_yellow_circle:', + unknown: ':white_circle:', +}; + /** * Formats pull requests as bulleted Slack links, one line each. * @@ -26,8 +34,8 @@ function formatPullRequestLines( showTeamCount: boolean, ): string[] { return pullRequests.map( - ({ url, number, title, requestedTeams }) => - `• <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>${ + ({ url, number, title, requestedTeams, ciState }) => + `• ${CI_ICONS[ciState]} <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>${ showTeamCount ? ` (${requestedTeams.length} teams)` : '' }`, ); diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 780dfc16..7cd44b49 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -3,6 +3,7 @@ export type PullRequest = { title: string; url: string; requestedTeams: string[]; + ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; export type Reminder = { diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index b5ef43b5..a2d6dfc5 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -13,6 +13,7 @@ export function pr(overrides: Partial = {}): PullRequest { title: 'Bump foo from 1.0.0 to 1.0.1', url: 'https://github.com/MetaMask/example/pull/1', requestedTeams: [], + ciState: 'unknown', ...overrides, }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index 62f68ebe..fe51a1a6 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -27,6 +27,7 @@ function node( isDraft: false, author: { __typename: 'Bot', login: 'dependabot' }, reviewRequests: { nodes: [] }, + commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, ...overrides, }; } @@ -72,6 +73,7 @@ describe('toPullRequest', () => { title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], + ciState: 'unknown', }); }); @@ -89,6 +91,21 @@ describe('toPullRequest', () => { ); expect(pullRequest?.requestedTeams).toStrictEqual(['wallet']); }); + + it('maps the status rollup to a CI state', () => { + const rollup = ( + statusCheckRollup: { state: string } | null, + ): string | undefined => + toPullRequest( + node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), + )?.ciState; + expect(rollup({ state: 'SUCCESS' })).toBe('passing'); + expect(rollup({ state: 'FAILURE' })).toBe('failing'); + expect(rollup({ state: 'ERROR' })).toBe('failing'); + expect(rollup({ state: 'PENDING' })).toBe('pending'); + expect(rollup({ state: 'EXPECTED' })).toBe('pending'); + expect(rollup(null)).toBe('unknown'); + }); }); describe('toPullRequests', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 6ded92da..eadb2462 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -399,3 +399,42 @@ describe('buildSlackPayload shared by many teams', () => { ]); }); }); + +describe('buildSlackPayload CI icons', () => { + const fallback = { sharedByManyTeams: [], noTeam: [] }; + + it('puts an icon for the CI state in front of each PR', () => { + const payload = buildSlackPayload( + { + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'pending' }), + pr({ number: 4, ciState: 'unknown' }), + ], + }, + fallback, + }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + const lines = sectionText(payload.blocks[1]).split('\n'); + expect(lines[1]).toMatch(/^• :large_green_circle: .*#1 /u); + expect(lines[2]).toMatch(/^• :red_circle: .*#2 /u); + expect(lines[3]).toMatch(/^• :large_yellow_circle: .*#3 /u); + expect(lines[4]).toMatch(/^• :white_circle: .*#4 /u); + }); + + it('keeps a failing PR under its own team', () => { + const payload = buildSlackPayload( + { byTeam: { a: [pr({ ciState: 'failing' })] }, fallback }, + {}, + { fallbackTeam: 'f', repository: 'MetaMask/example' }, + ); + assert.ok(payload); + expect(payload.blocks).toHaveLength(2); + expect(sectionText(payload.blocks[1]).startsWith('a\n')).toBe(true); + }); +}); From 45acfefbbe34007d136fa776a2af041ed5c7b66a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 20:25:27 +0100 Subject: [PATCH 27/61] feat: use a check mark for passing CI and a warning for failing CI --- .github/scripts/dependabot-pr-reminder/slack-payload.mts | 6 +++--- .../tests/dependabot-pr-reminder/slack-payload.test.mts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index efc848ee..49918a13 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -16,9 +16,9 @@ const MAX_TITLE_LENGTH = 200; /** Shown in front of each PR to tell its CI state at a glance. */ const CI_ICONS: Record = { - passing: ':large_green_circle:', - failing: ':red_circle:', - pending: ':large_yellow_circle:', + passing: ':white_check_mark:', + failing: ':warning:', + pending: ':hourglass_flowing_sand:', unknown: ':white_circle:', }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index eadb2462..e367dfab 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -421,9 +421,9 @@ describe('buildSlackPayload CI icons', () => { ); assert.ok(payload); const lines = sectionText(payload.blocks[1]).split('\n'); - expect(lines[1]).toMatch(/^• :large_green_circle: .*#1 /u); - expect(lines[2]).toMatch(/^• :red_circle: .*#2 /u); - expect(lines[3]).toMatch(/^• :large_yellow_circle: .*#3 /u); + expect(lines[1]).toMatch(/^• :white_check_mark: .*#1 /u); + expect(lines[2]).toMatch(/^• :warning: .*#2 /u); + expect(lines[3]).toMatch(/^• :hourglass_flowing_sand: .*#3 /u); expect(lines[4]).toMatch(/^• :white_circle: .*#4 /u); }); From 10b1532d3f7b06f3bebc201fda277d448521d7dd Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 24 Nov 2026 21:04:05 +0100 Subject: [PATCH 28/61] feat: tell teams exactly what to do in the reminder The default note now lists the steps (changelog, CI icon meaning, fixing CI, review, merge) and names the repository. reminder-note takes default, empty or custom text, and {repository} is filled in. --- .../actions/remind-dependabot-prs/action.yml | 4 +- .../scripts/dependabot-pr-reminder/cli.mts | 3 +- .../dependabot-pr-reminder/reminder-note.mts | 49 +++++++++++++++++++ .../dependabot-pr-reminder/slack-payload.mts | 2 +- .../reminder-note.test.mts | 44 +++++++++++++++++ .github/workflows/remind-dependabot-prs.yml | 4 +- 6 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 .github/scripts/dependabot-pr-reminder/reminder-note.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index bd6d9408..92b4968f 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -25,9 +25,9 @@ inputs: required: false default: '5' reminder-note: - description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none.' + description: 'Note shown under the headline, as Slack mrkdwn. `default` uses the built in instructions, empty for none. `{repository}` is replaced by the repository name.' required: false - default: 'Tagged teams own these PRs: read the changelog, test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' + default: 'default' outputs: has-prs: diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index d255d01d..26672101 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -6,6 +6,7 @@ import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; import { fetchDependabotPullRequests } from './github-api.mts'; +import { resolveReminderNote } from './reminder-note.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; @@ -67,7 +68,7 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { ); } - const note = environment.REMINDER_NOTE?.trim(); + const note = resolveReminderNote(environment.REMINDER_NOTE, repository); const payload = buildSlackPayload(reminder, topology, { fallbackTeam, repository, diff --git a/.github/scripts/dependabot-pr-reminder/reminder-note.mts b/.github/scripts/dependabot-pr-reminder/reminder-note.mts new file mode 100644 index 00000000..55908ad0 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/reminder-note.mts @@ -0,0 +1,49 @@ +import { escapeSlack } from '../shared/slack-blocks.mts'; +import { CI_ICONS } from './slack-payload.mts'; + +/** The value of `reminder-note` that selects the built in note. */ +export const DEFAULT_NOTE_KEYWORD = 'default'; + +/** + * Builds the built in note, which tells teams what to do with the PRs. The icon + * legend is built from the icons the message really uses. + * + * @param repository - The repository the PRs are in, such as `MetaMask/core`. + * @returns The note, as Slack mrkdwn. + */ +function buildDefaultNote(repository: string): string { + return [ + '*What to do if your team is tagged on a PR below*', + `Some packages in ${escapeSlack(repository)} have outdated dependencies, and Dependabot opened PRs to bump them.`, + '', + '1. Read the changelogs of the dependencies being bumped.', + `2. Check the icon: ${CI_ICONS.passing} CI passes, ${CI_ICONS.failing} CI fails, ${CI_ICONS.pending} CI is still running, ${CI_ICONS.unknown} no checks.`, + '3. If CI fails, work out why and fix it. You can push directly to the PR, but Dependabot stops updating it once you do.', + "4. Have a teammate review and approve it. If the PR touches other teams' packages, work with them to get their changes and approvals too.", + '5. Merge once CI passes and every required team has approved.', + '', + 'PRs under "Shared by many teams" are coordinated by the team tagged on that section.', + ].join('\n'); +} + +/** + * Works out the note to show from the `reminder-note` setting. + * + * @param value - The setting. Unset or `default` gives the built in note, empty + * gives no note, and any other text is used as it is, with `{repository}` + * replaced by the repository name. + * @param repository - The repository the PRs are in. + * @returns The note, or undefined when there should be none. + */ +export function resolveReminderNote( + value: string | undefined, + repository: string, +): string | undefined { + if (value === undefined || value.trim() === DEFAULT_NOTE_KEYWORD) { + return buildDefaultNote(repository); + } + const note = value.trim(); + return note + ? note.replaceAll('{repository}', escapeSlack(repository)) + : undefined; +} diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 49918a13..3465e161 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -15,7 +15,7 @@ import type { PullRequest, Reminder } from './types.mts'; const MAX_TITLE_LENGTH = 200; /** Shown in front of each PR to tell its CI state at a glance. */ -const CI_ICONS: Record = { +export const CI_ICONS: Record = { passing: ':white_check_mark:', failing: ':warning:', pending: ':hourglass_flowing_sand:', diff --git a/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts b/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts new file mode 100644 index 00000000..699332d1 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; + +import { resolveReminderNote } from '../../dependabot-pr-reminder/reminder-note.mts'; +import { CI_ICONS } from '../../dependabot-pr-reminder/slack-payload.mts'; +import { MAX_SECTION_LENGTH } from '../../shared/slack-blocks.mts'; + +describe('resolveReminderNote', () => { + it.each([undefined, 'default', ' default '])( + 'gives the built in note for %j', + (value) => { + const note = resolveReminderNote(value, 'MetaMask/core'); + expect(note).toContain('Some packages in MetaMask/core'); + expect(note).toContain('1. Read the changelogs'); + expect(note).toContain('5. Merge once CI passes'); + }, + ); + + it('explains every icon the message uses', () => { + const note = resolveReminderNote('default', 'MetaMask/core'); + for (const icon of Object.values(CI_ICONS)) { + expect(note).toContain(icon); + } + }); + + it('fits in one Slack section', () => { + const note = resolveReminderNote('default', 'MetaMask/core'); + expect(note?.length).toBeLessThan(MAX_SECTION_LENGTH); + }); + + it('gives no note for an empty value', () => { + expect(resolveReminderNote('', 'MetaMask/core')).toBeUndefined(); + expect(resolveReminderNote(' ', 'MetaMask/core')).toBeUndefined(); + }); + + it('uses custom text and fills in the repository', () => { + expect(resolveReminderNote('Own {repository}.', 'MetaMask/core')).toBe( + 'Own MetaMask/core.', + ); + }); + + it('escapes the repository name', () => { + expect(resolveReminderNote('default', 'a/c')).toContain('a<b>/c'); + }); +}); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 7bea1b07..2f7123ce 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -44,8 +44,8 @@ on: reminder-note: required: false type: string - default: 'Tagged teams own these PRs: read the changelog, test the update, approve it and merge it. If a PR is listed under the wrong team, say so in a reply.' - description: 'Note shown under the headline of the message, as Slack mrkdwn. Empty for none' + default: 'default' + description: 'Note shown under the headline, as Slack mrkdwn. `default` uses the built in instructions, empty for none. `{repository}` is replaced by the repository name' environment: required: false type: string From d4bdbede70259b7981c2aae7dd33f5125d15c0b3 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 25 Nov 2026 10:33:54 +0100 Subject: [PATCH 29/61] feat: redesign the Dependabot reminder message Header with counts, a short note with an optional guide link, then PRs grouped by CI state (needs a fix, in progress, shared by many teams, CI passing). Each PR shows the package and versions with its teams tagged under it, and there is an icon legend at the bottom. Adds a guide-url input and parses Dependabot titles. --- .../actions/remind-dependabot-prs/action.yml | 7 +- .../scripts/dependabot-pr-reminder/cli.mts | 8 +- .../dependabot-title.mts | 62 ++ .../dependabot-pr-reminder/reminder-note.mts | 52 +- .../dependabot-pr-reminder/slack-payload.mts | 379 ++++++++---- .../dependabot-title.test.mts | 48 ++ .../tests/dependabot-pr-reminder/fixtures.mts | 6 +- .../reminder-note.test.mts | 59 +- .../slack-payload.test.mts | 577 ++++++++---------- .github/workflows/remind-dependabot-prs.yml | 8 +- 10 files changed, 695 insertions(+), 511 deletions(-) create mode 100644 .github/scripts/dependabot-pr-reminder/dependabot-title.mts create mode 100644 .github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 92b4968f..1fb930bd 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -24,8 +24,12 @@ inputs: description: 'A PR requested from more than this many teams is listed under the fallback team.' required: false default: '5' + guide-url: + description: 'Link to a guide for handling these PRs, shown under the note. Empty for none.' + required: false + default: '' reminder-note: - description: 'Note shown under the headline, as Slack mrkdwn. `default` uses the built in instructions, empty for none. `{repository}` is replaced by the repository name.' + description: 'Note shown under the counts, as Slack mrkdwn. `default` uses the built in note, empty for none. `{repository}` is replaced by the repository name.' required: false default: 'default' @@ -58,6 +62,7 @@ runs: TOPOLOGY_REF: ${{ inputs.topology-ref }} SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} REMINDER_NOTE: ${{ inputs.reminder-note }} + GUIDE_URL: ${{ inputs.guide-url }} run: | set -euo pipefail node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 26672101..7192a857 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -6,7 +6,7 @@ import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; import { fetchDependabotPullRequests } from './github-api.mts'; -import { resolveReminderNote } from './reminder-note.mts'; +import { parseGuideUrl, resolveReminderNote } from './reminder-note.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; @@ -68,7 +68,11 @@ export async function main(environment: NodeJS.ProcessEnv): Promise { ); } - const note = resolveReminderNote(environment.REMINDER_NOTE, repository); + const note = resolveReminderNote( + environment.REMINDER_NOTE, + repository, + parseGuideUrl(environment.GUIDE_URL), + ); const payload = buildSlackPayload(reminder, topology, { fallbackTeam, repository, diff --git a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts new file mode 100644 index 00000000..e4c38b3d --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts @@ -0,0 +1,62 @@ +import { escapeSlack } from '../shared/slack-blocks.mts'; + +// An optional conventional commit prefix, such as `chore(deps):`. The scope is +// captured so `deps-dev` can be told apart from `deps`. +const PREFIX = String.raw`(?:[a-z]+(?:\(([^)]*)\))?!?:\s*)?`; +const IN_DIRECTORY = String.raw`(?:\s+in\s+(\S+))?`; + +const PACKAGE_TITLE = new RegExp( + `^${PREFIX}[Bb]ump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)${IN_DIRECTORY}$`, + 'u', +); + +const GROUP_TITLE = new RegExp( + `^${PREFIX}[Bb]ump\\s+the\\s+(\\S+)\\s+group(?:\\s+(?:across\\s+\\d+\\s+director(?:y|ies)|in\\s+\\S+))?\\s+with\\s+(\\d+)\\s+updates?$`, + 'u', +); + +/** + * Makes a value safe to show inside a Slack code span. + * + * @param value - The raw value. + * @returns The escaped value, with no backticks. + */ +function code(value: string): string { + return `\`${escapeSlack(value).replaceAll('`', "'")}\``; +} + +/** + * Turns a Dependabot pull request title into a short description of the + * update, as Slack mrkdwn. For example `chore(deps): bump foo from 1.0.0 to + * 2.0.0` becomes `foo 1.0.0 → 2.0.0`, and a group update becomes + * `name group, 7 updates`. + * + * @param title - The pull request title. + * @returns The description, or undefined when the title is not a Dependabot + * title this knows how to read. + */ +export function describeUpdate(title: string): string | undefined { + const trimmed = title.trim(); + + const packageMatch = PACKAGE_TITLE.exec(trimmed); + if (packageMatch) { + const [, scope, name, from, to, directory] = packageMatch; + if (name && from && to) { + return [ + `${code(name)} ${escapeSlack(from)} → ${escapeSlack(to)}`, + scope?.includes('dev') ? ' (dev)' : '', + directory ? ` · ${code(directory)}` : '', + ].join(''); + } + } + + const groupMatch = GROUP_TITLE.exec(trimmed); + if (groupMatch) { + const [, , name, count] = groupMatch; + if (name && count) { + return `${code(name)} group, ${count} ${count === '1' ? 'update' : 'updates'}`; + } + } + + return undefined; +} diff --git a/.github/scripts/dependabot-pr-reminder/reminder-note.mts b/.github/scripts/dependabot-pr-reminder/reminder-note.mts index 55908ad0..128316d3 100644 --- a/.github/scripts/dependabot-pr-reminder/reminder-note.mts +++ b/.github/scripts/dependabot-pr-reminder/reminder-note.mts @@ -1,29 +1,29 @@ import { escapeSlack } from '../shared/slack-blocks.mts'; -import { CI_ICONS } from './slack-payload.mts'; /** The value of `reminder-note` that selects the built in note. */ export const DEFAULT_NOTE_KEYWORD = 'default'; +const DEFAULT_NOTE = + ':wave: *Is your team tagged?* Check the changelogs, fix CI if it fails, and get approval from every tagged team before merging. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; + +const GUIDE_URL_PATTERN = /^https:\/\/[^\s<>|]+$/u; + /** - * Builds the built in note, which tells teams what to do with the PRs. The icon - * legend is built from the icons the message really uses. + * Checks and returns the guide URL from the `guide-url` setting. * - * @param repository - The repository the PRs are in, such as `MetaMask/core`. - * @returns The note, as Slack mrkdwn. + * @param value - The setting. + * @returns The URL, or undefined when empty. + * @throws If the value is not an https URL that is safe to put in a Slack link. */ -function buildDefaultNote(repository: string): string { - return [ - '*What to do if your team is tagged on a PR below*', - `Some packages in ${escapeSlack(repository)} have outdated dependencies, and Dependabot opened PRs to bump them.`, - '', - '1. Read the changelogs of the dependencies being bumped.', - `2. Check the icon: ${CI_ICONS.passing} CI passes, ${CI_ICONS.failing} CI fails, ${CI_ICONS.pending} CI is still running, ${CI_ICONS.unknown} no checks.`, - '3. If CI fails, work out why and fix it. You can push directly to the PR, but Dependabot stops updating it once you do.', - "4. Have a teammate review and approve it. If the PR touches other teams' packages, work with them to get their changes and approvals too.", - '5. Merge once CI passes and every required team has approved.', - '', - 'PRs under "Shared by many teams" are coordinated by the team tagged on that section.', - ].join('\n'); +export function parseGuideUrl(value: string | undefined): string | undefined { + const trimmed = (value ?? '').trim(); + if (!trimmed) { + return undefined; + } + if (!GUIDE_URL_PATTERN.test(trimmed)) { + throw new Error('GUIDE_URL must be an https URL'); + } + return trimmed; } /** @@ -33,17 +33,21 @@ function buildDefaultNote(repository: string): string { * gives no note, and any other text is used as it is, with `{repository}` * replaced by the repository name. * @param repository - The repository the PRs are in. + * @param guideUrl - A link to a guide, added under the note when there is one. * @returns The note, or undefined when there should be none. */ export function resolveReminderNote( value: string | undefined, repository: string, + guideUrl?: string, ): string | undefined { - if (value === undefined || value.trim() === DEFAULT_NOTE_KEYWORD) { - return buildDefaultNote(repository); + const trimmed = value?.trim(); + const note = + trimmed === undefined || trimmed === DEFAULT_NOTE_KEYWORD + ? DEFAULT_NOTE + : trimmed.replaceAll('{repository}', escapeSlack(repository)); + if (!note) { + return undefined; } - const note = value.trim(); - return note - ? note.replaceAll('{repository}', escapeSlack(repository)) - : undefined; + return guideUrl ? `${note}\n<${guideUrl}|Read the full guide>` : note; } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 3465e161..e2a91a28 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,7 +1,6 @@ import { + MAX_BLOCKS, MAX_SECTION_LENGTH, - capBlocks, - chunkSections, escapeSlack, section, truncateText, @@ -9,92 +8,124 @@ import { import type { SlackBlock } from '../shared/slack-blocks.mts'; import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; +import { describeUpdate } from './dependabot-title.mts'; import type { PullRequest, Reminder } from './types.mts'; -/** Long titles are cut before escaping so a cut can't split a link or entity. */ -const MAX_TITLE_LENGTH = 200; +export type HeaderBlock = { + type: 'header'; + text: { type: 'plain_text'; text: string; emoji: true }; +}; +export type ContextBlock = { + type: 'context'; + elements: { type: 'mrkdwn'; text: string }[]; +}; +export type DividerBlock = { type: 'divider' }; + +/** Any block in the payload. */ +export type ReminderBlock = + | SlackBlock + | HeaderBlock + | ContextBlock + | DividerBlock; -/** Shown in front of each PR to tell its CI state at a glance. */ +/** Shown to tell a PR's CI state at a glance. */ export const CI_ICONS: Record = { passing: ':white_check_mark:', - failing: ':warning:', + failing: ':x:', pending: ':hourglass_flowing_sand:', unknown: ':white_circle:', }; +const HEADER_TEXT = ':dependabot: Open Dependabot pull requests'; + +/** Long titles are cut before escaping so a cut can't split a link or entity. */ +const MAX_TITLE_LENGTH = 200; + +/** A block and the team mentions in it, so only shown teams get pinged. */ +type Entry = { block: ReminderBlock; handles: string[] }; + +/** One pull request ready to show, with the mentions in its text. */ +type Item = { text: string; handles: string[] }; + +const divider: DividerBlock = { type: 'divider' }; + /** - * Formats pull requests as bulleted Slack links, one line each. + * Describes a pull request, as the package and versions when its title is a + * Dependabot title we can read, and as the cut down title otherwise. * - * @param pullRequests - The pull requests to list. - * @param showTeamCount - Whether to add how many teams were requested. - * @returns The bulleted lines. + * @param pullRequest - The pull request. + * @returns The description, as Slack mrkdwn. */ -function formatPullRequestLines( - pullRequests: PullRequest[], - showTeamCount: boolean, -): string[] { - return pullRequests.map( - ({ url, number, title, requestedTeams, ciState }) => - `• ${CI_ICONS[ciState]} <${url}|#${number} ${escapeSlack(truncateText(title, MAX_TITLE_LENGTH))}>${ - showTeamCount ? ` (${requestedTeams.length} teams)` : '' - }`, +function describePullRequest(pullRequest: PullRequest): string { + const { title } = pullRequest; + return ( + describeUpdate(title) ?? escapeSlack(truncateText(title, MAX_TITLE_LENGTH)) ); } /** - * Groups pull requests by the teams they were requested from, so each PR is - * listed once, under all of its teams. PRs with the same set of teams share a - * group. Groups and teams keep the order in which they first appear. + * Packs items into section blocks that fit Slack's limit. The heading is + * repeated on every block, and items are separated by a blank line. * - * @param byTeam - Each team with its pull requests. - * @returns The groups of teams and the pull requests they share. + * @param heading - The heading shown on top of each block. + * @param headingHandles - The mentions in the heading. + * @param items - The items to list. + * @returns One or more blocks. */ -function groupPullRequestsByTeams( - byTeam: Reminder['byTeam'], -): { teams: string[]; pullRequests: PullRequest[] }[] { - const teamsByPullRequest = new Map< - number, - { pullRequest: PullRequest; teams: string[] } - >(); - for (const [team, pullRequests] of Object.entries(byTeam)) { - for (const pullRequest of pullRequests) { - const entry = teamsByPullRequest.get(pullRequest.number); - if (entry) { - entry.teams.push(team); - } else { - teamsByPullRequest.set(pullRequest.number, { - pullRequest, - teams: [team], - }); - } +function packItems( + heading: string, + headingHandles: string[], + items: Item[], +): Entry[] { + const budget = Math.max(MAX_SECTION_LENGTH - heading.length - 1, 1); + const entries: Entry[] = []; + let current: Item[] = []; + let length = 0; + + const flush = (): void => { + if (current.length > 0) { + entries.push({ + block: section( + `${heading}\n${current.map(({ text }) => text).join('\n\n')}`, + ), + handles: [ + ...headingHandles, + ...current.flatMap(({ handles }) => handles), + ], + }); + current = []; + length = 0; } - } + }; - const groups = new Map< - string, - { teams: string[]; pullRequests: PullRequest[] } - >(); - for (const { pullRequest, teams } of teamsByPullRequest.values()) { - const key = [...teams].sort().join(','); - const group = groups.get(key); - if (group) { - group.pullRequests.push(pullRequest); - } else { - groups.set(key, { teams, pullRequests: [pullRequest] }); + for (const item of items) { + const text = truncateText(item.text, budget); + const added = text.length + (current.length > 0 ? 2 : 0); + if (current.length > 0 && length + added > budget) { + flush(); } + length += text.length + (current.length > 0 ? 2 : 0); + current.push({ text, handles: item.handles }); } - return [...groups.values()]; + flush(); + return entries; } /** * Builds the Slack incoming webhook payload for a reminder. * + * The message has a headline with counts, an optional note, then the pull + * requests in groups: the ones that need a fix, the ones still running, the + * ones shared by many teams, and the ones that pass CI. Each pull request is + * listed once, with all of its teams tagged under it. + * * @param reminder - The classified reminder. * @param topology - The team topology used to look up Slack user groups. * @param options - Payload options. - * @param options.fallbackTeam - The team tagged on the fallback sections. - * @param options.repository - The repository name shown in the header. - * @param options.note - Text shown right under the headline, as Slack mrkdwn. Left out + * @param options.fallbackTeam - The team that coordinates shared pull requests + * and the ones with no team. + * @param options.repository - The repository, in `owner/name` form. + * @param options.note - Text shown under the counts, as Slack mrkdwn. Left out * when empty. * @returns The payload, or undefined when there is nothing to post. */ @@ -105,30 +136,9 @@ export function buildSlackPayload( ): | { text: string; - blocks: SlackBlock[]; + blocks: ReminderBlock[]; } | undefined { - const teamEntries = Object.entries(reminder.byTeam).filter( - ([, pullRequests]) => pullRequests.length > 0, - ); - const teamGroups = groupPullRequestsByTeams(reminder.byTeam); - const fallbackSections = [ - { - label: 'Shared by many teams', - pullRequests: reminder.fallback.sharedByManyTeams, - showTeamCount: true, - }, - { - label: undefined, - pullRequests: reminder.fallback.noTeam, - showTeamCount: false, - }, - ].filter(({ pullRequests }) => pullRequests.length > 0); - - if (teamEntries.length === 0 && fallbackSections.length === 0) { - return undefined; - } - // A handle like `@core-platform-team` in message text becomes a mention. A // team without one is shown as a plain name. const tag = (team: string): { text: string; handle?: string } => { @@ -138,65 +148,168 @@ export function buildSlackPayload( : { text: escapeSlack(normalizeTeamSlug(team)) }; }; - const headline = `*[${escapeSlack(options.repository)}] Open Dependabot pull requests*`; - // Each section remembers its team mention, so only teams whose section is - // actually sent get pinged. - // The note goes right under the headline. The block cap only cuts from the - // end, so it is always shown. - const entries: { block: SlackBlock; handles: string[] }[] = [ - { block: section(headline), handles: [] }, + // List each PR once, with every team it was requested from. + const owned = new Map< + number, + { pullRequest: PullRequest; teams: string[] } + >(); + for (const [team, pullRequests] of Object.entries(reminder.byTeam)) { + for (const pullRequest of pullRequests) { + const entry = owned.get(pullRequest.number); + if (entry) { + entry.teams.push(team); + } else { + owned.set(pullRequest.number, { pullRequest, teams: [team] }); + } + } + } + for (const pullRequest of reminder.fallback.noTeam) { + owned.set(pullRequest.number, { + pullRequest, + teams: [options.fallbackTeam], + }); + } + const shared = reminder.fallback.sharedByManyTeams; + + const everyPullRequest = [ + ...[...owned.values()].map(({ pullRequest }) => pullRequest), + ...shared, + ]; + if (everyPullRequest.length === 0) { + return undefined; + } + + const ownedItem = ( + { pullRequest, teams }: { pullRequest: PullRequest; teams: string[] }, + withIcon: boolean, + ): Item => { + const tags = teams.map(tag); + const icon = withIcon ? `${CI_ICONS[pullRequest.ciState]} ` : ''; + return { + text: `${icon}<${pullRequest.url}|#${pullRequest.number}> ${describePullRequest(pullRequest)}\n${tags.map(({ text }) => text).join(' ')}`, + handles: tags.flatMap(({ handle }) => (handle ? [handle] : [])), + }; + }; + + const ownedBy = ( + states: PullRequest['ciState'][], + ): { pullRequest: PullRequest; teams: string[] }[] => + [...owned.values()].filter(({ pullRequest }) => + states.includes(pullRequest.ciState), + ); + + const fallbackTag = tag(options.fallbackTeam); + const groups: Entry[][] = [ + packItems( + `*${CI_ICONS.failing} Needs a fix*`, + [], + ownedBy(['failing']).map((entry) => ownedItem(entry, false)), + ), + packItems( + `*${CI_ICONS.pending} In progress*`, + [], + ownedBy(['pending', 'unknown']).map((entry) => ownedItem(entry, true)), + ), + packItems( + `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${fallbackTag.text}`, + fallbackTag.handle ? [fallbackTag.handle] : [], + shared.map((pullRequest) => ({ + text: `${CI_ICONS[pullRequest.ciState]} <${pullRequest.url}|#${pullRequest.number}> ${describePullRequest(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, + handles: [], + })), + ), + packItems( + `*${CI_ICONS.passing} CI passing*`, + [], + ownedBy(['passing']).map((entry) => ownedItem(entry, false)), + ), + ].filter((group) => group.length > 0); + + const middle: Entry[] = groups.flatMap((group, index) => [ + ...(index > 0 ? [{ block: divider, handles: [] }] : []), + ...group, + ]); + + // The counts line, only showing the states that have pull requests. + const counts = ( + [ + ['passing', 'passing'], + ['failing', 'failing'], + ['pending', 'running'], + ['unknown', 'no checks'], + ] as const + ).flatMap(([state, label]) => { + const total = everyPullRequest.filter( + ({ ciState }) => ciState === state, + ).length; + return total > 0 ? [`${CI_ICONS[state]} ${total} ${label}`] : []; + }); + const repository = escapeSlack(options.repository); + + const top: ReminderBlock[] = [ + { + type: 'header', + text: { type: 'plain_text', text: HEADER_TEXT, emoji: true }, + }, + { + type: 'context', + elements: [ + { + type: 'mrkdwn', + text: [ + ``, + `*${everyPullRequest.length}* open`, + ...counts, + ].join(' · '), + }, + ], + }, ...(options.note - ? [ - { - block: section(truncateText(options.note, MAX_SECTION_LENGTH)), - handles: [], - }, - ] + ? [section(truncateText(options.note, MAX_SECTION_LENGTH))] : []), + divider, ]; - const addSections = ( - teams: string[], - pullRequests: PullRequest[], + const bottom: ReminderBlock[] = [ + divider, { - label, - showTeamCount = false, - }: { label?: string | undefined; showTeamCount?: boolean } = {}, - ): void => { - const tags = teams.map(tag); - const header = tags.map(({ text }) => text).join(' '); - const fullHeader = label ? `${header} *${label}*` : header; - const handles = tags.flatMap(({ handle }) => (handle ? [handle] : [])); - for (const text of chunkSections( - fullHeader, - formatPullRequestLines(pullRequests, showTeamCount), - )) { - entries.push({ block: section(text), handles }); - } - }; - for (const { teams, pullRequests } of teamGroups) { - addSections(teams, pullRequests); - } - for (const { label, pullRequests, showTeamCount } of fallbackSections) { - addSections([options.fallbackTeam], pullRequests, { label, showTeamCount }); - } + type: 'context', + elements: [ + { + type: 'mrkdwn', + text: `${CI_ICONS.passing} CI passes · ${CI_ICONS.failing} CI fails · ${CI_ICONS.pending} CI running · ${CI_ICONS.unknown} no checks`, + }, + ], + }, + ]; - const { blocks, omitted } = capBlocks( - entries.map(({ block }) => block), - (omittedBlocks) => - `…and ${omittedBlocks.reduce( - (total, block) => - total + - block.text.text.split('\n').filter((line) => line.startsWith('•')) - .length, - 0, - )} more pull request(s) not shown`, - ); - const shownEntries = - omitted.length > 0 ? entries.slice(0, blocks.length - 1) : entries; - const mentions = new Set(shownEntries.flatMap(({ handles }) => handles)); + // Keep the top and bottom, and cut the middle if the message is too long. + const room = MAX_BLOCKS - top.length - bottom.length; + let shown = middle; + let overflow: ReminderBlock[] = []; + if (middle.length > room) { + shown = middle.slice(0, room - 1); + const omitted = middle.slice(room - 1); + const omittedCount = omitted.reduce( + (total, { block }) => + total + + ('text' in block + ? (block.text.text.match(/\|#\d+>/gu) ?? []).length + : 0), + 0, + ); + overflow = [section(`…and ${omittedCount} more pull request(s) not shown`)]; + } + const mentions = new Set(shown.flatMap(({ handles }) => handles)); return { - text: [headline, ...mentions].join(' '), - blocks, + text: [`Open Dependabot pull requests in ${repository}`, ...mentions].join( + ' ', + ), + blocks: [ + ...top, + ...shown.map(({ block }) => block), + ...overflow, + ...bottom, + ], }; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts new file mode 100644 index 00000000..261d9d67 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; + +import { describeUpdate } from '../../dependabot-pr-reminder/dependabot-title.mts'; + +describe('describeUpdate', () => { + it('reads a package bump', () => { + expect( + describeUpdate('chore(deps): bump @noble/curves from 1.9.7 to 2.4.0'), + ).toBe('`@noble/curves` 1.9.7 → 2.4.0'); + }); + + it('marks a dev dependency', () => { + expect( + describeUpdate('chore(deps-dev): bump jsdom from 27.4.0 to 31.0.1'), + ).toBe('`jsdom` 27.4.0 → 31.0.1 (dev)'); + }); + + it('reads a title without a prefix and with a directory', () => { + expect(describeUpdate('Bump foo from 1.0.0 to 1.1.0 in /packages/a')).toBe( + '`foo` 1.0.0 → 1.1.0 · `/packages/a`', + ); + }); + + it('reads a group update across directories', () => { + expect( + describeUpdate( + 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', + ), + ).toBe('`external-non-major` group, 7 updates'); + }); + + it('reads a group update in a directory and a single update', () => { + expect(describeUpdate('Bump the tools group in /app with 1 update')).toBe( + '`tools` group, 1 update', + ); + }); + + it('returns undefined for titles it does not know', () => { + expect(describeUpdate('Bump a and b')).toBeUndefined(); + expect(describeUpdate('Something else entirely')).toBeUndefined(); + }); + + it('escapes Slack characters and backticks', () => { + expect(describeUpdate('bump a&b from 1<2 to 3>4')).toBe( + '`a&b` 1<2 → 3>4', + ); + }); +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index a2d6dfc5..1342135c 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -1,5 +1,5 @@ +import type { ReminderBlock } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; -import type { SlackBlock } from '../../shared/slack-blocks.mts'; /** * Builds a pull request for tests. @@ -24,6 +24,6 @@ export function pr(overrides: Partial = {}): PullRequest { * @param block - The block, if any. * @returns The text, or an empty string when there is no block. */ -export function sectionText(block: SlackBlock | undefined): string { - return block?.text.text ?? ''; +export function sectionText(block: ReminderBlock | undefined): string { + return block && 'text' in block ? block.text.text : ''; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts b/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts index 699332d1..04998ba1 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts @@ -1,7 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { resolveReminderNote } from '../../dependabot-pr-reminder/reminder-note.mts'; -import { CI_ICONS } from '../../dependabot-pr-reminder/slack-payload.mts'; +import { + parseGuideUrl, + resolveReminderNote, +} from '../../dependabot-pr-reminder/reminder-note.mts'; import { MAX_SECTION_LENGTH } from '../../shared/slack-blocks.mts'; describe('resolveReminderNote', () => { @@ -9,27 +11,23 @@ describe('resolveReminderNote', () => { 'gives the built in note for %j', (value) => { const note = resolveReminderNote(value, 'MetaMask/core'); - expect(note).toContain('Some packages in MetaMask/core'); - expect(note).toContain('1. Read the changelogs'); - expect(note).toContain('5. Merge once CI passes'); + expect(note).toContain('*Is your team tagged?*'); + expect(note).toContain('Check the changelogs'); + expect(note).toContain('Dependabot stops updating it'); }, ); - it('explains every icon the message uses', () => { - const note = resolveReminderNote('default', 'MetaMask/core'); - for (const icon of Object.values(CI_ICONS)) { - expect(note).toContain(icon); - } - }); - it('fits in one Slack section', () => { const note = resolveReminderNote('default', 'MetaMask/core'); expect(note?.length).toBeLessThan(MAX_SECTION_LENGTH); }); - it('gives no note for an empty value', () => { + it('gives no note for an empty value, even with a guide', () => { expect(resolveReminderNote('', 'MetaMask/core')).toBeUndefined(); expect(resolveReminderNote(' ', 'MetaMask/core')).toBeUndefined(); + expect( + resolveReminderNote('', 'MetaMask/core', 'https://example.com/guide'), + ).toBeUndefined(); }); it('uses custom text and fills in the repository', () => { @@ -39,6 +37,39 @@ describe('resolveReminderNote', () => { }); it('escapes the repository name', () => { - expect(resolveReminderNote('default', 'a/c')).toContain('a<b>/c'); + expect(resolveReminderNote('Own {repository}.', 'a/c')).toBe( + 'Own a<b>/c.', + ); + }); + + it('adds a link to the guide under the note', () => { + expect( + resolveReminderNote('Own it.', 'MetaMask/core', 'https://example.com/g'), + ).toBe('Own it.\n'); + expect( + resolveReminderNote('default', 'MetaMask/core', 'https://example.com/g'), + ).toMatch(/\n$/u); + }); +}); + +describe('parseGuideUrl', () => { + it('returns undefined when unset or blank', () => { + expect(parseGuideUrl(undefined)).toBeUndefined(); + expect(parseGuideUrl(' ')).toBeUndefined(); + }); + + it('returns an https URL', () => { + expect(parseGuideUrl(' https://example.com/guide.md ')).toBe( + 'https://example.com/guide.md', + ); + }); + + it.each([ + 'http://example.com', + 'example.com', + 'https://a.com/x>y', + 'https://a b', + ])('rejects %s', (value) => { + expect(() => parseGuideUrl(value)).toThrow('GUIDE_URL'); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index e367dfab..cd1edfdd 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -1,440 +1,351 @@ import { assert, describe, expect, it } from 'vitest'; import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; -import type { Reminder } from '../../dependabot-pr-reminder/types.mts'; +import type { + PullRequest, + Reminder, +} from '../../dependabot-pr-reminder/types.mts'; import { pr, sectionText } from './fixtures.mts'; -describe('buildSlackPayload', () => { - const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; - const emptyReminder = (): Reminder => ({ - byTeam: {}, - fallback: { sharedByManyTeams: [], noTeam: [] }, - }); - const allText = (payload: { text: string; blocks: unknown[] }): string => - `${payload.text}\n${JSON.stringify(payload.blocks)}`; +const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; + +const topology = { + a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, + b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, + platform: { + githubHandle: 'MetaMask/platform', + slackHandle: { team: '@platform-team' }, + }, +}; + +/** + * Builds a reminder for tests. + * + * @param parts - The parts of the reminder. + * @param parts.byTeam - Pull requests by team. + * @param parts.shared - Pull requests shared by many teams. + * @param parts.noTeam - Pull requests with no team. + * @returns The reminder. + */ +function reminder( + parts: { + byTeam?: Record; + shared?: PullRequest[]; + noTeam?: PullRequest[]; + } = {}, +): Reminder { + return { + byTeam: parts.byTeam ?? {}, + fallback: { + sharedByManyTeams: parts.shared ?? [], + noTeam: parts.noTeam ?? [], + }, + }; +} - it('returns undefined for an empty reminder', () => { - expect(buildSlackPayload(emptyReminder(), {}, options)).toBeUndefined(); +describe('buildSlackPayload', () => { + it('returns undefined when there are no pull requests', () => { + expect(buildSlackPayload(reminder(), {}, options)).toBeUndefined(); }); - it('tags a team using slackHandle.team', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr({ number: 7 })]; + it('starts with a header, the counts and a divider, and ends with a legend', () => { const payload = buildSlackPayload( - reminder, - { - 'core-platform': { - githubHandle: 'MetaMask/core-platform', - slackHandle: { team: '@core-platform-team' }, - }, - }, + reminder({ byTeam: { a: [pr({ ciState: 'passing' })] } }), + topology, options, ); assert.ok(payload); - expect(allText(payload)).toMatch(/@core-platform-team/u); - expect(allText(payload)).toMatch(/#7/u); - expect(payload.text).toMatch(/@core-platform-team/u); - expect(allText(payload)).not.toMatch(/:dependabot:/u); - }); - - it('matches githubHandle regardless of case or @ prefix', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr()]; - const payload = buildSlackPayload( - reminder, - { - key: { - githubHandle: '@MetaMask/Core-Platform', - slackHandle: { team: '@nine-team' }, - }, - }, - options, + const types = payload.blocks.map(({ type }) => type); + expect(types.slice(0, 3)).toStrictEqual(['header', 'context', 'divider']); + expect(types.slice(-2)).toStrictEqual(['divider', 'context']); + expect(JSON.stringify(payload.blocks[0])).toContain( + ':dependabot: Open Dependabot pull requests', + ); + expect(JSON.stringify(payload.blocks.at(-1))).toContain( + ':white_check_mark: CI passes · :x: CI fails', ); - assert.ok(payload); - expect(allText(payload)).toMatch(/@nine-team/u); - }); - - it('falls back to the plain team name when topology has no match', () => { - const reminder = emptyReminder(); - reminder.byTeam['core-platform'] = [pr()]; - const payload = buildSlackPayload(reminder, {}, options); - assert.ok(payload); - expect(allText(payload)).toMatch(/core-platform/u); - expect(allText(payload)).not.toMatch(/@core-platform-team/u); - }); - - it('escapes &, <, > in PR titles', () => { - const reminder = emptyReminder(); - reminder.byTeam.a = [pr({ title: 'Bump & b > c' })]; - const payload = buildSlackPayload(reminder, {}, options); - assert.ok(payload); - expect(allText(payload)).toMatch(/Bump <a> & b > c/u); }); - it('renders fallback sections under the fallback team', () => { - const reminder = emptyReminder(); - reminder.fallback.noTeam = [pr({ number: 3 })]; + it('shows the repository link, how many are open, and only the states present', () => { const payload = buildSlackPayload( - reminder, - { - platform: { - githubHandle: 'MetaMask/platform', - slackHandle: { team: '@platform-team' }, + reminder({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'failing' }), + ], }, - }, + }), + topology, options, ); assert.ok(payload); - const text = allText(payload); - expect(text).toMatch(/@platform-team/u); - expect(text).toMatch(/#3/u); + expect(JSON.stringify(payload.blocks[1])).toContain( + ' · *3* open · :white_check_mark: 1 passing · :x: 2 failing', + ); + expect(JSON.stringify(payload.blocks[1])).not.toContain('running'); }); -}); -describe('buildSlackPayload chunking', () => { - it('splits a long team list into sections under the Slack limit', () => { - const pullRequests = Array.from({ length: 60 }, (_, index) => - pr({ - number: index + 1, - title: `Bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, - url: `https://github.com/MetaMask/example/pull/${index + 1}`, - }), - ); - const reminder: Reminder = { - byTeam: { wallet: pullRequests }, - fallback: { sharedByManyTeams: [], noTeam: [] }, - }; + it('puts the note between the counts and the first divider', () => { const payload = buildSlackPayload( - reminder, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, + reminder({ byTeam: { a: [pr()] } }), + topology, + { ...options, note: 'Own it.' }, ); assert.ok(payload); - const texts = payload.blocks.map(sectionText); - expect(texts.length).toBeGreaterThan(3); - for (const text of texts) { - assert.ok(text.length <= 3000, `section has ${text.length} characters`); - } - const joined = texts.join('\n'); - for (const { number } of pullRequests) { - assert.ok(joined.includes(`#${number} `), `PR #${number} is missing`); - } + expect(payload.blocks.map(({ type }) => type).slice(0, 4)).toStrictEqual([ + 'header', + 'context', + 'section', + 'divider', + ]); + expect(sectionText(payload.blocks[2])).toBe('Own it.'); }); -}); - -describe('buildSlackPayload limits and lookup', () => { - const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - it('caps blocks at 50 and appends an overflow line', () => { - const byTeam: Reminder['byTeam'] = {}; - for (let index = 0; index < 80; index++) { - byTeam[`team-${index}`] = [pr({ number: index + 1 })]; - } + it('leaves the note out when there is none', () => { const payload = buildSlackPayload( - { - byTeam, - fallback: { sharedByManyTeams: [], noTeam: [] }, - }, - {}, + reminder({ byTeam: { a: [pr()] } }), + topology, options, ); assert.ok(payload); - expect(payload.blocks.length).toBeLessThanOrEqual(50); - expect(sectionText(payload.blocks.at(-1))).toMatch(/…and \d+ more/u); + expect(payload.blocks.map(({ type }) => type)).not.toContain('Own it.'); + expect(payload.blocks[2]?.type).toBe('divider'); }); - it('does not throw on null topology entries', () => { + it('groups by CI state in order, with dividers between the groups', () => { const payload = buildSlackPayload( - { - byTeam: { a: [pr()] }, - fallback: { sharedByManyTeams: [], noTeam: [] }, - }, - { - bad: null, - good: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, - }, + reminder({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'pending' }), + ], + }, + shared: [pr({ number: 4, ciState: 'failing', requestedTeams: ['x'] })], + }), + topology, options, ); - expect(payload?.text).toMatch(/@a-team/u); + assert.ok(payload); + const headings = payload.blocks + .filter(({ type }) => type === 'section') + .map((block) => sectionText(block).split('\n')[0]); + expect(headings).toStrictEqual([ + '*:x: Needs a fix*', + '*:hourglass_flowing_sand: In progress*', + '*:busts_in_silhouette: Shared by many teams*', + '*:white_check_mark: CI passing*', + ]); }); -}); - -describe('buildSlackPayload mentions and titles', () => { - const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { sharedByManyTeams: [], noTeam: [] }; - it('does not turn @ text in titles into mentions', () => { + it('shows the package and versions and tags the teams under each PR', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr({ title: 'Bump @here/x' })] }, fallback }, - {}, + reminder({ + byTeam: { + a: [pr({ number: 7, ciState: 'failing' })], + b: [pr({ number: 7, ciState: 'failing' })], + plain: [pr({ number: 7, ciState: 'failing' })], + }, + }), + topology, options, ); assert.ok(payload); - expect(payload).not.toHaveProperty('link_names'); + const text = sectionText(payload.blocks[3]); + expect(text).toBe( + '*:x: Needs a fix*\n `foo` 1.0.0 → 1.0.1\n@a-team @b-team plain', + ); }); - it('shortens long titles before wrapping them in a link', () => { + it('lists each PR once, even when many teams share it', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr({ title: `${'x'.repeat(500)} & more` })] }, fallback }, - {}, + reminder({ + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 2 })], + }, + }), + topology, options, ); assert.ok(payload); - expect(sectionText(payload.blocks[1])).toMatch(/x…>$/u); - expect(sectionText(payload.blocks[1])).not.toContain('&'); + const all = JSON.stringify(payload.blocks); + expect(all.match(/\|#1>/gu)).toHaveLength(1); + expect(all.match(/\|#2>/gu)).toHaveLength(1); }); - it('only pings teams whose section is shown', () => { - const byTeam: Reminder['byTeam'] = {}; - const topology: Record< - string, - { githubHandle: string; slackHandle: { team: string } } - > = {}; - for (let index = 0; index < 80; index++) { - byTeam[`team-${index}`] = [pr({ number: index + 1 })]; - topology[`t${index}`] = { - githubHandle: `MetaMask/team-${index}`, - slackHandle: { team: `@g${index}` }, - }; - } - const payload = buildSlackPayload({ byTeam, fallback }, topology, options); - assert.ok(payload); - expect(payload.blocks).toHaveLength(50); - expect(payload.text).toContain('@g0'); - expect(payload.text).not.toContain('@g79'); - }); -}); - -describe('buildSlackPayload grouping', () => { - const options = { fallbackTeam: 'f', repository: 'MetaMask/example' }; - const fallback = { sharedByManyTeams: [], noTeam: [] }; - const topology = { - a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, - b: { githubHandle: 'MetaMask/b', slackHandle: { team: '@b-team' } }, - }; - - it('lists a shared set of PRs once under all of its teams', () => { - const shared = [pr({ number: 1 }), pr({ number: 2 })]; + it('shows a PR with no team under the fallback team', () => { const payload = buildSlackPayload( - { - byTeam: { a: shared, b: [pr({ number: 2 }), pr({ number: 1 })] }, - fallback, - }, + reminder({ noTeam: [pr({ number: 5, ciState: 'passing' })] }), topology, options, ); assert.ok(payload); - expect(payload.blocks).toHaveLength(2); - const [, sharedBlock] = payload.blocks; - expect(sectionText(sharedBlock).split('\n')[0]).toBe('@a-team @b-team'); - expect(sectionText(sharedBlock).match(/#1 /gu)).toHaveLength(1); - expect(payload.text).toContain('@a-team @b-team'); + expect(sectionText(payload.blocks[3])).toBe( + '*:white_check_mark: CI passing*\n `foo` 1.0.0 → 1.0.1\n@platform-team', + ); }); - it('lists each PR once, under all of its teams', () => { + it('shows shared PRs with an icon and team count, coordinated by the fallback team', () => { const payload = buildSlackPayload( - { - byTeam: { - a: [pr({ number: 1 }), pr({ number: 2 })], - b: [pr({ number: 2 })], - c: [pr({ number: 2 })], - }, - fallback, - }, + reminder({ + shared: [ + pr({ + number: 9, + ciState: 'failing', + requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'], + }), + ], + }), topology, options, ); assert.ok(payload); - expect(payload.blocks).toHaveLength(3); - expect(sectionText(payload.blocks[1]).split('\n')[0]).toBe('@a-team'); - expect(sectionText(payload.blocks[1])).toMatch(/#1 /u); - expect(sectionText(payload.blocks[2]).split('\n')[0]).toBe( - '@a-team @b-team c', + const text = sectionText(payload.blocks[3]); + expect(text.split('\n')[0]).toBe( + '*:busts_in_silhouette: Shared by many teams*', ); - expect(sectionText(payload.blocks[2])).toMatch(/#2 /u); - expect(JSON.stringify(payload.blocks).match(/#2 /gu)).toHaveLength(1); + expect(text.split('\n')[1]).toBe('Coordinated by @platform-team'); + expect(text).toMatch(/:x: <[^>]*\|#9> `foo` 1\.0\.0 → 1\.0\.1 · 6 teams$/u); }); - it('puts PRs with the same teams together', () => { + it('shows an icon per PR in the in progress group', () => { const payload = buildSlackPayload( - { + reminder({ byTeam: { - a: [pr({ number: 1 }), pr({ number: 2 })], - b: [pr({ number: 2 }), pr({ number: 1 })], + a: [ + pr({ number: 1, ciState: 'pending' }), + pr({ number: 2, ciState: 'unknown' }), + ], }, - fallback, - }, + }), topology, options, ); assert.ok(payload); - expect(payload.blocks).toHaveLength(2); - expect(sectionText(payload.blocks[1]).split('\n')).toHaveLength(3); + const text = sectionText(payload.blocks[3]); + expect(text).toMatch(/:hourglass_flowing_sand: <[^>]*\|#1>/u); + expect(text).toMatch(/:white_circle: <[^>]*\|#2>/u); }); - it('shows a team without a handle as plain text next to tagged teams', () => { + it('puts the handles of tagged teams in the top level text', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr()], plain: [pr()] }, fallback }, + reminder({ + byTeam: { a: [pr()], b: [pr()], plain: [pr()] }, + }), topology, options, ); assert.ok(payload); - expect(sectionText(payload.blocks[1]).split('\n')[0]).toBe('@a-team plain'); - expect(payload.text).toContain('@a-team'); + expect(payload.text).toContain('@a-team @b-team'); expect(payload.text).not.toContain('plain'); }); -}); - -describe('buildSlackPayload note', () => { - const fallback = { sharedByManyTeams: [], noTeam: [] }; - it('adds the note as a section right under the headline', () => { + it('escapes the title of a PR it cannot read and cuts it short', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr()] }, fallback }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example', note: 'Own it.' }, + reminder({ + byTeam: { a: [pr({ title: `Odd & ${'x'.repeat(500)}` })] }, + }), + topology, + options, ); assert.ok(payload); - expect(payload.blocks[1]).toStrictEqual({ - type: 'section', - text: { type: 'mrkdwn', text: 'Own it.' }, - }); + const text = sectionText(payload.blocks[3]); + expect(text).toContain('Odd <title> & '); + expect(text).toContain('…'); + expect(text.length).toBeLessThan(500); }); - it('leaves the note out when there is none', () => { + it('does not turn @ text into mentions with link_names', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr()] }, fallback }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, + reminder({ byTeam: { a: [pr({ title: 'Bump @here/x' })] } }), + topology, + options, ); assert.ok(payload); - expect(payload.blocks.map(({ type }) => type)).toStrictEqual([ - 'section', - 'section', - ]); + expect(payload).not.toHaveProperty('link_names'); }); - it('keeps the note when the block cap is hit', () => { - const byTeam: Reminder['byTeam'] = {}; - for (let index = 0; index < 80; index++) { - byTeam[`team-${index}`] = [pr({ number: index + 1 })]; - } - const payload = buildSlackPayload( - { byTeam, fallback }, - {}, - { - fallbackTeam: 'f', - repository: 'MetaMask/example', - note: 'Own it.', - }, + it('splits a long group into blocks under the Slack limit, repeating the heading', () => { + const pullRequests = Array.from({ length: 60 }, (_, index) => + pr({ + number: index + 1, + title: `chore(deps): bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, + ciState: 'failing', + }), ); - assert.ok(payload); - expect(payload.blocks).toHaveLength(50); - expect(sectionText(payload.blocks[1])).toBe('Own it.'); - expect(sectionText(payload.blocks.at(-1))).toMatch(/…and \d+ more/u); - }); - - it('cuts a very long note to fit Slack', () => { const payload = buildSlackPayload( - { byTeam: { a: [pr()] }, fallback }, - {}, - { - fallbackTeam: 'f', - repository: 'MetaMask/example', - note: 'x'.repeat(5000), - }, - ); - assert.ok(payload); - const serialized = JSON.stringify(payload.blocks[1]); - expect(serialized).toContain('…'); - expect(serialized.length).toBeLessThan(2900); - }); -}); - -describe('buildSlackPayload shared by many teams', () => { - const fallback = { - sharedByManyTeams: [ - pr({ number: 9, requestedTeams: ['a', 'b', 'c', 'd'] }), - ], - noTeam: [], - }; - const topology = { - platform: { - githubHandle: 'MetaMask/platform', - slackHandle: { team: '@platform-team' }, - }, - }; - - it('lists the PR under the fallback team with how many teams it has', () => { - const payload = buildSlackPayload({ byTeam: {}, fallback }, topology, { - fallbackTeam: 'platform', - repository: 'MetaMask/example', - }); - assert.ok(payload); - const text = sectionText(payload.blocks[1]); - expect(text.split('\n')[0]).toBe('@platform-team *Shared by many teams*'); - expect(text).toMatch(/#9 .*\(4 teams\)$/u); - expect(payload.text).toContain('@platform-team'); - }); - - it('puts the shared section before the PRs with no team', () => { - const payload = buildSlackPayload( - { - byTeam: {}, - fallback: { - ...fallback, - noTeam: [pr({ number: 3 })], - }, - }, + reminder({ byTeam: { a: pullRequests } }), topology, - { fallbackTeam: 'platform', repository: 'MetaMask/example' }, + options, ); assert.ok(payload); - const headers = payload.blocks - .slice(1) - .map((block) => sectionText(block).split('\n')[0]); - expect(headers).toStrictEqual([ - '@platform-team *Shared by many teams*', - '@platform-team', - ]); + const sections = payload.blocks.filter(({ type }) => type === 'section'); + expect(sections.length).toBeGreaterThan(1); + for (const block of sections) { + expect(sectionText(block).length).toBeLessThanOrEqual(3000); + expect(sectionText(block).startsWith('*:x: Needs a fix*\n')).toBe(true); + } + const all = JSON.stringify(payload.blocks); + for (const { number } of pullRequests) { + expect(all).toContain(`|#${number}>`); + } }); }); -describe('buildSlackPayload CI icons', () => { - const fallback = { sharedByManyTeams: [], noTeam: [] }; +describe('buildSlackPayload block limit', () => { + /** + * Builds many teams that each have their own PR, in a handle each. + * + * @returns The reminder and the topology. + */ + function manyTeams(): { + reminder: Reminder; + topology: Record< + string, + { githubHandle: string; slackHandle: { team: string } } + >; + } { + const byTeam: Reminder['byTeam'] = {}; + const manyTopology: Record< + string, + { githubHandle: string; slackHandle: { team: string } } + > = {}; + for (let index = 0; index < 800; index++) { + byTeam[`team-${index}`] = [ + pr({ + number: index + 1, + title: `chore(deps): bump ${'p'.repeat(150)}${index} from 1.0.0 to 1.0.1`, + ciState: 'failing', + }), + ]; + manyTopology[`t${index}`] = { + githubHandle: `MetaMask/team-${index}`, + slackHandle: { team: `@g${index}` }, + }; + } + return { reminder: reminder({ byTeam }), topology: manyTopology }; + } - it('puts an icon for the CI state in front of each PR', () => { - const payload = buildSlackPayload( - { - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'pending' }), - pr({ number: 4, ciState: 'unknown' }), - ], - }, - fallback, - }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, - ); + it('stays under 50 blocks, keeps the legend, and says how many were left out', () => { + const many = manyTeams(); + const payload = buildSlackPayload(many.reminder, many.topology, options); assert.ok(payload); - const lines = sectionText(payload.blocks[1]).split('\n'); - expect(lines[1]).toMatch(/^• :white_check_mark: .*#1 /u); - expect(lines[2]).toMatch(/^• :warning: .*#2 /u); - expect(lines[3]).toMatch(/^• :hourglass_flowing_sand: .*#3 /u); - expect(lines[4]).toMatch(/^• :white_circle: .*#4 /u); + expect(payload.blocks.length).toBeLessThanOrEqual(50); + expect(payload.blocks.at(-1)?.type).toBe('context'); + expect(JSON.stringify(payload.blocks)).toMatch( + /…and \d+ more pull request\(s\) not shown/u, + ); }); - it('keeps a failing PR under its own team', () => { - const payload = buildSlackPayload( - { byTeam: { a: [pr({ ciState: 'failing' })] }, fallback }, - {}, - { fallbackTeam: 'f', repository: 'MetaMask/example' }, - ); + it('only pings teams whose PRs are shown', () => { + const many = manyTeams(); + const payload = buildSlackPayload(many.reminder, many.topology, options); assert.ok(payload); - expect(payload.blocks).toHaveLength(2); - expect(sectionText(payload.blocks[1]).startsWith('a\n')).toBe(true); + expect(payload.text).toContain('@g0'); + expect(payload.text).not.toContain('@g799'); }); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 2f7123ce..cb33f5e0 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -41,11 +41,16 @@ on: type: number default: 5 description: 'A PR requested from more than this many teams is listed under the fallback team' + guide-url: + required: false + type: string + default: '' + description: 'Link to a guide for handling these PRs, shown under the note. Empty for none' reminder-note: required: false type: string default: 'default' - description: 'Note shown under the headline, as Slack mrkdwn. `default` uses the built in instructions, empty for none. `{repository}` is replaced by the repository name' + description: 'Note shown under the counts, as Slack mrkdwn. `default` uses the built in note, empty for none. `{repository}` is replaced by the repository name' environment: required: false type: string @@ -88,6 +93,7 @@ jobs: topology-ref: ${{ inputs.topology-ref }} shared-team-threshold: ${{ inputs.shared-team-threshold }} reminder-note: ${{ inputs.reminder-note }} + guide-url: ${{ inputs.guide-url }} - name: Send Slack notification if: steps.remind.outputs.has-prs == 'true' From e15026b96aa19356beb7ecdc8e145d992c660748 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 25 Nov 2026 10:55:23 +0100 Subject: [PATCH 30/61] fix: run the reminder script when started through a symlinked path The entry check compared plain paths, so a symlinked directory made it skip main and quietly post nothing. Compare real paths, and make the action fail when the script produced no output. --- .../actions/remind-dependabot-prs/action.yml | 6 ++ .../scripts/dependabot-pr-reminder/cli.mts | 8 ++- .../tests/dependabot-pr-reminder/cli.test.mts | 65 +++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/tests/dependabot-pr-reminder/cli.test.mts diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 1fb930bd..54f33aca 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -66,3 +66,9 @@ runs: run: | set -euo pipefail node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" + + # Fail loudly if the script did not run, instead of quietly posting nothing. + if ! grep -q '^has-prs=' "$GITHUB_OUTPUT"; then + echo "::error::The Dependabot reminder script did not produce an output" + exit 1 + fi diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 7192a857..0819e06a 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -1,3 +1,4 @@ +import { realpathSync } from 'node:fs'; import { appendFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -93,7 +94,12 @@ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); } -if (process.argv[1] === fileURLToPath(import.meta.url)) { +// Compare real paths, since a symlinked directory makes the two differ and the +// script would otherwise silently do nothing. +if ( + process.argv[1] && + realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) +) { main(process.env).catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts new file mode 100644 index 00000000..4a21c1a0 --- /dev/null +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -0,0 +1,65 @@ +import { execFile } from 'node:child_process'; +import { mkdtemp, rm, symlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { afterEach, describe, expect, it } from 'vitest'; + +const execFileAsync = promisify(execFile); + +const SCRIPT = fileURLToPath( + new URL('../../dependabot-pr-reminder/cli.mts', import.meta.url), +); + +describe('cli entry point', () => { + let directory: string | undefined; + + afterEach(async () => { + if (directory) { + await rm(directory, { recursive: true, force: true }); + directory = undefined; + } + }); + + /** + * Runs the script with no settings, so it stops at once with a message. + * + * @param scriptPath - The path to run it through. + * @returns What it printed on stderr. + */ + async function runWithoutSettings(scriptPath: string): Promise<string> { + try { + await execFileAsync(process.execPath, [scriptPath], { + env: { PATH: process.env.PATH ?? '' }, + }); + } catch (error) { + return (error as { stderr?: string }).stderr ?? ''; + } + return ''; + } + + it('runs when started by its plain path', async () => { + expect(await runWithoutSettings(SCRIPT)).toContain('are required'); + }); + + it('runs when started through a path with .. segments', async () => { + const dotted = join( + SCRIPT, + '..', + '..', + 'dependabot-pr-reminder', + 'cli.mts', + ); + expect(await runWithoutSettings(dotted)).toContain('are required'); + }); + + it('runs when started through a symlinked directory', async () => { + directory = await mkdtemp(join(tmpdir(), 'reminder-cli-')); + const link = join(directory, 'scripts'); + await symlink(resolve(SCRIPT, '..'), link); + expect(await runWithoutSettings(join(link, 'cli.mts'))).toContain( + 'are required', + ); + }); +}); From 2d08bb0983074e64778bfb280191e229a7a22a6a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 25 Nov 2026 12:41:37 +0100 Subject: [PATCH 31/61] test: use a path that really contains parent segments path.join removed the .. segments before the script started, so the test did not cover the action's GITHUB_ACTION_PATH/../.. invocation. --- .../tests/dependabot-pr-reminder/cli.test.mts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index 4a21c1a0..d405b48b 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -1,7 +1,7 @@ import { execFile } from 'node:child_process'; import { mkdtemp, rm, symlink } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; import { afterEach, describe, expect, it } from 'vitest'; @@ -44,13 +44,9 @@ describe('cli entry point', () => { }); it('runs when started through a path with .. segments', async () => { - const dotted = join( - SCRIPT, - '..', - '..', - 'dependabot-pr-reminder', - 'cli.mts', - ); + // Built as a string, since `path.join` would remove the `..` segments. + const dotted = `${dirname(SCRIPT)}/../dependabot-pr-reminder/cli.mts`; + expect(dotted).toContain('/../'); expect(await runWithoutSettings(dotted)).toContain('are required'); }); From 9d6c70641e7a202e832f9f5079d0690f52916f16 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 25 Nov 2026 12:58:40 +0100 Subject: [PATCH 32/61] docs: say the script needs Node 22.18 or newer --- .github/actions/remind-dependabot-prs/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 54f33aca..6c33dba1 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -44,7 +44,7 @@ outputs: runs: using: composite steps: - # The script is a .mts file, which requires Node 22+ to run directly. + # The script is a .mts file, which requires Node 22.18+ to run directly. - name: Set up Node uses: actions/setup-node@v6 with: From 16f8aa03e0beffdaecf22559ec42e92a5d247a0d Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 25 Nov 2026 15:18:53 +0100 Subject: [PATCH 33/61] feat: let the reminder report on another repository A repository input (default: the calling repository) makes it possible to run the action from a fork against the real repo, and the name is checked so it can't change the search query. --- .../actions/remind-dependabot-prs/action.yml | 8 +++++-- .../scripts/dependabot-pr-reminder/cli.mts | 3 ++- .../tests/dependabot-pr-reminder/cli.test.mts | 21 +++++++++++++++++-- .github/workflows/remind-dependabot-prs.yml | 6 ++++++ 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 6c33dba1..82085cbb 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -3,8 +3,12 @@ description: 'Builds a Slack payload listing open Dependabot PRs grouped by owni inputs: github-token: - description: 'Token used to read pull request data from the invoking repository.' + description: 'Token used to read pull request data from the repository.' required: true + repository: + description: 'Repository to report on, as owner/name. Empty uses the invoking repository.' + required: false + default: '' planning-token: description: 'Token with read access to MetaMask/MetaMask-planning (for topology.json).' required: true @@ -54,7 +58,7 @@ runs: id: reminder shell: bash env: - GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_REPOSITORY: ${{ inputs.repository || github.repository }} GH_TOKEN: ${{ inputs.github-token }} PLANNING_TOKEN: ${{ inputs.planning-token }} OWNER_TEAMS: ${{ inputs.owner-teams }} diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 0819e06a..75a8b97c 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -26,7 +26,8 @@ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } - if (repository.split('/').filter(Boolean).length !== 2) { + // The name goes into a search query, so only allow plain owner/name values. + if (!/^[\w.-]+\/[\w.-]+$/u.test(repository)) { throw new Error('GITHUB_REPOSITORY must be in owner/name form'); } const ref = environment.TOPOLOGY_REF?.trim() diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index d405b48b..57a935e7 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -26,12 +26,16 @@ describe('cli entry point', () => { * Runs the script with no settings, so it stops at once with a message. * * @param scriptPath - The path to run it through. + * @param settings - Environment settings to give it. * @returns What it printed on stderr. */ - async function runWithoutSettings(scriptPath: string): Promise<string> { + async function runWithoutSettings( + scriptPath: string, + settings: Record<string, string> = {}, + ): Promise<string> { try { await execFileAsync(process.execPath, [scriptPath], { - env: { PATH: process.env.PATH ?? '' }, + env: { PATH: process.env.PATH ?? '', ...settings }, }); } catch (error) { return (error as { stderr?: string }).stderr ?? ''; @@ -58,4 +62,17 @@ describe('cli entry point', () => { 'are required', ); }); + + it.each(['MetaMask/core is:issue', 'MetaMask', 'a/b/c', 'a/b c'])( + 'rejects the repository %j before searching', + async (repository) => { + const output = await runWithoutSettings(SCRIPT, { + GITHUB_REPOSITORY: repository, + FALLBACK_TEAM: 'core-platform', + PLANNING_TOKEN: 'token', + GITHUB_OUTPUT: join(tmpdir(), 'reminder-cli-output.txt'), + }); + expect(output).toContain('owner/name'); + }, + ); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index cb33f5e0..45d59529 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -21,6 +21,11 @@ name: Remind Dependabot PRs on: workflow_call: inputs: + repository: + required: false + type: string + default: '' + description: 'Repository to report on, as owner/name. Empty uses the calling repository' owner-teams: required: false type: string @@ -87,6 +92,7 @@ jobs: uses: MetaMask/github-tools/.github/actions/remind-dependabot-prs@v1 with: github-token: ${{ github.token }} + repository: ${{ inputs.repository }} planning-token: ${{ steps.planning-token.outputs.token }} owner-teams: ${{ inputs.owner-teams }} fallback-team: ${{ inputs.fallback-team }} From ce9a1a65eeacb8c8915823f7688337b29e2d572a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 13:42:15 +0100 Subject: [PATCH 34/61] Revert "feat: let the reminder report on another repository" This reverts commit 5c288d198fbac15d5b83730f10b4f1759c899616. --- .../actions/remind-dependabot-prs/action.yml | 8 ++----- .../scripts/dependabot-pr-reminder/cli.mts | 3 +-- .../tests/dependabot-pr-reminder/cli.test.mts | 21 ++----------------- .github/workflows/remind-dependabot-prs.yml | 6 ------ 4 files changed, 5 insertions(+), 33 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 82085cbb..6c33dba1 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -3,12 +3,8 @@ description: 'Builds a Slack payload listing open Dependabot PRs grouped by owni inputs: github-token: - description: 'Token used to read pull request data from the repository.' + description: 'Token used to read pull request data from the invoking repository.' required: true - repository: - description: 'Repository to report on, as owner/name. Empty uses the invoking repository.' - required: false - default: '' planning-token: description: 'Token with read access to MetaMask/MetaMask-planning (for topology.json).' required: true @@ -58,7 +54,7 @@ runs: id: reminder shell: bash env: - GITHUB_REPOSITORY: ${{ inputs.repository || github.repository }} + GITHUB_REPOSITORY: ${{ github.repository }} GH_TOKEN: ${{ inputs.github-token }} PLANNING_TOKEN: ${{ inputs.planning-token }} OWNER_TEAMS: ${{ inputs.owner-teams }} diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 75a8b97c..0819e06a 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -26,8 +26,7 @@ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } - // The name goes into a search query, so only allow plain owner/name values. - if (!/^[\w.-]+\/[\w.-]+$/u.test(repository)) { + if (repository.split('/').filter(Boolean).length !== 2) { throw new Error('GITHUB_REPOSITORY must be in owner/name form'); } const ref = environment.TOPOLOGY_REF?.trim() diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index 57a935e7..d405b48b 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -26,16 +26,12 @@ describe('cli entry point', () => { * Runs the script with no settings, so it stops at once with a message. * * @param scriptPath - The path to run it through. - * @param settings - Environment settings to give it. * @returns What it printed on stderr. */ - async function runWithoutSettings( - scriptPath: string, - settings: Record<string, string> = {}, - ): Promise<string> { + async function runWithoutSettings(scriptPath: string): Promise<string> { try { await execFileAsync(process.execPath, [scriptPath], { - env: { PATH: process.env.PATH ?? '', ...settings }, + env: { PATH: process.env.PATH ?? '' }, }); } catch (error) { return (error as { stderr?: string }).stderr ?? ''; @@ -62,17 +58,4 @@ describe('cli entry point', () => { 'are required', ); }); - - it.each(['MetaMask/core is:issue', 'MetaMask', 'a/b/c', 'a/b c'])( - 'rejects the repository %j before searching', - async (repository) => { - const output = await runWithoutSettings(SCRIPT, { - GITHUB_REPOSITORY: repository, - FALLBACK_TEAM: 'core-platform', - PLANNING_TOKEN: 'token', - GITHUB_OUTPUT: join(tmpdir(), 'reminder-cli-output.txt'), - }); - expect(output).toContain('owner/name'); - }, - ); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 45d59529..cb33f5e0 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -21,11 +21,6 @@ name: Remind Dependabot PRs on: workflow_call: inputs: - repository: - required: false - type: string - default: '' - description: 'Repository to report on, as owner/name. Empty uses the calling repository' owner-teams: required: false type: string @@ -92,7 +87,6 @@ jobs: uses: MetaMask/github-tools/.github/actions/remind-dependabot-prs@v1 with: github-token: ${{ github.token }} - repository: ${{ inputs.repository }} planning-token: ${{ steps.planning-token.outputs.token }} owner-teams: ${{ inputs.owner-teams }} fallback-team: ${{ inputs.fallback-team }} From f4a4cde59a1738cc54a862e90efdeaa03114c5ad Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 13:57:22 +0100 Subject: [PATCH 35/61] refactor: simplify the Dependabot reminder Drops what nothing needs (the note input, the block overflow handling and the client side author checks), merges duplicated tables, and trims comments. --- .../actions/remind-dependabot-prs/action.yml | 15 +- .../dependabot-pr-reminder/classify.mts | 50 +-- .../scripts/dependabot-pr-reminder/cli.mts | 49 +-- .../dependabot-title.mts | 66 +-- .../dependabot-pr-reminder/github-api.mts | 168 +++----- .../dependabot-pr-reminder/reminder-note.mts | 53 --- .../dependabot-pr-reminder/slack-payload.mts | 383 ++++++----------- .../scripts/dependabot-pr-reminder/teams.mts | 16 +- .../dependabot-pr-reminder/classify.test.mts | 99 ++--- .../dependabot-title.test.mts | 64 ++- .../tests/dependabot-pr-reminder/fixtures.mts | 12 - .../github-api.test.mts | 179 +++----- .../reminder-note.test.mts | 75 ---- .../slack-payload.test.mts | 395 ++++++------------ .github/workflows/remind-dependabot-prs.yml | 38 +- 15 files changed, 501 insertions(+), 1161 deletions(-) delete mode 100644 .github/scripts/dependabot-pr-reminder/reminder-note.mts delete mode 100644 .github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 6c33dba1..22385eaf 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -3,7 +3,7 @@ description: 'Builds a Slack payload listing open Dependabot PRs grouped by owni inputs: github-token: - description: 'Token used to read pull request data from the invoking repository.' + description: 'Token used to read the pull requests of this repository.' required: true planning-token: description: 'Token with read access to MetaMask/MetaMask-planning (for topology.json).' @@ -25,13 +25,9 @@ inputs: required: false default: '5' guide-url: - description: 'Link to a guide for handling these PRs, shown under the note. Empty for none.' + description: 'Link to a guide for handling these PRs, shown in the message. Empty for none.' required: false default: '' - reminder-note: - description: 'Note shown under the counts, as Slack mrkdwn. `default` uses the built in note, empty for none. `{repository}` is replaced by the repository name.' - required: false - default: 'default' outputs: has-prs: @@ -61,14 +57,7 @@ runs: FALLBACK_TEAM: ${{ inputs.fallback-team }} TOPOLOGY_REF: ${{ inputs.topology-ref }} SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} - REMINDER_NOTE: ${{ inputs.reminder-note }} GUIDE_URL: ${{ inputs.guide-url }} run: | set -euo pipefail node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" - - # Fail loudly if the script did not run, instead of quietly posting nothing. - if ! grep -q '^has-prs=' "$GITHUB_OUTPUT"; then - echo "::error::The Dependabot reminder script did not produce an output" - exit 1 - fi diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 386684f9..73c4b96a 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -1,51 +1,33 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; -/** A PR requested from more than this many teams goes to the fallback team. */ -export const DEFAULT_SHARED_TEAM_THRESHOLD = 5; - -/** - * Sorts pull requests into per-team groups and fallback buckets. - * - * PRs with remaining requested teams are grouped by team. When more than - * `sharedTeamThreshold` teams remain, no single team owns the PR, so it goes to - * the fallback team instead. PRs with no team left go to the fallback team too. - * - * @param pullRequests - The open Dependabot pull requests. - * @param options - Classification options. - * @param options.ownerTeams - If set, only these teams are kept as owners. - * @param options.fallbackTeam - The team that handles the fallback buckets. - * @param options.sharedTeamThreshold - The most teams a PR can have and still - * be listed under each of them. Defaults to 5. - * @returns The classified reminder. - */ +// Groups PRs by the teams still requested as reviewers. A PR with more than +// `sharedTeamThreshold` teams has no single owner, so it goes to the fallback +// team, like a PR with no team. export function classifyPullRequests( pullRequests: PullRequest[], - options: { - ownerTeams?: string[]; - fallbackTeam: string; - sharedTeamThreshold?: number; - }, + { + ownerTeams, + sharedTeamThreshold, + }: { ownerTeams?: string[] | undefined; sharedTeamThreshold: number }, ): Reminder { - const ownerTeams = options.ownerTeams?.map(normalizeTeamSlug); - const sharedTeamThreshold = - options.sharedTeamThreshold ?? DEFAULT_SHARED_TEAM_THRESHOLD; + const owners = ownerTeams?.map(normalizeTeamSlug); const reminder: Reminder = { byTeam: {}, fallback: { sharedByManyTeams: [], noTeam: [] }, }; for (const pullRequest of pullRequests) { - const teams = pullRequest.requestedTeams - .map(normalizeTeamSlug) - .filter((team) => !ownerTeams || ownerTeams.includes(team)); - - const uniqueTeams = new Set(teams); + const teams = new Set( + pullRequest.requestedTeams + .map(normalizeTeamSlug) + .filter((team) => !owners || owners.includes(team)), + ); - if (uniqueTeams.size > sharedTeamThreshold) { + if (teams.size > sharedTeamThreshold) { reminder.fallback.sharedByManyTeams.push(pullRequest); - } else if (uniqueTeams.size > 0) { - for (const team of uniqueTeams) { + } else if (teams.size > 0) { + for (const team of teams) { (reminder.byTeam[team] ??= []).push(pullRequest); } } else { diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 0819e06a..b9ffceca 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -7,15 +7,9 @@ import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; import { fetchDependabotPullRequests } from './github-api.mts'; -import { parseGuideUrl, resolveReminderNote } from './reminder-note.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; -/** - * Fetches open Dependabot pull requests and writes the Slack payload. - * - * @param environment - The process environment. - */ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { const repository = environment.GITHUB_REPOSITORY; const fallbackTeam = environment.FALLBACK_TEAM; @@ -26,76 +20,49 @@ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } - if (repository.split('/').filter(Boolean).length !== 2) { - throw new Error('GITHUB_REPOSITORY must be in owner/name form'); - } - const ref = environment.TOPOLOGY_REF?.trim() - ? environment.TOPOLOGY_REF.trim() - : 'main'; const pullRequests = await fetchDependabotPullRequests(repository, { environment, }); - // Skip the topology request entirely when there is nothing to report. if (pullRequests.length === 0) { console.log('No open Dependabot pull requests to report.'); await appendFile(outputPath, 'has-prs=false\n'); return; } - const ownerTeams = parseOwnerTeams(environment.OWNER_TEAMS); - const sharedTeamThreshold = parseSharedTeamThreshold( - environment.SHARED_TEAM_THRESHOLD, - ); const reminder = classifyPullRequests(pullRequests, { - ...(ownerTeams ? { ownerTeams } : {}), - ...(sharedTeamThreshold === undefined ? {} : { sharedTeamThreshold }), - fallbackTeam, + ownerTeams: parseOwnerTeams(environment.OWNER_TEAMS), + sharedTeamThreshold: + parseSharedTeamThreshold(environment.SHARED_TEAM_THRESHOLD) ?? 5, }); - // Tags are a nicety. If topology is unavailable, still post, with team names - // as plain text. + // Tags are optional, so the message still goes out without them. let topology: Topology = {}; try { topology = await fetchTopology({ - ref, + ref: environment.TOPOLOGY_REF?.trim() ? environment.TOPOLOGY_REF : 'main', gh: { environment, token: planningToken }, }); } catch (error) { console.log( - `::warning::Could not read topology.json, posting without Slack tags: ${ - error instanceof Error ? error.message : String(error) - }`, + `::warning::Could not read topology.json, posting without Slack tags: ${String(error)}`, ); } - const note = resolveReminderNote( - environment.REMINDER_NOTE, - repository, - parseGuideUrl(environment.GUIDE_URL), - ); const payload = buildSlackPayload(reminder, topology, { fallbackTeam, repository, - ...(note ? { note } : {}), + guideUrl: environment.GUIDE_URL?.trim(), }); - if (!payload) { - console.log('No open Dependabot pull requests to report.'); - await appendFile(outputPath, 'has-prs=false\n'); - return; - } - const payloadPath = join( environment.RUNNER_TEMP ?? '.', 'dependabot-reminder-payload.json', ); await writeFile(payloadPath, JSON.stringify(payload)); await appendFile(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); - console.log(`Wrote Slack payload with ${payload.blocks.length} sections.`); } -// Compare real paths, since a symlinked directory makes the two differ and the -// script would otherwise silently do nothing. +// Real paths, so starting it through a symlinked directory still runs it. if ( process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) diff --git a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts index e4c38b3d..e7dcbafe 100644 --- a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts @@ -1,61 +1,31 @@ import { escapeSlack } from '../shared/slack-blocks.mts'; -// An optional conventional commit prefix, such as `chore(deps):`. The scope is -// captured so `deps-dev` can be told apart from `deps`. +// `chore(deps-dev): bump foo from 1.0.0 to 2.0.0` and +// `chore(deps): bump the foo group across 1 directory with 7 updates`. The +// scope is captured to tell `deps-dev` from `deps`. const PREFIX = String.raw`(?:[a-z]+(?:\(([^)]*)\))?!?:\s*)?`; -const IN_DIRECTORY = String.raw`(?:\s+in\s+(\S+))?`; - -const PACKAGE_TITLE = new RegExp( - `^${PREFIX}[Bb]ump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)${IN_DIRECTORY}$`, - 'u', +const PACKAGE = new RegExp( + `^${PREFIX}bump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)(?:\\s+in\\s+\\S+)?$`, + 'iu', ); - -const GROUP_TITLE = new RegExp( - `^${PREFIX}[Bb]ump\\s+the\\s+(\\S+)\\s+group(?:\\s+(?:across\\s+\\d+\\s+director(?:y|ies)|in\\s+\\S+))?\\s+with\\s+(\\d+)\\s+updates?$`, - 'u', +const GROUP = new RegExp( + `^${PREFIX}bump\\s+the\\s+(\\S+)\\s+group(?:\\s+(?:across\\s+\\d+\\s+director(?:y|ies)|in\\s+\\S+))?\\s+with\\s+(\\d+)\\s+updates?$`, + 'iu', ); -/** - * Makes a value safe to show inside a Slack code span. - * - * @param value - The raw value. - * @returns The escaped value, with no backticks. - */ -function code(value: string): string { - return `\`${escapeSlack(value).replaceAll('`', "'")}\``; -} +const code = (value: string): string => + `\`${escapeSlack(value).replaceAll('`', "'")}\``; -/** - * Turns a Dependabot pull request title into a short description of the - * update, as Slack mrkdwn. For example `chore(deps): bump foo from 1.0.0 to - * 2.0.0` becomes `foo 1.0.0 → 2.0.0`, and a group update becomes - * `name group, 7 updates`. - * - * @param title - The pull request title. - * @returns The description, or undefined when the title is not a Dependabot - * title this knows how to read. - */ +// Shortens a Dependabot title to `foo 1.0.0 → 2.0.0`, or undefined if it isn't one. export function describeUpdate(title: string): string | undefined { - const trimmed = title.trim(); - - const packageMatch = PACKAGE_TITLE.exec(trimmed); - if (packageMatch) { - const [, scope, name, from, to, directory] = packageMatch; - if (name && from && to) { - return [ - `${code(name)} ${escapeSlack(from)} → ${escapeSlack(to)}`, - scope?.includes('dev') ? ' (dev)' : '', - directory ? ` · ${code(directory)}` : '', - ].join(''); - } + const [, scope, name, from, to] = PACKAGE.exec(title.trim()) ?? []; + if (name && from && to) { + return `${code(name)} ${escapeSlack(from)} → ${escapeSlack(to)}${scope?.includes('dev') ? ' (dev)' : ''}`; } - const groupMatch = GROUP_TITLE.exec(trimmed); - if (groupMatch) { - const [, , name, count] = groupMatch; - if (name && count) { - return `${code(name)} group, ${count} ${count === '1' ? 'update' : 'updates'}`; - } + const [, , group, count] = GROUP.exec(title.trim()) ?? []; + if (group && count) { + return `${code(group)} group, ${count} ${count === '1' ? 'update' : 'updates'}`; } return undefined; diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 4dfe0419..cf6b6b04 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -2,35 +2,28 @@ import { ghGraphqlPages } from '../shared/github-cli.mts'; import type { GhOptions } from '../shared/github-cli.mts'; import type { PullRequest } from './types.mts'; -export type GraphQlPullRequestNode = { - number: number; - title: string; - url: string; - isDraft: boolean; - author: { __typename: string; login: string } | null; - reviewRequests: { - nodes: { - requestedReviewer: { __typename: string; slug?: string } | null; - }[]; - }; - commits: { - nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; - }; -}; - -/** A page of search results. Nodes that are not pull requests come back empty. */ -export type SearchPage = { +type SearchPage = { data: { - search: { nodes: (GraphQlPullRequestNode | Record<string, never>)[] }; + search: { + nodes: { + number: number; + title: string; + url: string; + reviewRequests: { + nodes: { + requestedReviewer: { __typename: string; slug?: string } | null; + }[]; + }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; + }[]; + }; }; }; -/** - * One query returns every field the reminder needs, including the requested - * teams, so a run costs a single request per 100 pull requests. The search - * filter keeps drafts and non Dependabot authors out on the server side. - */ -export const PULL_REQUESTS_QUERY = ` +// One query returns everything needed, so a run costs one request per 100 PRs. +const QUERY = ` query($searchQuery: String!, $endCursor: String) { search(query: $searchQuery, type: ISSUE, first: 100, after: $endCursor) { pageInfo { hasNextPage endCursor } @@ -39,8 +32,6 @@ query($searchQuery: String!, $endCursor: String) { number title url - isDraft - author { __typename login } reviewRequests(first: 20) { nodes { requestedReviewer { __typename ... on Team { slug } } } } @@ -50,106 +41,41 @@ query($searchQuery: String!, $endCursor: String) { } }`; -/** - * Builds the search string for open, non draft Dependabot pull requests. - * - * @param repository - The repository in `owner/name` form. - * @returns The GitHub search query. - */ -export function buildSearchQuery(repository: string): string { - return `repo:${repository} is:pr is:open draft:false author:app/dependabot`; -} - -/** - * Maps a commit status rollup to a CI state. - * - * @param rollupState - The GraphQL rollup state, or null when there are no - * checks. - * @returns The CI state. - */ -function toCiState(rollupState: string | null): PullRequest['ciState'] { - if (rollupState === 'SUCCESS') { - return 'passing'; - } - if (rollupState === 'FAILURE' || rollupState === 'ERROR') { - return 'failing'; - } - if (rollupState === 'PENDING' || rollupState === 'EXPECTED') { - return 'pending'; - } - return 'unknown'; -} - -/** - * Maps a search node to a PullRequest. - * - * @param node - The search node. - * @returns The pull request, or undefined for non pull requests, drafts and - * non Dependabot PRs. The server side search already filters those, this is a - * safety net. - */ -export function toPullRequest( - node: GraphQlPullRequestNode | Record<string, never>, -): PullRequest | undefined { - if (!('number' in node)) { - return undefined; - } - // GraphQL returns `dependabot` for the Bot actor; REST returns - // `dependabot[bot]`. Accept both, but only for Bot actors. - if ( - node.isDraft || - node.author?.__typename !== 'Bot' || - (node.author.login !== 'dependabot' && - node.author.login !== 'dependabot[bot]') - ) { - return undefined; - } - - const rollupState = - node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null; - - return { - number: node.number, - title: node.title, - url: node.url, - requestedTeams: node.reviewRequests.nodes.flatMap( - ({ requestedReviewer }) => - requestedReviewer?.__typename === 'Team' && requestedReviewer.slug - ? [requestedReviewer.slug] - : [], - ), - ciState: toCiState(rollupState), - }; -} - -/** - * Maps search pages to pull requests. - * - * @param pages - The paginated search responses. - * @returns The Dependabot pull requests. - */ -export function toPullRequests(pages: SearchPage[]): PullRequest[] { - return pages - .flatMap((page) => page.data.search.nodes) - .map(toPullRequest) - .filter((pullRequest): pullRequest is PullRequest => Boolean(pullRequest)); -} +const CI_STATES: Record<string, PullRequest['ciState']> = { + SUCCESS: 'passing', + FAILURE: 'failing', + ERROR: 'failing', + PENDING: 'pending', + EXPECTED: 'pending', +}; -/** - * Fetches the open Dependabot pull requests of a repository. - * - * @param repository - The repository in `owner/name` form. - * @param gh - Options for the underlying `gh api` calls. - * @returns The pull requests. - */ export async function fetchDependabotPullRequests( repository: string, gh: GhOptions, ): Promise<PullRequest[]> { const pages = await ghGraphqlPages<SearchPage>( - PULL_REQUESTS_QUERY, - { searchQuery: buildSearchQuery(repository) }, + QUERY, + { + searchQuery: `repo:${repository} is:pr is:open draft:false author:app/dependabot`, + }, gh, ); - return toPullRequests(pages); + + return pages + .flatMap((page) => page.data.search.nodes) + .map((node) => ({ + number: node.number, + title: node.title, + url: node.url, + requestedTeams: node.reviewRequests.nodes.flatMap( + ({ requestedReviewer }) => + requestedReviewer?.__typename === 'Team' && requestedReviewer.slug + ? [requestedReviewer.slug] + : [], + ), + ciState: + CI_STATES[ + node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? '' + ] ?? 'unknown', + })); } diff --git a/.github/scripts/dependabot-pr-reminder/reminder-note.mts b/.github/scripts/dependabot-pr-reminder/reminder-note.mts deleted file mode 100644 index 128316d3..00000000 --- a/.github/scripts/dependabot-pr-reminder/reminder-note.mts +++ /dev/null @@ -1,53 +0,0 @@ -import { escapeSlack } from '../shared/slack-blocks.mts'; - -/** The value of `reminder-note` that selects the built in note. */ -export const DEFAULT_NOTE_KEYWORD = 'default'; - -const DEFAULT_NOTE = - ':wave: *Is your team tagged?* Check the changelogs, fix CI if it fails, and get approval from every tagged team before merging. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; - -const GUIDE_URL_PATTERN = /^https:\/\/[^\s<>|]+$/u; - -/** - * Checks and returns the guide URL from the `guide-url` setting. - * - * @param value - The setting. - * @returns The URL, or undefined when empty. - * @throws If the value is not an https URL that is safe to put in a Slack link. - */ -export function parseGuideUrl(value: string | undefined): string | undefined { - const trimmed = (value ?? '').trim(); - if (!trimmed) { - return undefined; - } - if (!GUIDE_URL_PATTERN.test(trimmed)) { - throw new Error('GUIDE_URL must be an https URL'); - } - return trimmed; -} - -/** - * Works out the note to show from the `reminder-note` setting. - * - * @param value - The setting. Unset or `default` gives the built in note, empty - * gives no note, and any other text is used as it is, with `{repository}` - * replaced by the repository name. - * @param repository - The repository the PRs are in. - * @param guideUrl - A link to a guide, added under the note when there is one. - * @returns The note, or undefined when there should be none. - */ -export function resolveReminderNote( - value: string | undefined, - repository: string, - guideUrl?: string, -): string | undefined { - const trimmed = value?.trim(); - const note = - trimmed === undefined || trimmed === DEFAULT_NOTE_KEYWORD - ? DEFAULT_NOTE - : trimmed.replaceAll('{repository}', escapeSlack(repository)); - if (!note) { - return undefined; - } - return guideUrl ? `${note}\n<${guideUrl}|Read the full guide>` : note; -} diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index e2a91a28..895aaa7e 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,5 +1,4 @@ import { - MAX_BLOCKS, MAX_SECTION_LENGTH, escapeSlack, section, @@ -11,305 +10,185 @@ import type { Topology } from '../shared/topology.mts'; import { describeUpdate } from './dependabot-title.mts'; import type { PullRequest, Reminder } from './types.mts'; -export type HeaderBlock = { - type: 'header'; - text: { type: 'plain_text'; text: string; emoji: true }; -}; -export type ContextBlock = { - type: 'context'; - elements: { type: 'mrkdwn'; text: string }[]; -}; -export type DividerBlock = { type: 'divider' }; - -/** Any block in the payload. */ export type ReminderBlock = | SlackBlock - | HeaderBlock - | ContextBlock - | DividerBlock; - -/** Shown to tell a PR's CI state at a glance. */ -export const CI_ICONS: Record<PullRequest['ciState'], string> = { - passing: ':white_check_mark:', - failing: ':x:', - pending: ':hourglass_flowing_sand:', - unknown: ':white_circle:', + | { + type: 'header'; + text: { type: 'plain_text'; text: string; emoji: true }; + } + | { type: 'context'; elements: { type: 'mrkdwn'; text: string }[] } + | { type: 'divider' }; + +type CiState = PullRequest['ciState']; + +const CI: Record<CiState, { icon: string; count: string; legend: string }> = { + passing: { + icon: ':white_check_mark:', + count: 'passing', + legend: 'CI passes', + }, + failing: { icon: ':x:', count: 'failing', legend: 'CI fails' }, + pending: { + icon: ':hourglass_flowing_sand:', + count: 'running', + legend: 'CI running', + }, + unknown: { icon: ':white_circle:', count: 'no checks', legend: 'no checks' }, }; -const HEADER_TEXT = ':dependabot: Open Dependabot pull requests'; +const NOTE = + ':wave: *Is your team tagged?* Check the changelogs, fix CI if it fails, and get approval from every tagged team before merging. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; -/** Long titles are cut before escaping so a cut can't split a link or entity. */ const MAX_TITLE_LENGTH = 200; -/** A block and the team mentions in it, so only shown teams get pinged. */ -type Entry = { block: ReminderBlock; handles: string[] }; +const divider: ReminderBlock = { type: 'divider' }; -/** One pull request ready to show, with the mentions in its text. */ -type Item = { text: string; handles: string[] }; +const context = (text: string): ReminderBlock => ({ + type: 'context', + elements: [{ type: 'mrkdwn', text }], +}); -const divider: DividerBlock = { type: 'divider' }; - -/** - * Describes a pull request, as the package and versions when its title is a - * Dependabot title we can read, and as the cut down title otherwise. - * - * @param pullRequest - The pull request. - * @returns The description, as Slack mrkdwn. - */ -function describePullRequest(pullRequest: PullRequest): string { - const { title } = pullRequest; - return ( - describeUpdate(title) ?? escapeSlack(truncateText(title, MAX_TITLE_LENGTH)) - ); -} +const describe = ({ title }: PullRequest): string => + describeUpdate(title) ?? escapeSlack(truncateText(title, MAX_TITLE_LENGTH)); -/** - * Packs items into section blocks that fit Slack's limit. The heading is - * repeated on every block, and items are separated by a blank line. - * - * @param heading - The heading shown on top of each block. - * @param headingHandles - The mentions in the heading. - * @param items - The items to list. - * @returns One or more blocks. - */ -function packItems( - heading: string, - headingHandles: string[], - items: Item[], -): Entry[] { - const budget = Math.max(MAX_SECTION_LENGTH - heading.length - 1, 1); - const entries: Entry[] = []; - let current: Item[] = []; +// A section holds at most 3000 characters, so a long group continues in a new +// section with the heading repeated. +function packItems(heading: string, items: string[]): ReminderBlock[] { + const budget = MAX_SECTION_LENGTH - heading.length - 1; + const chunks: string[][] = []; let length = 0; - - const flush = (): void => { - if (current.length > 0) { - entries.push({ - block: section( - `${heading}\n${current.map(({ text }) => text).join('\n\n')}`, - ), - handles: [ - ...headingHandles, - ...current.flatMap(({ handles }) => handles), - ], - }); - current = []; - length = 0; - } - }; - - for (const item of items) { - const text = truncateText(item.text, budget); - const added = text.length + (current.length > 0 ? 2 : 0); - if (current.length > 0 && length + added > budget) { - flush(); + for (const item of items.map((text) => truncateText(text, budget))) { + const chunk = chunks.at(-1); + if (chunk && length + item.length + 2 <= budget) { + chunk.push(item); + length += item.length + 2; + } else { + chunks.push([item]); + length = item.length; } - length += text.length + (current.length > 0 ? 2 : 0); - current.push({ text, handles: item.handles }); } - flush(); - return entries; + return chunks.map((chunk) => section(`${heading}\n${chunk.join('\n\n')}`)); } -/** - * Builds the Slack incoming webhook payload for a reminder. - * - * The message has a headline with counts, an optional note, then the pull - * requests in groups: the ones that need a fix, the ones still running, the - * ones shared by many teams, and the ones that pass CI. Each pull request is - * listed once, with all of its teams tagged under it. - * - * @param reminder - The classified reminder. - * @param topology - The team topology used to look up Slack user groups. - * @param options - Payload options. - * @param options.fallbackTeam - The team that coordinates shared pull requests - * and the ones with no team. - * @param options.repository - The repository, in `owner/name` form. - * @param options.note - Text shown under the counts, as Slack mrkdwn. Left out - * when empty. - * @returns The payload, or undefined when there is nothing to post. - */ export function buildSlackPayload( reminder: Reminder, topology: Topology, - options: { fallbackTeam: string; repository: string; note?: string }, -): - | { - text: string; - blocks: ReminderBlock[]; - } - | undefined { - // A handle like `@core-platform-team` in message text becomes a mention. A - // team without one is shown as a plain name. - const tag = (team: string): { text: string; handle?: string } => { + { + fallbackTeam, + repository, + guideUrl, + }: { + fallbackTeam: string; + repository: string; + guideUrl?: string | undefined; + }, +): { text: string; blocks: ReminderBlock[] } { + // A handle in the text becomes a Slack mention. Teams without one stay plain. + const mentions = new Set<string>(); + const tag = (team: string): string => { const handle = getSlackHandle(topology, team); - return handle - ? { text: handle, handle } - : { text: escapeSlack(normalizeTeamSlug(team)) }; + if (!handle) { + return escapeSlack(normalizeTeamSlug(team)); + } + mentions.add(escapeSlack(handle)); + return escapeSlack(handle); }; - // List each PR once, with every team it was requested from. + // Each PR is listed once, with every team it was requested from. const owned = new Map< number, { pullRequest: PullRequest; teams: string[] } >(); + const own = (pullRequest: PullRequest, team: string): void => { + const entry = owned.get(pullRequest.number); + if (entry) { + entry.teams.push(team); + } else { + owned.set(pullRequest.number, { pullRequest, teams: [team] }); + } + }; for (const [team, pullRequests] of Object.entries(reminder.byTeam)) { for (const pullRequest of pullRequests) { - const entry = owned.get(pullRequest.number); - if (entry) { - entry.teams.push(team); - } else { - owned.set(pullRequest.number, { pullRequest, teams: [team] }); - } + own(pullRequest, team); } } for (const pullRequest of reminder.fallback.noTeam) { - owned.set(pullRequest.number, { - pullRequest, - teams: [options.fallbackTeam], - }); - } - const shared = reminder.fallback.sharedByManyTeams; - - const everyPullRequest = [ - ...[...owned.values()].map(({ pullRequest }) => pullRequest), - ...shared, - ]; - if (everyPullRequest.length === 0) { - return undefined; + own(pullRequest, fallbackTeam); } - const ownedItem = ( - { pullRequest, teams }: { pullRequest: PullRequest; teams: string[] }, - withIcon: boolean, - ): Item => { - const tags = teams.map(tag); - const icon = withIcon ? `${CI_ICONS[pullRequest.ciState]} ` : ''; - return { - text: `${icon}<${pullRequest.url}|#${pullRequest.number}> ${describePullRequest(pullRequest)}\n${tags.map(({ text }) => text).join(' ')}`, - handles: tags.flatMap(({ handle }) => (handle ? [handle] : [])), - }; - }; - - const ownedBy = ( - states: PullRequest['ciState'][], - ): { pullRequest: PullRequest; teams: string[] }[] => - [...owned.values()].filter(({ pullRequest }) => - states.includes(pullRequest.ciState), - ); + const link = ({ url, number }: PullRequest): string => `<${url}|#${number}>`; + const ownedItems = (states: CiState[], withIcon: boolean): string[] => + [...owned.values()] + .filter(({ pullRequest }) => states.includes(pullRequest.ciState)) + .map( + ({ pullRequest, teams }) => + `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describe(pullRequest)}\n${teams.map(tag).join(' ')}`, + ); - const fallbackTag = tag(options.fallbackTeam); - const groups: Entry[][] = [ - packItems( - `*${CI_ICONS.failing} Needs a fix*`, - [], - ownedBy(['failing']).map((entry) => ownedItem(entry, false)), - ), + const shared = reminder.fallback.sharedByManyTeams; + const groups = [ packItems( - `*${CI_ICONS.pending} In progress*`, - [], - ownedBy(['pending', 'unknown']).map((entry) => ownedItem(entry, true)), + `*${CI.failing.icon} Needs a fix*`, + ownedItems(['failing'], false), ), packItems( - `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${fallbackTag.text}`, - fallbackTag.handle ? [fallbackTag.handle] : [], - shared.map((pullRequest) => ({ - text: `${CI_ICONS[pullRequest.ciState]} <${pullRequest.url}|#${pullRequest.number}> ${describePullRequest(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, - handles: [], - })), + `*${CI.pending.icon} In progress*`, + ownedItems(['pending', 'unknown'], true), ), + shared.length > 0 + ? packItems( + `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tag(fallbackTeam)}`, + shared.map( + (pullRequest) => + `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describe(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, + ), + ) + : [], packItems( - `*${CI_ICONS.passing} CI passing*`, - [], - ownedBy(['passing']).map((entry) => ownedItem(entry, false)), + `*${CI.passing.icon} CI passing*`, + ownedItems(['passing'], false), ), ].filter((group) => group.length > 0); - const middle: Entry[] = groups.flatMap((group, index) => [ - ...(index > 0 ? [{ block: divider, handles: [] }] : []), - ...group, - ]); - - // The counts line, only showing the states that have pull requests. - const counts = ( - [ - ['passing', 'passing'], - ['failing', 'failing'], - ['pending', 'running'], - ['unknown', 'no checks'], - ] as const - ).flatMap(([state, label]) => { - const total = everyPullRequest.filter( - ({ ciState }) => ciState === state, - ).length; - return total > 0 ? [`${CI_ICONS[state]} ${total} ${label}`] : []; + const all = [...owned.values()] + .map(({ pullRequest }) => pullRequest) + .concat(shared); + const counts = (Object.keys(CI) as CiState[]).flatMap((state) => { + const total = all.filter(({ ciState }) => ciState === state).length; + return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; }); - const repository = escapeSlack(options.repository); - - const top: ReminderBlock[] = [ - { - type: 'header', - text: { type: 'plain_text', text: HEADER_TEXT, emoji: true }, - }, - { - type: 'context', - elements: [ - { - type: 'mrkdwn', - text: [ - `<https://github.com/${options.repository}|${repository}>`, - `*${everyPullRequest.length}* open`, - ...counts, - ].join(' · '), - }, - ], - }, - ...(options.note - ? [section(truncateText(options.note, MAX_SECTION_LENGTH))] - : []), - divider, - ]; - const bottom: ReminderBlock[] = [ - divider, - { - type: 'context', - elements: [ - { - type: 'mrkdwn', - text: `${CI_ICONS.passing} CI passes · ${CI_ICONS.failing} CI fails · ${CI_ICONS.pending} CI running · ${CI_ICONS.unknown} no checks`, - }, - ], - }, - ]; - - // Keep the top and bottom, and cut the middle if the message is too long. - const room = MAX_BLOCKS - top.length - bottom.length; - let shown = middle; - let overflow: ReminderBlock[] = []; - if (middle.length > room) { - shown = middle.slice(0, room - 1); - const omitted = middle.slice(room - 1); - const omittedCount = omitted.reduce( - (total, { block }) => - total + - ('text' in block - ? (block.text.text.match(/\|#\d+>/gu) ?? []).length - : 0), - 0, - ); - overflow = [section(`…and ${omittedCount} more pull request(s) not shown`)]; - } - const mentions = new Set(shown.flatMap(({ handles }) => handles)); return { text: [`Open Dependabot pull requests in ${repository}`, ...mentions].join( ' ', ), blocks: [ - ...top, - ...shown.map(({ block }) => block), - ...overflow, - ...bottom, + { + type: 'header', + text: { + type: 'plain_text', + text: ':dependabot: Open Dependabot pull requests', + emoji: true, + }, + }, + context( + [ + `<https://github.com/${repository}|${escapeSlack(repository)}>`, + `*${all.length}* open`, + ...counts, + ].join(' · '), + ), + section(guideUrl ? `${NOTE}\n<${guideUrl}|Read the full guide>` : NOTE), + divider, + ...groups.flatMap((group, index) => + index > 0 ? [divider, ...group] : group, + ), + divider, + context( + Object.values(CI) + .map(({ icon, legend }) => `${icon} ${legend}`) + .join(' · '), + ), ], }; } diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts index 2e8edacb..3f0a63f9 100644 --- a/.github/scripts/dependabot-pr-reminder/teams.mts +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -1,10 +1,4 @@ -/** - * Parses the comma-separated OWNER_TEAMS value. - * - * @param value - The raw value. - * @returns The team list, or undefined when no teams are configured (so that - * no filtering is applied). - */ +// Comma separated team slugs, or undefined to keep every team. export function parseOwnerTeams( value: string | undefined, ): string[] | undefined { @@ -15,13 +9,7 @@ export function parseOwnerTeams( return teams.length > 0 ? teams : undefined; } -/** - * Parses the SHARED_TEAM_THRESHOLD value. - * - * @param value - The raw value. - * @returns The threshold, or undefined to use the default. - * @throws If the value is set but is not a positive whole number. - */ +// A positive whole number, or undefined to use the default. export function parseSharedTeamThreshold( value: string | undefined, ): number | undefined { diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 006525ae..b75b8dc2 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -3,81 +3,64 @@ import { describe, expect, it } from 'vitest'; import { classifyPullRequests } from '../../dependabot-pr-reminder/classify.mts'; import { pr } from './fixtures.mts'; +const options = { sharedTeamThreshold: 3 }; + describe('classifyPullRequests', () => { - it('groups a PR under each remaining requested team', () => { + it('lists a PR under each requested team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.byTeam.a).toStrictEqual([pullRequest]); - expect(result.byTeam.b).toStrictEqual([pullRequest]); + + const { byTeam } = classifyPullRequests([pullRequest], options); + + expect(byTeam).toStrictEqual({ a: [pullRequest], b: [pullRequest] }); }); - it('lists PRs with no teams under the fallback, approved or not', () => { + it('puts a PR with no team in the fallback', () => { const pullRequest = pr(); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.fallback.noTeam).toStrictEqual([pullRequest]); - }); - it('filters other teams out when ownerTeams is set', () => { - const pullRequest = pr({ requestedTeams: ['ui', 'extension-platform'] }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['extension-platform'], - fallbackTeam: 'f', - }); - expect(Object.keys(result.byTeam)).toStrictEqual(['extension-platform']); - expect(result.byTeam['extension-platform']).toStrictEqual([pullRequest]); - }); + const { fallback } = classifyPullRequests([pullRequest], options); - it('lists a PR under the fallback when ownerTeams leaves nothing', () => { - const pullRequest = pr({ requestedTeams: ['ui'] }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['extension-platform'], - fallbackTeam: 'f', - }); - expect(result.byTeam).toStrictEqual({}); - expect(result.fallback.noTeam).toStrictEqual([pullRequest]); + expect(fallback.noTeam).toStrictEqual([pullRequest]); }); - it('normalizes team names before comparing and grouping', () => { - const pullRequest = pr({ requestedTeams: ['MetaMask/UI', 'Core'] }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['@metamask/core'], - fallbackTeam: 'f', - }); - expect(Object.keys(result.byTeam)).toStrictEqual(['core']); - }); + it('keeps a PR with exactly the threshold under its teams', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); - it('keeps a PR under its teams when it has exactly the threshold', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd', 'e'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b', 'c', 'd', 'e']); - expect(result.fallback.sharedByManyTeams).toStrictEqual([]); + const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + + expect(Object.keys(byTeam)).toStrictEqual(['a', 'b', 'c']); + expect(fallback.sharedByManyTeams).toStrictEqual([]); }); - it('moves a PR with more teams than the threshold to the fallback', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'] }); - const result = classifyPullRequests([pullRequest], { fallbackTeam: 'f' }); - expect(result.byTeam).toStrictEqual({}); - expect(result.fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + it('puts a PR with more teams than the threshold in the fallback', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); + + const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + + expect(byTeam).toStrictEqual({}); + expect(fallback.sharedByManyTeams).toStrictEqual([pullRequest]); }); - it('uses a custom threshold', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b'] }); - const result = classifyPullRequests([pullRequest], { - fallbackTeam: 'f', - sharedTeamThreshold: 1, + it('only counts the owner teams, ignoring case and repeats', () => { + const pullRequest = pr({ requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'] }); + + const { byTeam, fallback } = classifyPullRequests([pullRequest], { + ...options, + ownerTeams: ['@MetaMask/a', 'b'], }); - expect(result.fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + + expect(Object.keys(byTeam)).toStrictEqual(['a', 'b']); + expect(fallback.sharedByManyTeams).toStrictEqual([]); }); - it('counts only the owner teams and ignores repeats', () => { - const pullRequest = pr({ - requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], - }); - const result = classifyPullRequests([pullRequest], { - ownerTeams: ['a', 'b'], - fallbackTeam: 'f', + it('puts a PR in the fallback when no owner team is left', () => { + const pullRequest = pr({ requestedTeams: ['ui'] }); + + const { byTeam, fallback } = classifyPullRequests([pullRequest], { + ...options, + ownerTeams: ['extension-platform'], }); - expect(Object.keys(result.byTeam)).toStrictEqual(['a', 'b']); - expect(result.fallback.sharedByManyTeams).toStrictEqual([]); + + expect(byTeam).toStrictEqual({}); + expect(fallback.noTeam).toStrictEqual([pullRequest]); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts index 261d9d67..60108965 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts @@ -3,46 +3,30 @@ import { describe, expect, it } from 'vitest'; import { describeUpdate } from '../../dependabot-pr-reminder/dependabot-title.mts'; describe('describeUpdate', () => { - it('reads a package bump', () => { - expect( - describeUpdate('chore(deps): bump @noble/curves from 1.9.7 to 2.4.0'), - ).toBe('`@noble/curves` 1.9.7 → 2.4.0'); + it.each([ + [ + 'chore(deps): bump @noble/curves from 1.9.7 to 2.4.0', + '`@noble/curves` 1.9.7 → 2.4.0', + ], + [ + 'chore(deps-dev): bump jsdom from 27.4.0 to 31.0.1', + '`jsdom` 27.4.0 → 31.0.1 (dev)', + ], + ['Bump foo from 1.0.0 to 1.1.0 in /packages/a', '`foo` 1.0.0 → 1.1.0'], + [ + 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', + '`external-non-major` group, 7 updates', + ], + ['Bump the tools group in /app with 1 update', '`tools` group, 1 update'], + ['bump a&b from 1<2 to 3>4', '`a&b` 1<2 → 3>4'], + ])('reads %s', (title, expected) => { + expect(describeUpdate(title)).toBe(expected); }); - it('marks a dev dependency', () => { - expect( - describeUpdate('chore(deps-dev): bump jsdom from 27.4.0 to 31.0.1'), - ).toBe('`jsdom` 27.4.0 → 31.0.1 (dev)'); - }); - - it('reads a title without a prefix and with a directory', () => { - expect(describeUpdate('Bump foo from 1.0.0 to 1.1.0 in /packages/a')).toBe( - '`foo` 1.0.0 → 1.1.0 · `/packages/a`', - ); - }); - - it('reads a group update across directories', () => { - expect( - describeUpdate( - 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', - ), - ).toBe('`external-non-major` group, 7 updates'); - }); - - it('reads a group update in a directory and a single update', () => { - expect(describeUpdate('Bump the tools group in /app with 1 update')).toBe( - '`tools` group, 1 update', - ); - }); - - it('returns undefined for titles it does not know', () => { - expect(describeUpdate('Bump a and b')).toBeUndefined(); - expect(describeUpdate('Something else entirely')).toBeUndefined(); - }); - - it('escapes Slack characters and backticks', () => { - expect(describeUpdate('bump a&b from 1<2 to 3>4')).toBe( - '`a&b` 1<2 → 3>4', - ); - }); + it.each(['Bump a and b', 'Something else entirely'])( + 'does not read %s', + (title) => { + expect(describeUpdate(title)).toBeUndefined(); + }, + ); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index 1342135c..c0255096 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -1,12 +1,6 @@ import type { ReminderBlock } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; -/** - * Builds a pull request for tests. - * - * @param overrides - Fields to override on the default pull request. - * @returns The pull request. - */ export function pr(overrides: Partial<PullRequest> = {}): PullRequest { return { number: 1, @@ -18,12 +12,6 @@ export function pr(overrides: Partial<PullRequest> = {}): PullRequest { }; } -/** - * Reads the text of a section block. - * - * @param block - The block, if any. - * @returns The text, or an empty string when there is no block. - */ export function sectionText(block: ReminderBlock | undefined): string { return block && 'text' in block ? block.text.text : ''; } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index fe51a1a6..a8161256 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -1,75 +1,74 @@ import { describe, expect, it, vi } from 'vitest'; +import type { Mock } from 'vitest'; -import { - buildSearchQuery, - fetchDependabotPullRequests, - toPullRequest, - toPullRequests, -} from '../../dependabot-pr-reminder/github-api.mts'; -import type { - GraphQlPullRequestNode, - SearchPage, -} from '../../dependabot-pr-reminder/github-api.mts'; +import { fetchDependabotPullRequests } from '../../dependabot-pr-reminder/github-api.mts'; +import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; -/** - * Builds a search node for tests. - * - * @param overrides - Fields to override. - * @returns The node. - */ -function node( - overrides: Partial<GraphQlPullRequestNode> = {}, -): GraphQlPullRequestNode { +type Node = { + number: number; + title: string; + url: string; + reviewRequests: { + nodes: { + requestedReviewer: { __typename: string; slug?: string } | null; + }[]; + }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; +}; + +function node(overrides: Partial<Node> = {}): Node { return { number: 7, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', - isDraft: false, - author: { __typename: 'Bot', login: 'dependabot' }, reviewRequests: { nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, ...overrides, }; } -describe('toPullRequest', () => { - it('returns undefined for search nodes that are not pull requests', () => { - expect(toPullRequest({})).toBeUndefined(); - }); +type Run = (args: string[]) => Promise<string>; - it('returns undefined for drafts', () => { - expect(toPullRequest(node({ isDraft: true }))).toBeUndefined(); - }); +function runReturning(...pages: Node[][]): Mock<Run> { + return vi + .fn<Run>() + .mockResolvedValue( + JSON.stringify(pages.map((nodes) => ({ data: { search: { nodes } } }))), + ); +} - it('returns undefined for non-Dependabot authors', () => { - expect( - toPullRequest(node({ author: { __typename: 'Bot', login: 'other' } })), - ).toBeUndefined(); +async function fetchFrom(...pages: Node[][]): Promise<PullRequest[]> { + return await fetchDependabotPullRequests('MetaMask/core', { + environment: {}, + run: runReturning(...pages), }); +} - it('rejects a User named dependabot', () => { - expect( - toPullRequest( - node({ author: { __typename: 'User', login: 'dependabot' } }), - ), - ).toBeUndefined(); - }); +describe('fetchDependabotPullRequests', () => { + it('needs one request for one page and searches for open Dependabot PRs', async () => { + const run = runReturning([node()]); + await fetchDependabotPullRequests('MetaMask/core', { + environment: {}, + run, + }); - it('accepts a Bot named dependabot[bot]', () => { - expect( - toPullRequest( - node({ author: { __typename: 'Bot', login: 'dependabot[bot]' } }), - )?.number, - ).toBe(7); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]?.[0]).toContain( + 'searchQuery=repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', + ); }); - it('returns undefined when the author is missing', () => { - expect(toPullRequest(node({ author: null }))).toBeUndefined(); - }); + it('maps the PRs of every page', async () => { + const pullRequests = await fetchFrom( + [node({ number: 1 })], + [node({ number: 2 })], + ); - it('maps a Dependabot PR', () => { - expect(toPullRequest(node())).toStrictEqual({ - number: 7, + expect(pullRequests.map(({ number }) => number)).toStrictEqual([1, 2]); + expect(pullRequests[0]).toStrictEqual({ + number: 1, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], @@ -77,8 +76,8 @@ describe('toPullRequest', () => { }); }); - it('keeps requested teams and ignores requested users', () => { - const pullRequest = toPullRequest( + it('keeps requested teams and ignores requested users', async () => { + const pullRequests = await fetchFrom([ node({ reviewRequests: { nodes: [ @@ -88,69 +87,25 @@ describe('toPullRequest', () => { ], }, }), - ); - expect(pullRequest?.requestedTeams).toStrictEqual(['wallet']); - }); - - it('maps the status rollup to a CI state', () => { - const rollup = ( - statusCheckRollup: { state: string } | null, - ): string | undefined => - toPullRequest( - node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), - )?.ciState; - expect(rollup({ state: 'SUCCESS' })).toBe('passing'); - expect(rollup({ state: 'FAILURE' })).toBe('failing'); - expect(rollup({ state: 'ERROR' })).toBe('failing'); - expect(rollup({ state: 'PENDING' })).toBe('pending'); - expect(rollup({ state: 'EXPECTED' })).toBe('pending'); - expect(rollup(null)).toBe('unknown'); - }); -}); - -describe('toPullRequests', () => { - it('flattens pages and drops nodes that do not qualify', () => { - const pages: SearchPage[] = [ - { data: { search: { nodes: [node({ number: 1 }), {}] } } }, - { data: { search: { nodes: [node({ number: 2, isDraft: true })] } } }, - { data: { search: { nodes: [node({ number: 3 })] } } }, - ]; - expect(toPullRequests(pages).map(({ number }) => number)).toStrictEqual([ - 1, 3, ]); - }); -}); -describe('buildSearchQuery', () => { - it('filters to open, non draft Dependabot pull requests', () => { - expect(buildSearchQuery('MetaMask/core')).toBe( - 'repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', - ); + expect(pullRequests[0]?.requestedTeams).toStrictEqual(['wallet']); }); -}); -describe('fetchDependabotPullRequests', () => { - it('needs a single gh call for a repository with one page of PRs', async () => { - const page: SearchPage = { - data: { search: { nodes: [node({ number: 11 })] } }, - }; - const run = vi - .fn<() => Promise<string>>() - .mockResolvedValue(JSON.stringify([page])); - const pullRequests = await fetchDependabotPullRequests('MetaMask/core', { - environment: {}, - run, - }); - expect(pullRequests.map(({ number }) => number)).toStrictEqual([11]); - expect(run).toHaveBeenCalledTimes(1); - expect(run.mock.calls[0]).toStrictEqual([ - expect.arrayContaining([ - 'graphql', - '--paginate', - '--slurp', - `searchQuery=${buildSearchQuery('MetaMask/core')}`, - ]), - {}, + it.each([ + [{ state: 'SUCCESS' }, 'passing'], + [{ state: 'FAILURE' }, 'failing'], + [{ state: 'ERROR' }, 'failing'], + [{ state: 'PENDING' }, 'pending'], + [{ state: 'EXPECTED' }, 'pending'], + [null, 'unknown'], + ])('maps the status %j to %s', async (statusCheckRollup, ciState) => { + const pullRequests = await fetchFrom([ + node({ + commits: { nodes: [{ commit: { statusCheckRollup } }] }, + }), ]); + + expect(pullRequests[0]?.ciState).toBe(ciState); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts b/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts deleted file mode 100644 index 04998ba1..00000000 --- a/.github/scripts/tests/dependabot-pr-reminder/reminder-note.test.mts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - parseGuideUrl, - resolveReminderNote, -} from '../../dependabot-pr-reminder/reminder-note.mts'; -import { MAX_SECTION_LENGTH } from '../../shared/slack-blocks.mts'; - -describe('resolveReminderNote', () => { - it.each([undefined, 'default', ' default '])( - 'gives the built in note for %j', - (value) => { - const note = resolveReminderNote(value, 'MetaMask/core'); - expect(note).toContain('*Is your team tagged?*'); - expect(note).toContain('Check the changelogs'); - expect(note).toContain('Dependabot stops updating it'); - }, - ); - - it('fits in one Slack section', () => { - const note = resolveReminderNote('default', 'MetaMask/core'); - expect(note?.length).toBeLessThan(MAX_SECTION_LENGTH); - }); - - it('gives no note for an empty value, even with a guide', () => { - expect(resolveReminderNote('', 'MetaMask/core')).toBeUndefined(); - expect(resolveReminderNote(' ', 'MetaMask/core')).toBeUndefined(); - expect( - resolveReminderNote('', 'MetaMask/core', 'https://example.com/guide'), - ).toBeUndefined(); - }); - - it('uses custom text and fills in the repository', () => { - expect(resolveReminderNote('Own {repository}.', 'MetaMask/core')).toBe( - 'Own MetaMask/core.', - ); - }); - - it('escapes the repository name', () => { - expect(resolveReminderNote('Own {repository}.', 'a<b>/c')).toBe( - 'Own a<b>/c.', - ); - }); - - it('adds a link to the guide under the note', () => { - expect( - resolveReminderNote('Own it.', 'MetaMask/core', 'https://example.com/g'), - ).toBe('Own it.\n<https://example.com/g|Read the full guide>'); - expect( - resolveReminderNote('default', 'MetaMask/core', 'https://example.com/g'), - ).toMatch(/\n<https:\/\/example\.com\/g\|Read the full guide>$/u); - }); -}); - -describe('parseGuideUrl', () => { - it('returns undefined when unset or blank', () => { - expect(parseGuideUrl(undefined)).toBeUndefined(); - expect(parseGuideUrl(' ')).toBeUndefined(); - }); - - it('returns an https URL', () => { - expect(parseGuideUrl(' https://example.com/guide.md ')).toBe( - 'https://example.com/guide.md', - ); - }); - - it.each([ - 'http://example.com', - 'example.com', - 'https://a.com/x>y', - 'https://a b', - ])('rejects %s', (value) => { - expect(() => parseGuideUrl(value)).toThrow('GUIDE_URL'); - }); -}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index cd1edfdd..bef025f4 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -1,4 +1,4 @@ -import { assert, describe, expect, it } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { @@ -18,22 +18,11 @@ const topology = { }, }; -/** - * Builds a reminder for tests. - * - * @param parts - The parts of the reminder. - * @param parts.byTeam - Pull requests by team. - * @param parts.shared - Pull requests shared by many teams. - * @param parts.noTeam - Pull requests with no team. - * @returns The reminder. - */ -function reminder( - parts: { - byTeam?: Record<string, PullRequest[]>; - shared?: PullRequest[]; - noTeam?: PullRequest[]; - } = {}, -): Reminder { +function reminder(parts: { + byTeam?: Record<string, PullRequest[]>; + shared?: PullRequest[]; + noTeam?: PullRequest[]; +}): Reminder { return { byTeam: parts.byTeam ?? {}, fallback: { @@ -43,233 +32,180 @@ function reminder( }; } -describe('buildSlackPayload', () => { - it('returns undefined when there are no pull requests', () => { - expect(buildSlackPayload(reminder(), {}, options)).toBeUndefined(); +function build( + parts: Parameters<typeof reminder>[0], + extra = {}, +): ReturnType<typeof buildSlackPayload> { + return buildSlackPayload(reminder(parts), topology, { + ...options, + ...extra, }); +} - it('starts with a header, the counts and a divider, and ends with a legend', () => { - const payload = buildSlackPayload( - reminder({ byTeam: { a: [pr({ ciState: 'passing' })] } }), - topology, - options, - ); - assert.ok(payload); - const types = payload.blocks.map(({ type }) => type); - expect(types.slice(0, 3)).toStrictEqual(['header', 'context', 'divider']); - expect(types.slice(-2)).toStrictEqual(['divider', 'context']); - expect(JSON.stringify(payload.blocks[0])).toContain( - ':dependabot: Open Dependabot pull requests', - ); - expect(JSON.stringify(payload.blocks.at(-1))).toContain( - ':white_check_mark: CI passes · :x: CI fails', - ); - }); +// The blocks after the header, counts, note and first divider. +function groups(parts: Parameters<typeof reminder>[0]): string[] { + return build(parts) + .blocks.slice(4, -2) + .map((block) => sectionText(block) || '---'); +} - it('shows the repository link, how many are open, and only the states present', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'failing' }), - ], - }, - }), - topology, - options, - ); - assert.ok(payload); - expect(JSON.stringify(payload.blocks[1])).toContain( - '<https://github.com/MetaMask/example|MetaMask/example> · *3* open · :white_check_mark: 1 passing · :x: 2 failing', - ); - expect(JSON.stringify(payload.blocks[1])).not.toContain('running'); - }); +describe('buildSlackPayload', () => { + it('starts with the header, counts, note and a divider, and ends with the legend', () => { + const { blocks } = build({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'failing' }), + ], + }, + }); - it('puts the note between the counts and the first divider', () => { - const payload = buildSlackPayload( - reminder({ byTeam: { a: [pr()] } }), - topology, - { ...options, note: 'Own it.' }, - ); - assert.ok(payload); - expect(payload.blocks.map(({ type }) => type).slice(0, 4)).toStrictEqual([ + expect(blocks.map(({ type }) => type)).toStrictEqual([ 'header', 'context', 'section', 'divider', + 'section', + 'divider', + 'section', + 'divider', + 'context', ]); - expect(sectionText(payload.blocks[2])).toBe('Own it.'); + expect(JSON.stringify(blocks[0])).toContain( + ':dependabot: Open Dependabot pull requests', + ); + expect(JSON.stringify(blocks[1])).toContain( + '<https://github.com/MetaMask/example|MetaMask/example> · *3* open · :white_check_mark: 1 passing · :x: 2 failing', + ); + expect(sectionText(blocks[2])).toContain('*Is your team tagged?*'); + expect(JSON.stringify(blocks.at(-1))).toContain( + ':white_check_mark: CI passes · :x: CI fails · :hourglass_flowing_sand: CI running · :white_circle: no checks', + ); }); - it('leaves the note out when there is none', () => { - const payload = buildSlackPayload( - reminder({ byTeam: { a: [pr()] } }), - topology, - options, + it('links the guide under the note when there is one', () => { + const { blocks } = build( + { byTeam: { a: [pr()] } }, + { guideUrl: 'https://example.com/guide' }, ); - assert.ok(payload); - expect(payload.blocks.map(({ type }) => type)).not.toContain('Own it.'); - expect(payload.blocks[2]?.type).toBe('divider'); - }); - it('groups by CI state in order, with dividers between the groups', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'pending' }), - ], - }, - shared: [pr({ number: 4, ciState: 'failing', requestedTeams: ['x'] })], - }), - topology, - options, + expect(sectionText(blocks[2])).toMatch( + /\n<https:\/\/example\.com\/guide\|Read the full guide>$/u, ); - assert.ok(payload); - const headings = payload.blocks - .filter(({ type }) => type === 'section') - .map((block) => sectionText(block).split('\n')[0]); + }); + + it('groups PRs by CI state, with the shared ones before the passing ones', () => { + const headings = groups({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'pending' }), + ], + }, + shared: [pr({ number: 4, requestedTeams: ['x'] })], + }).map((text) => text.split('\n')[0]); + expect(headings).toStrictEqual([ '*:x: Needs a fix*', + '---', '*:hourglass_flowing_sand: In progress*', + '---', '*:busts_in_silhouette: Shared by many teams*', + '---', '*:white_check_mark: CI passing*', ]); }); - it('shows the package and versions and tags the teams under each PR', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { - a: [pr({ number: 7, ciState: 'failing' })], - b: [pr({ number: 7, ciState: 'failing' })], - plain: [pr({ number: 7, ciState: 'failing' })], - }, - }), - topology, - options, - ); - assert.ok(payload); - const text = sectionText(payload.blocks[3]); + it('shows the package, versions and teams of each PR', () => { + const [text] = groups({ + byTeam: { + a: [pr({ number: 7, ciState: 'failing' })], + b: [pr({ number: 7, ciState: 'failing' })], + plain: [pr({ number: 7, ciState: 'failing' })], + }, + }); + expect(text).toBe( '*:x: Needs a fix*\n<https://github.com/MetaMask/example/pull/1|#7> `foo` 1.0.0 → 1.0.1\n@a-team @b-team plain', ); }); it('lists each PR once, even when many teams share it', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { - a: [pr({ number: 1 }), pr({ number: 2 })], - b: [pr({ number: 2 })], - }, - }), - topology, - options, - ); - assert.ok(payload); - const all = JSON.stringify(payload.blocks); + const { blocks } = build({ + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 2 })], + }, + }); + + const all = JSON.stringify(blocks); expect(all.match(/\|#1>/gu)).toHaveLength(1); expect(all.match(/\|#2>/gu)).toHaveLength(1); }); it('shows a PR with no team under the fallback team', () => { - const payload = buildSlackPayload( - reminder({ noTeam: [pr({ number: 5, ciState: 'passing' })] }), - topology, - options, - ); - assert.ok(payload); - expect(sectionText(payload.blocks[3])).toBe( + const [text] = groups({ + noTeam: [pr({ number: 5, ciState: 'passing' })], + }); + + expect(text).toBe( '*:white_check_mark: CI passing*\n<https://github.com/MetaMask/example/pull/1|#5> `foo` 1.0.0 → 1.0.1\n@platform-team', ); }); - it('shows shared PRs with an icon and team count, coordinated by the fallback team', () => { - const payload = buildSlackPayload( - reminder({ - shared: [ - pr({ - number: 9, - ciState: 'failing', - requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'], - }), - ], - }), - topology, - options, - ); - assert.ok(payload); - const text = sectionText(payload.blocks[3]); - expect(text.split('\n')[0]).toBe( + it('shows shared PRs with their icon and team count, coordinated by the fallback team', () => { + const [text] = groups({ + shared: [ + pr({ + number: 9, + ciState: 'failing', + requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'], + }), + ], + }); + + expect(text?.split('\n').slice(0, 2)).toStrictEqual([ '*:busts_in_silhouette: Shared by many teams*', - ); - expect(text.split('\n')[1]).toBe('Coordinated by @platform-team'); + 'Coordinated by @platform-team', + ]); expect(text).toMatch(/:x: <[^>]*\|#9> `foo` 1\.0\.0 → 1\.0\.1 · 6 teams$/u); }); - it('shows an icon per PR in the in progress group', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'pending' }), - pr({ number: 2, ciState: 'unknown' }), - ], - }, - }), - topology, - options, - ); - assert.ok(payload); - const text = sectionText(payload.blocks[3]); + it('shows an icon on each PR in the in progress group', () => { + const [text] = groups({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'pending' }), + pr({ number: 2, ciState: 'unknown' }), + ], + }, + }); + expect(text).toMatch(/:hourglass_flowing_sand: <[^>]*\|#1>/u); expect(text).toMatch(/:white_circle: <[^>]*\|#2>/u); }); - it('puts the handles of tagged teams in the top level text', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { a: [pr()], b: [pr()], plain: [pr()] }, - }), - topology, - options, + it('mentions the teams that have a handle in the text', () => { + const { text } = build({ byTeam: { a: [pr()], b: [pr()], plain: [pr()] } }); + + expect(text).toBe( + 'Open Dependabot pull requests in MetaMask/example @a-team @b-team', ); - assert.ok(payload); - expect(payload.text).toContain('@a-team @b-team'); - expect(payload.text).not.toContain('plain'); }); - it('escapes the title of a PR it cannot read and cuts it short', () => { - const payload = buildSlackPayload( - reminder({ - byTeam: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, - }), - topology, - options, - ); - assert.ok(payload); - const text = sectionText(payload.blocks[3]); + it('escapes and shortens the title of a PR it cannot read', () => { + const [text] = groups({ + byTeam: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, + }); + expect(text).toContain('Odd <title> & '); expect(text).toContain('…'); - expect(text.length).toBeLessThan(500); + expect(text?.length).toBeLessThan(500); }); - it('does not turn @ text into mentions with link_names', () => { - const payload = buildSlackPayload( - reminder({ byTeam: { a: [pr({ title: 'Bump @here/x' })] } }), - topology, - options, - ); - assert.ok(payload); - expect(payload).not.toHaveProperty('link_names'); - }); - - it('splits a long group into blocks under the Slack limit, repeating the heading', () => { + it('continues a long group in a new section with the heading repeated', () => { const pullRequests = Array.from({ length: 60 }, (_, index) => pr({ number: index + 1, @@ -277,75 +213,14 @@ describe('buildSlackPayload', () => { ciState: 'failing', }), ); - const payload = buildSlackPayload( - reminder({ byTeam: { a: pullRequests } }), - topology, - options, - ); - assert.ok(payload); - const sections = payload.blocks.filter(({ type }) => type === 'section'); - expect(sections.length).toBeGreaterThan(1); - for (const block of sections) { - expect(sectionText(block).length).toBeLessThanOrEqual(3000); - expect(sectionText(block).startsWith('*:x: Needs a fix*\n')).toBe(true); - } - const all = JSON.stringify(payload.blocks); - for (const { number } of pullRequests) { - expect(all).toContain(`|#${number}>`); - } - }); -}); -describe('buildSlackPayload block limit', () => { - /** - * Builds many teams that each have their own PR, in a handle each. - * - * @returns The reminder and the topology. - */ - function manyTeams(): { - reminder: Reminder; - topology: Record< - string, - { githubHandle: string; slackHandle: { team: string } } - >; - } { - const byTeam: Reminder['byTeam'] = {}; - const manyTopology: Record< - string, - { githubHandle: string; slackHandle: { team: string } } - > = {}; - for (let index = 0; index < 800; index++) { - byTeam[`team-${index}`] = [ - pr({ - number: index + 1, - title: `chore(deps): bump ${'p'.repeat(150)}${index} from 1.0.0 to 1.0.1`, - ciState: 'failing', - }), - ]; - manyTopology[`t${index}`] = { - githubHandle: `MetaMask/team-${index}`, - slackHandle: { team: `@g${index}` }, - }; - } - return { reminder: reminder({ byTeam }), topology: manyTopology }; - } + const sections = groups({ byTeam: { a: pullRequests } }); - it('stays under 50 blocks, keeps the legend, and says how many were left out', () => { - const many = manyTeams(); - const payload = buildSlackPayload(many.reminder, many.topology, options); - assert.ok(payload); - expect(payload.blocks.length).toBeLessThanOrEqual(50); - expect(payload.blocks.at(-1)?.type).toBe('context'); - expect(JSON.stringify(payload.blocks)).toMatch( - /…and \d+ more pull request\(s\) not shown/u, - ); - }); - - it('only pings teams whose PRs are shown', () => { - const many = manyTeams(); - const payload = buildSlackPayload(many.reminder, many.topology, options); - assert.ok(payload); - expect(payload.text).toContain('@g0'); - expect(payload.text).not.toContain('@g799'); + expect(sections.length).toBeGreaterThan(1); + for (const text of sections) { + expect(text.length).toBeLessThanOrEqual(3000); + expect(text.startsWith('*:x: Needs a fix*\n')).toBe(true); + } + expect(sections.join()).toContain('|#60>'); }); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index cb33f5e0..12a999ba 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -1,22 +1,15 @@ name: Remind Dependabot PRs -# Posts a Slack message listing open Dependabot PRs grouped by owning team. +# Posts a Slack message of open Dependabot PRs, grouped by owning team. # -# Caller requirements: -# - Name the calling workflow `remind-dependabot-prs.yml`. -# - Grant the job `contents`, `pull-requests`, `checks` and `statuses` read -# and `id-token: write`. A reusable workflow's permissions are capped by -# the caller's. -# - Have the environment named by `environment` (default `default-branch`). -# Protection rules or required reviewers on it will block scheduled runs. -# - Define the `TOKEN_EXCHANGE_URL` variable, with a token exchange policy -# allowing `contents: read` on MetaMask/MetaMask-planning. -# - Pass the `slack-webhook-url` secret. +# The caller must be named `remind-dependabot-prs.yml` and grant `contents`, +# `pull-requests`, `checks` and `statuses` read plus `id-token: write`. It also +# needs the `default-branch` environment, a `TOKEN_EXCHANGE_URL` variable with a +# policy allowing `contents: read` on MetaMask/MetaMask-planning, and the +# `slack-webhook-url` secret. # -# Note: the `@v1` references below only resolve after a github-tools release. -# Pointing a caller at a branch ref is not enough for a pre-release smoke test: -# this workflow also references `get-token@v1` and `remind-dependabot-prs@v1` -# internally, so temporarily edit those inner `uses:` refs to the branch ref. +# The `@v1` refs below only resolve after a release. To try a branch first, +# point them at it. on: workflow_call: @@ -45,17 +38,7 @@ on: required: false type: string default: '' - description: 'Link to a guide for handling these PRs, shown under the note. Empty for none' - reminder-note: - required: false - type: string - default: 'default' - description: 'Note shown under the counts, as Slack mrkdwn. `default` uses the built in note, empty for none. `{repository}` is replaced by the repository name' - environment: - required: false - type: string - default: 'default-branch' - description: 'Environment the job runs in, used for the token exchange' + description: 'Link to a guide for handling these PRs, shown in the message. Empty for none' secrets: slack-webhook-url: required: true @@ -65,7 +48,7 @@ jobs: remind: name: Remind Dependabot PRs runs-on: ubuntu-latest - environment: ${{ inputs.environment }} + environment: default-branch permissions: contents: read pull-requests: read @@ -92,7 +75,6 @@ jobs: fallback-team: ${{ inputs.fallback-team }} topology-ref: ${{ inputs.topology-ref }} shared-team-threshold: ${{ inputs.shared-team-threshold }} - reminder-note: ${{ inputs.reminder-note }} guide-url: ${{ inputs.guide-url }} - name: Send Slack notification From 7e80bfc3f94e3b7c04deae09777e3303b271510a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 14:02:10 +0100 Subject: [PATCH 36/61] fix: shorten Dependabot titles that name a directory and a group --- .github/scripts/dependabot-pr-reminder/dependabot-title.mts | 2 +- .../tests/dependabot-pr-reminder/dependabot-title.test.mts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts index e7dcbafe..027c15dd 100644 --- a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts @@ -5,7 +5,7 @@ import { escapeSlack } from '../shared/slack-blocks.mts'; // scope is captured to tell `deps-dev` from `deps`. const PREFIX = String.raw`(?:[a-z]+(?:\(([^)]*)\))?!?:\s*)?`; const PACKAGE = new RegExp( - `^${PREFIX}bump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)(?:\\s+in\\s+\\S+)?$`, + `^${PREFIX}bump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)(?:\\s+in\\s.*)?$`, 'iu', ); const GROUP = new RegExp( diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts index 60108965..11735e48 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts @@ -13,6 +13,10 @@ describe('describeUpdate', () => { '`jsdom` 27.4.0 → 31.0.1 (dev)', ], ['Bump foo from 1.0.0 to 1.1.0 in /packages/a', '`foo` 1.0.0 → 1.1.0'], + [ + 'chore(deps): bump tar from 7.5.24 to 8.0.5 in /packages/foundryup in the npm_and_yarn group across 1 directory', + '`tar` 7.5.24 → 8.0.5', + ], [ 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', '`external-non-major` group, 7 updates', From bf5fab13b6d82ff6d4f0e5a7410c9c3ffa937359 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 14:28:24 +0100 Subject: [PATCH 37/61] feat: list the passing PRs first --- .github/scripts/dependabot-pr-reminder/slack-payload.mts | 8 ++++---- .../tests/dependabot-pr-reminder/slack-payload.test.mts | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 895aaa7e..1d69b154 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -127,6 +127,10 @@ export function buildSlackPayload( const shared = reminder.fallback.sharedByManyTeams; const groups = [ + packItems( + `*${CI.passing.icon} CI passing*`, + ownedItems(['passing'], false), + ), packItems( `*${CI.failing.icon} Needs a fix*`, ownedItems(['failing'], false), @@ -144,10 +148,6 @@ export function buildSlackPayload( ), ) : [], - packItems( - `*${CI.passing.icon} CI passing*`, - ownedItems(['passing'], false), - ), ].filter((group) => group.length > 0); const all = [...owned.values()] diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index bef025f4..a2c8f341 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -95,7 +95,7 @@ describe('buildSlackPayload', () => { ); }); - it('groups PRs by CI state, with the shared ones before the passing ones', () => { + it('groups PRs by CI state, with the shared ones last', () => { const headings = groups({ byTeam: { a: [ @@ -108,13 +108,13 @@ describe('buildSlackPayload', () => { }).map((text) => text.split('\n')[0]); expect(headings).toStrictEqual([ + '*:white_check_mark: CI passing*', + '---', '*:x: Needs a fix*', '---', '*:hourglass_flowing_sand: In progress*', '---', '*:busts_in_silhouette: Shared by many teams*', - '---', - '*:white_check_mark: CI passing*', ]); }); From 507794af3b67e6946a0896dd083a4e5494c4188a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 15:28:38 +0100 Subject: [PATCH 38/61] refactor: cut titles by their escaped length --- .github/scripts/dependabot-pr-reminder/slack-payload.mts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 1d69b154..c7c02064 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -1,8 +1,8 @@ import { MAX_SECTION_LENGTH, + escapeAndTruncate, escapeSlack, section, - truncateText, } from '../shared/slack-blocks.mts'; import type { SlackBlock } from '../shared/slack-blocks.mts'; import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; @@ -49,7 +49,7 @@ const context = (text: string): ReminderBlock => ({ }); const describe = ({ title }: PullRequest): string => - describeUpdate(title) ?? escapeSlack(truncateText(title, MAX_TITLE_LENGTH)); + describeUpdate(title) ?? escapeAndTruncate(title, MAX_TITLE_LENGTH); // A section holds at most 3000 characters, so a long group continues in a new // section with the heading repeated. @@ -57,7 +57,7 @@ function packItems(heading: string, items: string[]): ReminderBlock[] { const budget = MAX_SECTION_LENGTH - heading.length - 1; const chunks: string[][] = []; let length = 0; - for (const item of items.map((text) => truncateText(text, budget))) { + for (const item of items) { const chunk = chunks.at(-1); if (chunk && length + item.length + 2 <= budget) { chunk.push(item); From b2768ae0d6bef5b182e4b58c5c4c8ac96f4fb3e0 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 15:41:27 +0100 Subject: [PATCH 39/61] test: structure the reminder tests as arrange, act, assert --- .../tests/dependabot-pr-reminder/cli.test.mts | 16 ++++++--- .../dependabot-title.test.mts | 8 +++-- .../dependabot-pr-reminder/teams.test.mts | 35 +++++++++++-------- 3 files changed, 38 insertions(+), 21 deletions(-) diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index d405b48b..fe8f3d74 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -40,22 +40,28 @@ describe('cli entry point', () => { } it('runs when started by its plain path', async () => { - expect(await runWithoutSettings(SCRIPT)).toContain('are required'); + const output = await runWithoutSettings(SCRIPT); + + expect(output).toContain('are required'); }); it('runs when started through a path with .. segments', async () => { // Built as a string, since `path.join` would remove the `..` segments. const dotted = `${dirname(SCRIPT)}/../dependabot-pr-reminder/cli.mts`; + + const output = await runWithoutSettings(dotted); + expect(dotted).toContain('/../'); - expect(await runWithoutSettings(dotted)).toContain('are required'); + expect(output).toContain('are required'); }); it('runs when started through a symlinked directory', async () => { directory = await mkdtemp(join(tmpdir(), 'reminder-cli-')); const link = join(directory, 'scripts'); await symlink(resolve(SCRIPT, '..'), link); - expect(await runWithoutSettings(join(link, 'cli.mts'))).toContain( - 'are required', - ); + + const output = await runWithoutSettings(join(link, 'cli.mts')); + + expect(output).toContain('are required'); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts index 11735e48..a1a90bb1 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts @@ -24,13 +24,17 @@ describe('describeUpdate', () => { ['Bump the tools group in /app with 1 update', '`tools` group, 1 update'], ['bump a&b from 1<2 to 3>4', '`a&b` 1<2 → 3>4'], ])('reads %s', (title, expected) => { - expect(describeUpdate(title)).toBe(expected); + const description = describeUpdate(title); + + expect(description).toBe(expected); }); it.each(['Bump a and b', 'Something else entirely'])( 'does not read %s', (title) => { - expect(describeUpdate(title)).toBeUndefined(); + const description = describeUpdate(title); + + expect(description).toBeUndefined(); }, ); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts index f84f3847..fc92bc81 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -6,31 +6,38 @@ import { } from '../../dependabot-pr-reminder/teams.mts'; describe('parseOwnerTeams', () => { - it('returns undefined for undefined, empty, and whitespace input', () => { - expect(parseOwnerTeams(undefined)).toBeUndefined(); - expect(parseOwnerTeams('')).toBeUndefined(); - expect(parseOwnerTeams(' \n ')).toBeUndefined(); - expect(parseOwnerTeams(' , ,')).toBeUndefined(); - }); + it.each([undefined, '', ' \n ', ' , ,'])( + 'returns undefined for %j', + (value) => { + const teams = parseOwnerTeams(value); + + expect(teams).toBeUndefined(); + }, + ); it('splits, trims, and drops empty entries', () => { - expect(parseOwnerTeams(' a, b ,,c ')).toStrictEqual(['a', 'b', 'c']); + const teams = parseOwnerTeams(' a, b ,,c '); + + expect(teams).toStrictEqual(['a', 'b', 'c']); }); }); describe('parseSharedTeamThreshold', () => { - it('returns undefined when unset or blank', () => { - expect(parseSharedTeamThreshold(undefined)).toBeUndefined(); - expect(parseSharedTeamThreshold(' ')).toBeUndefined(); + it.each([undefined, ' '])('returns undefined for %j', (value) => { + const threshold = parseSharedTeamThreshold(value); + + expect(threshold).toBeUndefined(); }); it('parses a positive whole number', () => { - expect(parseSharedTeamThreshold(' 4 ')).toBe(4); + const threshold = parseSharedTeamThreshold(' 4 '); + + expect(threshold).toBe(4); }); it.each(['0', '-1', '2.5', 'many'])('rejects %s', (value) => { - expect(() => parseSharedTeamThreshold(value)).toThrow( - 'SHARED_TEAM_THRESHOLD', - ); + const parse = (): number | undefined => parseSharedTeamThreshold(value); + + expect(parse).toThrow('SHARED_TEAM_THRESHOLD'); }); }); From 4a8bd15beb133fc5e2686b181c0f587bb5c0054b Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 15:50:26 +0100 Subject: [PATCH 40/61] test: one describe per file and drop assertions that only restated constants --- .../dependabot-pr-reminder/classify.test.mts | 82 ++--- .../tests/dependabot-pr-reminder/cli.test.mts | 82 ++--- .../dependabot-title.test.mts | 66 ++-- .../github-api.test.mts | 108 ++++--- .../slack-payload.test.mts | 306 +++++++++--------- .../dependabot-pr-reminder/teams.test.mts | 56 ++-- 6 files changed, 359 insertions(+), 341 deletions(-) diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index b75b8dc2..27d8ec99 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -5,62 +5,66 @@ import { pr } from './fixtures.mts'; const options = { sharedTeamThreshold: 3 }; -describe('classifyPullRequests', () => { - it('lists a PR under each requested team', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b'] }); +describe('classify', () => { + describe('classifyPullRequests', () => { + it('lists a PR under each requested team', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b'] }); - const { byTeam } = classifyPullRequests([pullRequest], options); + const { byTeam } = classifyPullRequests([pullRequest], options); - expect(byTeam).toStrictEqual({ a: [pullRequest], b: [pullRequest] }); - }); + expect(byTeam).toStrictEqual({ a: [pullRequest], b: [pullRequest] }); + }); - it('puts a PR with no team in the fallback', () => { - const pullRequest = pr(); + it('puts a PR with no team in the fallback', () => { + const pullRequest = pr(); - const { fallback } = classifyPullRequests([pullRequest], options); + const { fallback } = classifyPullRequests([pullRequest], options); - expect(fallback.noTeam).toStrictEqual([pullRequest]); - }); + expect(fallback.noTeam).toStrictEqual([pullRequest]); + }); - it('keeps a PR with exactly the threshold under its teams', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); + it('keeps a PR with exactly the threshold under its teams', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + const { byTeam, fallback } = classifyPullRequests([pullRequest], options); - expect(Object.keys(byTeam)).toStrictEqual(['a', 'b', 'c']); - expect(fallback.sharedByManyTeams).toStrictEqual([]); - }); + expect(Object.keys(byTeam)).toStrictEqual(['a', 'b', 'c']); + expect(fallback.sharedByManyTeams).toStrictEqual([]); + }); - it('puts a PR with more teams than the threshold in the fallback', () => { - const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); + it('puts a PR with more teams than the threshold in the fallback', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + const { byTeam, fallback } = classifyPullRequests([pullRequest], options); - expect(byTeam).toStrictEqual({}); - expect(fallback.sharedByManyTeams).toStrictEqual([pullRequest]); - }); + expect(byTeam).toStrictEqual({}); + expect(fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + }); + + it('only counts the owner teams, ignoring case and repeats', () => { + const pullRequest = pr({ + requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], + }); - it('only counts the owner teams, ignoring case and repeats', () => { - const pullRequest = pr({ requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'] }); + const { byTeam, fallback } = classifyPullRequests([pullRequest], { + ...options, + ownerTeams: ['@MetaMask/a', 'b'], + }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], { - ...options, - ownerTeams: ['@MetaMask/a', 'b'], + expect(Object.keys(byTeam)).toStrictEqual(['a', 'b']); + expect(fallback.sharedByManyTeams).toStrictEqual([]); }); - expect(Object.keys(byTeam)).toStrictEqual(['a', 'b']); - expect(fallback.sharedByManyTeams).toStrictEqual([]); - }); + it('puts a PR in the fallback when no owner team is left', () => { + const pullRequest = pr({ requestedTeams: ['ui'] }); - it('puts a PR in the fallback when no owner team is left', () => { - const pullRequest = pr({ requestedTeams: ['ui'] }); + const { byTeam, fallback } = classifyPullRequests([pullRequest], { + ...options, + ownerTeams: ['extension-platform'], + }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], { - ...options, - ownerTeams: ['extension-platform'], + expect(byTeam).toStrictEqual({}); + expect(fallback.noTeam).toStrictEqual([pullRequest]); }); - - expect(byTeam).toStrictEqual({}); - expect(fallback.noTeam).toStrictEqual([pullRequest]); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index fe8f3d74..eb1fc27b 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -12,56 +12,58 @@ const SCRIPT = fileURLToPath( new URL('../../dependabot-pr-reminder/cli.mts', import.meta.url), ); -describe('cli entry point', () => { - let directory: string | undefined; +describe('cli', () => { + describe('entry point', () => { + let directory: string | undefined; - afterEach(async () => { - if (directory) { - await rm(directory, { recursive: true, force: true }); - directory = undefined; - } - }); + afterEach(async () => { + if (directory) { + await rm(directory, { recursive: true, force: true }); + directory = undefined; + } + }); - /** - * Runs the script with no settings, so it stops at once with a message. - * - * @param scriptPath - The path to run it through. - * @returns What it printed on stderr. - */ - async function runWithoutSettings(scriptPath: string): Promise<string> { - try { - await execFileAsync(process.execPath, [scriptPath], { - env: { PATH: process.env.PATH ?? '' }, - }); - } catch (error) { - return (error as { stderr?: string }).stderr ?? ''; + /** + * Runs the script with no settings, so it stops at once with a message. + * + * @param scriptPath - The path to run it through. + * @returns What it printed on stderr. + */ + async function runWithoutSettings(scriptPath: string): Promise<string> { + try { + await execFileAsync(process.execPath, [scriptPath], { + env: { PATH: process.env.PATH ?? '' }, + }); + } catch (error) { + return (error as { stderr?: string }).stderr ?? ''; + } + return ''; } - return ''; - } - it('runs when started by its plain path', async () => { - const output = await runWithoutSettings(SCRIPT); + it('runs when started by its plain path', async () => { + const output = await runWithoutSettings(SCRIPT); - expect(output).toContain('are required'); - }); + expect(output).toContain('are required'); + }); - it('runs when started through a path with .. segments', async () => { - // Built as a string, since `path.join` would remove the `..` segments. - const dotted = `${dirname(SCRIPT)}/../dependabot-pr-reminder/cli.mts`; + it('runs when started through a path with .. segments', async () => { + // Built as a string, since `path.join` would remove the `..` segments. + const dotted = `${dirname(SCRIPT)}/../dependabot-pr-reminder/cli.mts`; - const output = await runWithoutSettings(dotted); + const output = await runWithoutSettings(dotted); - expect(dotted).toContain('/../'); - expect(output).toContain('are required'); - }); + expect(dotted).toContain('/../'); + expect(output).toContain('are required'); + }); - it('runs when started through a symlinked directory', async () => { - directory = await mkdtemp(join(tmpdir(), 'reminder-cli-')); - const link = join(directory, 'scripts'); - await symlink(resolve(SCRIPT, '..'), link); + it('runs when started through a symlinked directory', async () => { + directory = await mkdtemp(join(tmpdir(), 'reminder-cli-')); + const link = join(directory, 'scripts'); + await symlink(resolve(SCRIPT, '..'), link); - const output = await runWithoutSettings(join(link, 'cli.mts')); + const output = await runWithoutSettings(join(link, 'cli.mts')); - expect(output).toContain('are required'); + expect(output).toContain('are required'); + }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts index a1a90bb1..8edf3f15 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts @@ -2,39 +2,41 @@ import { describe, expect, it } from 'vitest'; import { describeUpdate } from '../../dependabot-pr-reminder/dependabot-title.mts'; -describe('describeUpdate', () => { - it.each([ - [ - 'chore(deps): bump @noble/curves from 1.9.7 to 2.4.0', - '`@noble/curves` 1.9.7 → 2.4.0', - ], - [ - 'chore(deps-dev): bump jsdom from 27.4.0 to 31.0.1', - '`jsdom` 27.4.0 → 31.0.1 (dev)', - ], - ['Bump foo from 1.0.0 to 1.1.0 in /packages/a', '`foo` 1.0.0 → 1.1.0'], - [ - 'chore(deps): bump tar from 7.5.24 to 8.0.5 in /packages/foundryup in the npm_and_yarn group across 1 directory', - '`tar` 7.5.24 → 8.0.5', - ], - [ - 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', - '`external-non-major` group, 7 updates', - ], - ['Bump the tools group in /app with 1 update', '`tools` group, 1 update'], - ['bump a&b from 1<2 to 3>4', '`a&b` 1<2 → 3>4'], - ])('reads %s', (title, expected) => { - const description = describeUpdate(title); +describe('dependabot-title', () => { + describe('describeUpdate', () => { + it.each([ + [ + 'chore(deps): bump @noble/curves from 1.9.7 to 2.4.0', + '`@noble/curves` 1.9.7 → 2.4.0', + ], + [ + 'chore(deps-dev): bump jsdom from 27.4.0 to 31.0.1', + '`jsdom` 27.4.0 → 31.0.1 (dev)', + ], + ['Bump foo from 1.0.0 to 1.1.0 in /packages/a', '`foo` 1.0.0 → 1.1.0'], + [ + 'chore(deps): bump tar from 7.5.24 to 8.0.5 in /packages/foundryup in the npm_and_yarn group across 1 directory', + '`tar` 7.5.24 → 8.0.5', + ], + [ + 'chore(deps): bump the external-non-major group across 1 directory with 7 updates', + '`external-non-major` group, 7 updates', + ], + ['Bump the tools group in /app with 1 update', '`tools` group, 1 update'], + ['bump a&b from 1<2 to 3>4', '`a&b` 1<2 → 3>4'], + ])('reads %s', (title, expected) => { + const description = describeUpdate(title); - expect(description).toBe(expected); - }); + expect(description).toBe(expected); + }); - it.each(['Bump a and b', 'Something else entirely'])( - 'does not read %s', - (title) => { - const description = describeUpdate(title); + it.each(['Bump a and b', 'Something else entirely'])( + 'does not read %s', + (title) => { + const description = describeUpdate(title); - expect(description).toBeUndefined(); - }, - ); + expect(description).toBeUndefined(); + }, + ); + }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index a8161256..45e61b95 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -46,66 +46,68 @@ async function fetchFrom(...pages: Node[][]): Promise<PullRequest[]> { }); } -describe('fetchDependabotPullRequests', () => { - it('needs one request for one page and searches for open Dependabot PRs', async () => { - const run = runReturning([node()]); - await fetchDependabotPullRequests('MetaMask/core', { - environment: {}, - run, - }); +describe('github-api', () => { + describe('fetchDependabotPullRequests', () => { + it('needs one request for one page and searches for open Dependabot PRs', async () => { + const run = runReturning([node()]); + await fetchDependabotPullRequests('MetaMask/core', { + environment: {}, + run, + }); - expect(run).toHaveBeenCalledTimes(1); - expect(run.mock.calls[0]?.[0]).toContain( - 'searchQuery=repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', - ); - }); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]?.[0]).toContain( + 'searchQuery=repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', + ); + }); - it('maps the PRs of every page', async () => { - const pullRequests = await fetchFrom( - [node({ number: 1 })], - [node({ number: 2 })], - ); + it('maps the PRs of every page', async () => { + const pullRequests = await fetchFrom( + [node({ number: 1 })], + [node({ number: 2 })], + ); - expect(pullRequests.map(({ number }) => number)).toStrictEqual([1, 2]); - expect(pullRequests[0]).toStrictEqual({ - number: 1, - title: 'Bump foo', - url: 'https://github.com/MetaMask/example/pull/7', - requestedTeams: [], - ciState: 'unknown', + expect(pullRequests.map(({ number }) => number)).toStrictEqual([1, 2]); + expect(pullRequests[0]).toStrictEqual({ + number: 1, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + requestedTeams: [], + ciState: 'unknown', + }); }); - }); - it('keeps requested teams and ignores requested users', async () => { - const pullRequests = await fetchFrom([ - node({ - reviewRequests: { - nodes: [ - { requestedReviewer: { __typename: 'Team', slug: 'wallet' } }, - { requestedReviewer: { __typename: 'User' } }, - { requestedReviewer: null }, - ], - }, - }), - ]); + it('keeps requested teams and ignores requested users', async () => { + const pullRequests = await fetchFrom([ + node({ + reviewRequests: { + nodes: [ + { requestedReviewer: { __typename: 'Team', slug: 'wallet' } }, + { requestedReviewer: { __typename: 'User' } }, + { requestedReviewer: null }, + ], + }, + }), + ]); - expect(pullRequests[0]?.requestedTeams).toStrictEqual(['wallet']); - }); + expect(pullRequests[0]?.requestedTeams).toStrictEqual(['wallet']); + }); - it.each([ - [{ state: 'SUCCESS' }, 'passing'], - [{ state: 'FAILURE' }, 'failing'], - [{ state: 'ERROR' }, 'failing'], - [{ state: 'PENDING' }, 'pending'], - [{ state: 'EXPECTED' }, 'pending'], - [null, 'unknown'], - ])('maps the status %j to %s', async (statusCheckRollup, ciState) => { - const pullRequests = await fetchFrom([ - node({ - commits: { nodes: [{ commit: { statusCheckRollup } }] }, - }), - ]); + it.each([ + [{ state: 'SUCCESS' }, 'passing'], + [{ state: 'FAILURE' }, 'failing'], + [{ state: 'ERROR' }, 'failing'], + [{ state: 'PENDING' }, 'pending'], + [{ state: 'EXPECTED' }, 'pending'], + [null, 'unknown'], + ])('maps the status %j to %s', async (statusCheckRollup, ciState) => { + const pullRequests = await fetchFrom([ + node({ + commits: { nodes: [{ commit: { statusCheckRollup } }] }, + }), + ]); - expect(pullRequests[0]?.ciState).toBe(ciState); + expect(pullRequests[0]?.ciState).toBe(ciState); + }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index a2c8f341..bb1b6db4 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -49,178 +49,184 @@ function groups(parts: Parameters<typeof reminder>[0]): string[] { .map((block) => sectionText(block) || '---'); } -describe('buildSlackPayload', () => { - it('starts with the header, counts, note and a divider, and ends with the legend', () => { - const { blocks } = build({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'failing' }), - ], - }, +describe('slack-payload', () => { + describe('buildSlackPayload', () => { + it('puts the header, counts and note above the groups and the legend below', () => { + const { blocks } = build({ byTeam: { a: [pr({ ciState: 'failing' })] } }); + + const types = blocks.map(({ type }) => type); + + expect(types).toStrictEqual([ + 'header', + 'context', + 'section', + 'divider', + 'section', + 'divider', + 'context', + ]); }); - expect(blocks.map(({ type }) => type)).toStrictEqual([ - 'header', - 'context', - 'section', - 'divider', - 'section', - 'divider', - 'section', - 'divider', - 'context', - ]); - expect(JSON.stringify(blocks[0])).toContain( - ':dependabot: Open Dependabot pull requests', - ); - expect(JSON.stringify(blocks[1])).toContain( - '<https://github.com/MetaMask/example|MetaMask/example> · *3* open · :white_check_mark: 1 passing · :x: 2 failing', - ); - expect(sectionText(blocks[2])).toContain('*Is your team tagged?*'); - expect(JSON.stringify(blocks.at(-1))).toContain( - ':white_check_mark: CI passes · :x: CI fails · :hourglass_flowing_sand: CI running · :white_circle: no checks', - ); - }); - - it('links the guide under the note when there is one', () => { - const { blocks } = build( - { byTeam: { a: [pr()] } }, - { guideUrl: 'https://example.com/guide' }, - ); - - expect(sectionText(blocks[2])).toMatch( - /\n<https:\/\/example\.com\/guide\|Read the full guide>$/u, - ); - }); + it('counts the open PRs by CI state', () => { + const { blocks } = build({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'failing' }), + ], + }, + }); + + const counts = JSON.stringify(blocks[1]); + + expect(counts).toContain( + '<https://github.com/MetaMask/example|MetaMask/example> · *3* open · :white_check_mark: 1 passing · :x: 2 failing', + ); + }); - it('groups PRs by CI state, with the shared ones last', () => { - const headings = groups({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'passing' }), - pr({ number: 2, ciState: 'failing' }), - pr({ number: 3, ciState: 'pending' }), - ], - }, - shared: [pr({ number: 4, requestedTeams: ['x'] })], - }).map((text) => text.split('\n')[0]); - - expect(headings).toStrictEqual([ - '*:white_check_mark: CI passing*', - '---', - '*:x: Needs a fix*', - '---', - '*:hourglass_flowing_sand: In progress*', - '---', - '*:busts_in_silhouette: Shared by many teams*', - ]); - }); + it('links the guide under the note when there is one', () => { + const { blocks } = build( + { byTeam: { a: [pr()] } }, + { guideUrl: 'https://example.com/guide' }, + ); - it('shows the package, versions and teams of each PR', () => { - const [text] = groups({ - byTeam: { - a: [pr({ number: 7, ciState: 'failing' })], - b: [pr({ number: 7, ciState: 'failing' })], - plain: [pr({ number: 7, ciState: 'failing' })], - }, + expect(sectionText(blocks[2])).toMatch( + /\n<https:\/\/example\.com\/guide\|Read the full guide>$/u, + ); }); - expect(text).toBe( - '*:x: Needs a fix*\n<https://github.com/MetaMask/example/pull/1|#7> `foo` 1.0.0 → 1.0.1\n@a-team @b-team plain', - ); - }); - - it('lists each PR once, even when many teams share it', () => { - const { blocks } = build({ - byTeam: { - a: [pr({ number: 1 }), pr({ number: 2 })], - b: [pr({ number: 2 })], - }, + it('groups PRs by CI state, with the shared ones last', () => { + const headings = groups({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'passing' }), + pr({ number: 2, ciState: 'failing' }), + pr({ number: 3, ciState: 'pending' }), + ], + }, + shared: [pr({ number: 4, requestedTeams: ['x'] })], + }).map((text) => text.split('\n')[0]); + + expect(headings).toStrictEqual([ + '*:white_check_mark: CI passing*', + '---', + '*:x: Needs a fix*', + '---', + '*:hourglass_flowing_sand: In progress*', + '---', + '*:busts_in_silhouette: Shared by many teams*', + ]); }); - const all = JSON.stringify(blocks); - expect(all.match(/\|#1>/gu)).toHaveLength(1); - expect(all.match(/\|#2>/gu)).toHaveLength(1); - }); + it('shows the package, versions and teams of each PR', () => { + const [text] = groups({ + byTeam: { + a: [pr({ number: 7, ciState: 'failing' })], + b: [pr({ number: 7, ciState: 'failing' })], + plain: [pr({ number: 7, ciState: 'failing' })], + }, + }); + + expect(text).toBe( + '*:x: Needs a fix*\n<https://github.com/MetaMask/example/pull/1|#7> `foo` 1.0.0 → 1.0.1\n@a-team @b-team plain', + ); + }); - it('shows a PR with no team under the fallback team', () => { - const [text] = groups({ - noTeam: [pr({ number: 5, ciState: 'passing' })], + it('lists each PR once, even when many teams share it', () => { + const { blocks } = build({ + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 2 })], + }, + }); + + const all = JSON.stringify(blocks); + expect(all.match(/\|#1>/gu)).toHaveLength(1); + expect(all.match(/\|#2>/gu)).toHaveLength(1); }); - expect(text).toBe( - '*:white_check_mark: CI passing*\n<https://github.com/MetaMask/example/pull/1|#5> `foo` 1.0.0 → 1.0.1\n@platform-team', - ); - }); + it('shows a PR with no team under the fallback team', () => { + const [text] = groups({ + noTeam: [pr({ number: 5, ciState: 'passing' })], + }); - it('shows shared PRs with their icon and team count, coordinated by the fallback team', () => { - const [text] = groups({ - shared: [ - pr({ - number: 9, - ciState: 'failing', - requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'], - }), - ], + expect(text).toBe( + '*:white_check_mark: CI passing*\n<https://github.com/MetaMask/example/pull/1|#5> `foo` 1.0.0 → 1.0.1\n@platform-team', + ); }); - expect(text?.split('\n').slice(0, 2)).toStrictEqual([ - '*:busts_in_silhouette: Shared by many teams*', - 'Coordinated by @platform-team', - ]); - expect(text).toMatch(/:x: <[^>]*\|#9> `foo` 1\.0\.0 → 1\.0\.1 · 6 teams$/u); - }); - - it('shows an icon on each PR in the in progress group', () => { - const [text] = groups({ - byTeam: { - a: [ - pr({ number: 1, ciState: 'pending' }), - pr({ number: 2, ciState: 'unknown' }), + it('shows shared PRs with their icon and team count, coordinated by the fallback team', () => { + const [text] = groups({ + shared: [ + pr({ + number: 9, + ciState: 'failing', + requestedTeams: ['a', 'b', 'c', 'd', 'e', 'f'], + }), ], - }, + }); + + expect(text?.split('\n').slice(0, 2)).toStrictEqual([ + '*:busts_in_silhouette: Shared by many teams*', + 'Coordinated by @platform-team', + ]); + expect(text).toMatch( + /:x: <[^>]*\|#9> `foo` 1\.0\.0 → 1\.0\.1 · 6 teams$/u, + ); }); - expect(text).toMatch(/:hourglass_flowing_sand: <[^>]*\|#1>/u); - expect(text).toMatch(/:white_circle: <[^>]*\|#2>/u); - }); + it('shows an icon on each PR in the in progress group', () => { + const [text] = groups({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'pending' }), + pr({ number: 2, ciState: 'unknown' }), + ], + }, + }); + + expect(text).toMatch(/:hourglass_flowing_sand: <[^>]*\|#1>/u); + expect(text).toMatch(/:white_circle: <[^>]*\|#2>/u); + }); - it('mentions the teams that have a handle in the text', () => { - const { text } = build({ byTeam: { a: [pr()], b: [pr()], plain: [pr()] } }); + it('mentions the teams that have a handle in the text', () => { + const { text } = build({ + byTeam: { a: [pr()], b: [pr()], plain: [pr()] }, + }); - expect(text).toBe( - 'Open Dependabot pull requests in MetaMask/example @a-team @b-team', - ); - }); + expect(text).toBe( + 'Open Dependabot pull requests in MetaMask/example @a-team @b-team', + ); + }); - it('escapes and shortens the title of a PR it cannot read', () => { - const [text] = groups({ - byTeam: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, + it('escapes and shortens the title of a PR it cannot read', () => { + const [text] = groups({ + byTeam: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, + }); + + expect(text).toContain('Odd <title> & '); + expect(text).toContain('…'); + expect(text?.length).toBeLessThan(500); }); - expect(text).toContain('Odd <title> & '); - expect(text).toContain('…'); - expect(text?.length).toBeLessThan(500); - }); + it('continues a long group in a new section with the heading repeated', () => { + const pullRequests = Array.from({ length: 60 }, (_, index) => + pr({ + number: index + 1, + title: `chore(deps): bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, + ciState: 'failing', + }), + ); + + const sections = groups({ byTeam: { a: pullRequests } }); - it('continues a long group in a new section with the heading repeated', () => { - const pullRequests = Array.from({ length: 60 }, (_, index) => - pr({ - number: index + 1, - title: `chore(deps): bump some-long-package-name-${index} from 1.0.0 to 1.0.1`, - ciState: 'failing', - }), - ); - - const sections = groups({ byTeam: { a: pullRequests } }); - - expect(sections.length).toBeGreaterThan(1); - for (const text of sections) { - expect(text.length).toBeLessThanOrEqual(3000); - expect(text.startsWith('*:x: Needs a fix*\n')).toBe(true); - } - expect(sections.join()).toContain('|#60>'); + expect(sections.length).toBeGreaterThan(1); + for (const text of sections) { + expect(text.length).toBeLessThanOrEqual(3000); + expect(text.startsWith('*:x: Needs a fix*\n')).toBe(true); + } + expect(sections.join()).toContain('|#60>'); + }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts index fc92bc81..6884364d 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts @@ -5,39 +5,41 @@ import { parseSharedTeamThreshold, } from '../../dependabot-pr-reminder/teams.mts'; -describe('parseOwnerTeams', () => { - it.each([undefined, '', ' \n ', ' , ,'])( - 'returns undefined for %j', - (value) => { - const teams = parseOwnerTeams(value); - - expect(teams).toBeUndefined(); - }, - ); - - it('splits, trims, and drops empty entries', () => { - const teams = parseOwnerTeams(' a, b ,,c '); - - expect(teams).toStrictEqual(['a', 'b', 'c']); +describe('teams', () => { + describe('parseOwnerTeams', () => { + it.each([undefined, '', ' \n ', ' , ,'])( + 'returns undefined for %j', + (value) => { + const teams = parseOwnerTeams(value); + + expect(teams).toBeUndefined(); + }, + ); + + it('splits, trims, and drops empty entries', () => { + const teams = parseOwnerTeams(' a, b ,,c '); + + expect(teams).toStrictEqual(['a', 'b', 'c']); + }); }); -}); -describe('parseSharedTeamThreshold', () => { - it.each([undefined, ' '])('returns undefined for %j', (value) => { - const threshold = parseSharedTeamThreshold(value); + describe('parseSharedTeamThreshold', () => { + it.each([undefined, ' '])('returns undefined for %j', (value) => { + const threshold = parseSharedTeamThreshold(value); - expect(threshold).toBeUndefined(); - }); + expect(threshold).toBeUndefined(); + }); - it('parses a positive whole number', () => { - const threshold = parseSharedTeamThreshold(' 4 '); + it('parses a positive whole number', () => { + const threshold = parseSharedTeamThreshold(' 4 '); - expect(threshold).toBe(4); - }); + expect(threshold).toBe(4); + }); - it.each(['0', '-1', '2.5', 'many'])('rejects %s', (value) => { - const parse = (): number | undefined => parseSharedTeamThreshold(value); + it.each(['0', '-1', '2.5', 'many'])('rejects %s', (value) => { + const parse = (): number | undefined => parseSharedTeamThreshold(value); - expect(parse).toThrow('SHARED_TEAM_THRESHOLD'); + expect(parse).toThrow('SHARED_TEAM_THRESHOLD'); + }); }); }); From 1f09684813066c9999915e76a8330ec73277e78e Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 16:06:04 +0100 Subject: [PATCH 41/61] refactor: run the reminder script directly, without the entry check --- .../scripts/dependabot-pr-reminder/cli.mts | 18 ++---- .../tests/dependabot-pr-reminder/cli.test.mts | 59 ++----------------- 2 files changed, 11 insertions(+), 66 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index b9ffceca..1db3e51a 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -1,7 +1,5 @@ -import { realpathSync } from 'node:fs'; import { appendFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; @@ -10,7 +8,7 @@ import { fetchDependabotPullRequests } from './github-api.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; -export async function main(environment: NodeJS.ProcessEnv): Promise<void> { +async function main(environment: NodeJS.ProcessEnv): Promise<void> { const repository = environment.GITHUB_REPOSITORY; const fallbackTeam = environment.FALLBACK_TEAM; const planningToken = environment.PLANNING_TOKEN; @@ -62,13 +60,7 @@ export async function main(environment: NodeJS.ProcessEnv): Promise<void> { await appendFile(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); } -// Real paths, so starting it through a symlinked directory still runs it. -if ( - process.argv[1] && - realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) -) { - main(process.env).catch((error: unknown) => { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; - }); -} +main(process.env).catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; +}); diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts index eb1fc27b..0e6815ec 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts @@ -1,10 +1,7 @@ import { execFile } from 'node:child_process'; -import { mkdtemp, rm, symlink } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; -import { afterEach, describe, expect, it } from 'vitest'; +import { describe, expect, it } from 'vitest'; const execFileAsync = promisify(execFile); @@ -13,57 +10,13 @@ const SCRIPT = fileURLToPath( ); describe('cli', () => { - describe('entry point', () => { - let directory: string | undefined; - - afterEach(async () => { - if (directory) { - await rm(directory, { recursive: true, force: true }); - directory = undefined; - } - }); - - /** - * Runs the script with no settings, so it stops at once with a message. - * - * @param scriptPath - The path to run it through. - * @returns What it printed on stderr. - */ - async function runWithoutSettings(scriptPath: string): Promise<string> { - try { - await execFileAsync(process.execPath, [scriptPath], { - env: { PATH: process.env.PATH ?? '' }, - }); - } catch (error) { - return (error as { stderr?: string }).stderr ?? ''; - } - return ''; - } - - it('runs when started by its plain path', async () => { - const output = await runWithoutSettings(SCRIPT); - - expect(output).toContain('are required'); + it('stops with a message when the required settings are missing', async () => { + const run = execFileAsync(process.execPath, [SCRIPT], { + env: { PATH: process.env.PATH }, }); - it('runs when started through a path with .. segments', async () => { - // Built as a string, since `path.join` would remove the `..` segments. - const dotted = `${dirname(SCRIPT)}/../dependabot-pr-reminder/cli.mts`; - - const output = await runWithoutSettings(dotted); - - expect(dotted).toContain('/../'); - expect(output).toContain('are required'); - }); - - it('runs when started through a symlinked directory', async () => { - directory = await mkdtemp(join(tmpdir(), 'reminder-cli-')); - const link = join(directory, 'scripts'); - await symlink(resolve(SCRIPT, '..'), link); - - const output = await runWithoutSettings(join(link, 'cli.mts')); - - expect(output).toContain('are required'); + await expect(run).rejects.toMatchObject({ + stderr: expect.stringContaining('are required'), }); }); }); From e47f0838552179d503ab3b73089def224b92e9d2 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 16:07:16 +0100 Subject: [PATCH 42/61] refactor: drop the unused topology ref input and the ReminderBlock export --- .github/actions/remind-dependabot-prs/action.yml | 5 ----- .github/scripts/dependabot-pr-reminder/cli.mts | 4 ++-- .github/scripts/dependabot-pr-reminder/slack-payload.mts | 2 +- .github/scripts/tests/dependabot-pr-reminder/fixtures.mts | 6 ++++-- .github/workflows/remind-dependabot-prs.yml | 6 ------ 5 files changed, 7 insertions(+), 16 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 22385eaf..4c4fde79 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -16,10 +16,6 @@ inputs: description: 'Team slug used for PRs that cannot be attributed to a team.' required: false default: 'core-platform' - topology-ref: - description: 'Git ref of MetaMask-planning to read topology.json from.' - required: false - default: 'main' shared-team-threshold: description: 'A PR requested from more than this many teams is listed under the fallback team.' required: false @@ -55,7 +51,6 @@ runs: PLANNING_TOKEN: ${{ inputs.planning-token }} OWNER_TEAMS: ${{ inputs.owner-teams }} FALLBACK_TEAM: ${{ inputs.fallback-team }} - TOPOLOGY_REF: ${{ inputs.topology-ref }} SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} GUIDE_URL: ${{ inputs.guide-url }} run: | diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 1db3e51a..46cfb137 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -38,8 +38,8 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { let topology: Topology = {}; try { topology = await fetchTopology({ - ref: environment.TOPOLOGY_REF?.trim() ? environment.TOPOLOGY_REF : 'main', - gh: { environment, token: planningToken }, + environment, + token: planningToken, }); } catch (error) { console.log( diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index c7c02064..0a2dd7fb 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -10,7 +10,7 @@ import type { Topology } from '../shared/topology.mts'; import { describeUpdate } from './dependabot-title.mts'; import type { PullRequest, Reminder } from './types.mts'; -export type ReminderBlock = +type ReminderBlock = | SlackBlock | { type: 'header'; diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts index c0255096..445fa28e 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts @@ -1,4 +1,4 @@ -import type { ReminderBlock } from '../../dependabot-pr-reminder/slack-payload.mts'; +import type { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; export function pr(overrides: Partial<PullRequest> = {}): PullRequest { @@ -12,6 +12,8 @@ export function pr(overrides: Partial<PullRequest> = {}): PullRequest { }; } -export function sectionText(block: ReminderBlock | undefined): string { +type Block = ReturnType<typeof buildSlackPayload>['blocks'][number]; + +export function sectionText(block: Block | undefined): string { return block && 'text' in block ? block.text.text : ''; } diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 12a999ba..1169b3a2 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -24,11 +24,6 @@ on: type: string default: 'core-platform' description: 'Team slug used for PRs that cannot be attributed to a team' - topology-ref: - required: false - type: string - default: 'main' - description: 'Git ref of MetaMask-planning to read topology.json from' shared-team-threshold: required: false type: number @@ -73,7 +68,6 @@ jobs: planning-token: ${{ steps.planning-token.outputs.token }} owner-teams: ${{ inputs.owner-teams }} fallback-team: ${{ inputs.fallback-team }} - topology-ref: ${{ inputs.topology-ref }} shared-team-threshold: ${{ inputs.shared-team-threshold }} guide-url: ${{ inputs.guide-url }} From b31f39873d0bed91f952153282d4b5bc9ffafcf6 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 16:23:28 +0100 Subject: [PATCH 43/61] feat: tag a team that owns every PR once, and make the note fit one team or several --- .../dependabot-pr-reminder/slack-payload.mts | 26 ++++++++-- .../slack-payload.test.mts | 47 +++++++++++++++++++ 2 files changed, 69 insertions(+), 4 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 0a2dd7fb..e645e7d2 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -37,7 +37,7 @@ const CI: Record<CiState, { icon: string; count: string; legend: string }> = { }; const NOTE = - ':wave: *Is your team tagged?* Check the changelogs, fix CI if it fails, and get approval from every tagged team before merging. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; + ':wave: *Open Dependabot PRs.* Check the changelogs, fix CI if it fails, and get approval before merging. If a PR lists several teams, each needs to approve it. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; const MAX_TITLE_LENGTH = 200; @@ -94,6 +94,8 @@ export function buildSlackPayload( return escapeSlack(handle); }; + const tags = (teams: string[]): string => teams.map(tag).join(' '); + // Each PR is listed once, with every team it was requested from. const owned = new Map< number, @@ -116,13 +118,22 @@ export function buildSlackPayload( own(pullRequest, fallbackTeam); } + // When every PR belongs to the same teams, tag them once instead of under + // each PR. + const sharedTeams = + owned.size > 1 && + new Set([...owned.values()].map(({ teams }) => [...teams].sort().join(','))) + .size === 1 + ? [...owned.values()][0]?.teams + : undefined; + const link = ({ url, number }: PullRequest): string => `<${url}|#${number}>`; const ownedItems = (states: CiState[], withIcon: boolean): string[] => [...owned.values()] .filter(({ pullRequest }) => states.includes(pullRequest.ciState)) .map( ({ pullRequest, teams }) => - `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describe(pullRequest)}\n${teams.map(tag).join(' ')}`, + `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describe(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, ); const shared = reminder.fallback.sharedByManyTeams; @@ -141,7 +152,7 @@ export function buildSlackPayload( ), shared.length > 0 ? packItems( - `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tag(fallbackTeam)}`, + `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([fallbackTeam])}`, shared.map( (pullRequest) => `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describe(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, @@ -158,6 +169,13 @@ export function buildSlackPayload( return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; }); + const note = section( + [ + sharedTeams ? `${tags(sharedTeams)} ${NOTE}` : NOTE, + ...(guideUrl ? [`<${guideUrl}|Read the full guide>`] : []), + ].join('\n'), + ); + return { text: [`Open Dependabot pull requests in ${repository}`, ...mentions].join( ' ', @@ -178,7 +196,7 @@ export function buildSlackPayload( ...counts, ].join(' · '), ), - section(guideUrl ? `${NOTE}\n<${guideUrl}|Read the full guide>` : NOTE), + note, divider, ...groups.flatMap((group, index) => index > 0 ? [divider, ...group] : group, diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index bb1b6db4..61bf813a 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -228,5 +228,52 @@ describe('slack-payload', () => { } expect(sections.join()).toContain('|#60>'); }); + + it('tags a team that owns every PR once at the top, not under each PR', () => { + const { blocks } = build({ + byTeam: { + a: [ + pr({ number: 1, ciState: 'failing' }), + pr({ number: 2, ciState: 'failing' }), + ], + }, + }); + + const note = sectionText(blocks[2]); + const group = sectionText(blocks[4]); + + expect(note.startsWith('@a-team ')).toBe(true); + expect(group).not.toContain('@a-team'); + expect(group).toMatch(/#1>[^\n]*\n\n[^\n]*#2>/u); + }); + + it('tags several teams once at the top when every PR has the same teams', () => { + const { blocks, text } = build({ + byTeam: { + a: [pr({ number: 1 }), pr({ number: 2 })], + b: [pr({ number: 1 }), pr({ number: 2 })], + }, + }); + + const note = sectionText(blocks[2]); + const group = sectionText(blocks[4]); + + expect(note.startsWith('@a-team @b-team ')).toBe(true); + expect(group).not.toContain('-team'); + expect(text).toContain('@a-team @b-team'); + }); + + it('keeps the teams under each PR when the PRs have different teams', () => { + const { blocks } = build({ + byTeam: { a: [pr({ number: 1 })], b: [pr({ number: 2 })] }, + }); + + const note = sectionText(blocks[2]); + const group = sectionText(blocks[4]); + + expect(note).not.toContain('@'); + expect(group).toContain('@a-team'); + expect(group).toContain('@b-team'); + }); }); }); From 78d24cab209de0086545edbb7ce717b7285eb4f7 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 16:31:14 +0100 Subject: [PATCH 44/61] feat: let callers override the reminder note and restore the multi team default --- .../actions/remind-dependabot-prs/action.yml | 5 +++ .../scripts/dependabot-pr-reminder/cli.mts | 1 + .../dependabot-pr-reminder/slack-payload.mts | 11 ++++--- .../slack-payload.test.mts | 32 +++++++++++++++++++ .github/workflows/remind-dependabot-prs.yml | 6 ++++ 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 4c4fde79..79e60e18 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -24,6 +24,10 @@ inputs: description: 'Link to a guide for handling these PRs, shown in the message. Empty for none.' required: false default: '' + reminder-note: + description: 'Note shown under the counts, as Slack mrkdwn. Empty uses the built in note.' + required: false + default: '' outputs: has-prs: @@ -53,6 +57,7 @@ runs: FALLBACK_TEAM: ${{ inputs.fallback-team }} SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} GUIDE_URL: ${{ inputs.guide-url }} + REMINDER_NOTE: ${{ inputs.reminder-note }} run: | set -euo pipefail node "$GITHUB_ACTION_PATH/../../scripts/dependabot-pr-reminder/cli.mts" diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 46cfb137..0f72465b 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -51,6 +51,7 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { fallbackTeam, repository, guideUrl: environment.GUIDE_URL?.trim(), + note: environment.REMINDER_NOTE?.trim(), }); const payloadPath = join( environment.RUNNER_TEMP ?? '.', diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index e645e7d2..d2def863 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -37,7 +37,7 @@ const CI: Record<CiState, { icon: string; count: string; legend: string }> = { }; const NOTE = - ':wave: *Open Dependabot PRs.* Check the changelogs, fix CI if it fails, and get approval before merging. If a PR lists several teams, each needs to approve it. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; + ':wave: *Is your team tagged?* Check the changelogs, fix CI if it fails, and get approval from every tagged team before merging. Pushing to a PR yourself is fine, but Dependabot stops updating it after that.'; const MAX_TITLE_LENGTH = 200; @@ -77,10 +77,12 @@ export function buildSlackPayload( fallbackTeam, repository, guideUrl, + note, }: { fallbackTeam: string; repository: string; guideUrl?: string | undefined; + note?: string | undefined; }, ): { text: string; blocks: ReminderBlock[] } { // A handle in the text becomes a Slack mention. Teams without one stay plain. @@ -169,9 +171,10 @@ export function buildSlackPayload( return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; }); - const note = section( + const noteText = note?.trim() ? note : NOTE; + const noteSection = section( [ - sharedTeams ? `${tags(sharedTeams)} ${NOTE}` : NOTE, + sharedTeams ? `${tags(sharedTeams)} ${noteText}` : noteText, ...(guideUrl ? [`<${guideUrl}|Read the full guide>`] : []), ].join('\n'), ); @@ -196,7 +199,7 @@ export function buildSlackPayload( ...counts, ].join(' · '), ), - note, + noteSection, divider, ...groups.flatMap((group, index) => index > 0 ? [divider, ...group] : group, diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 61bf813a..7c278be2 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -275,5 +275,37 @@ describe('slack-payload', () => { expect(group).toContain('@a-team'); expect(group).toContain('@b-team'); }); + + it('uses the note it is given instead of the built in one', () => { + const { blocks } = build( + { byTeam: { a: [pr()] } }, + { note: 'Custom note.' }, + ); + + const note = sectionText(blocks[2]); + + expect(note).toBe('Custom note.'); + }); + + it('keeps the built in note when the given note is blank', () => { + const { blocks } = build({ byTeam: { a: [pr()] } }, { note: ' ' }); + + const note = sectionText(blocks[2]); + + expect(note).toContain('*Is your team tagged?*'); + }); + + it('tags a shared owner before a custom note and links the guide after it', () => { + const { blocks } = build( + { byTeam: { a: [pr({ number: 1 }), pr({ number: 2 })] } }, + { note: 'Custom note.', guideUrl: 'https://example.com/guide' }, + ); + + const note = sectionText(blocks[2]); + + expect(note).toBe( + '@a-team Custom note.\n<https://example.com/guide|Read the full guide>', + ); + }); }); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 1169b3a2..c24f6f37 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -34,6 +34,11 @@ on: type: string default: '' description: 'Link to a guide for handling these PRs, shown in the message. Empty for none' + reminder-note: + required: false + type: string + default: '' + description: 'Note shown under the counts, as Slack mrkdwn. Empty uses the built in note' secrets: slack-webhook-url: required: true @@ -70,6 +75,7 @@ jobs: fallback-team: ${{ inputs.fallback-team }} shared-team-threshold: ${{ inputs.shared-team-threshold }} guide-url: ${{ inputs.guide-url }} + reminder-note: ${{ inputs.reminder-note }} - name: Send Slack notification if: steps.remind.outputs.has-prs == 'true' From 161f1f883497fe9f629174aac80b13d337fe093b Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 16:56:50 +0100 Subject: [PATCH 45/61] refactor: rename fallback-team to maintainer-team and make it required --- .../actions/remind-dependabot-prs/action.yml | 11 +++---- .../dependabot-pr-reminder/classify.mts | 8 ++--- .../scripts/dependabot-pr-reminder/cli.mts | 8 ++--- .../dependabot-pr-reminder/slack-payload.mts | 12 +++---- .../scripts/dependabot-pr-reminder/types.mts | 2 +- .../dependabot-pr-reminder/classify.test.mts | 32 +++++++++++-------- .../slack-payload.test.mts | 8 ++--- .github/workflows/remind-dependabot-prs.yml | 11 +++---- 8 files changed, 48 insertions(+), 44 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index 79e60e18..ea82a1cd 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -12,12 +12,11 @@ inputs: description: 'Comma-separated list of team slugs that own the invoking repository. May be empty.' required: false default: '' - fallback-team: - description: 'Team slug used for PRs that cannot be attributed to a team.' - required: false - default: 'core-platform' + maintainer-team: + description: 'Team that looks after the PRs no team is requested on, and coordinates the ones many teams share.' + required: true shared-team-threshold: - description: 'A PR requested from more than this many teams is listed under the fallback team.' + description: 'A PR requested from more than this many teams is listed under the maintainer team.' required: false default: '5' guide-url: @@ -54,7 +53,7 @@ runs: GH_TOKEN: ${{ inputs.github-token }} PLANNING_TOKEN: ${{ inputs.planning-token }} OWNER_TEAMS: ${{ inputs.owner-teams }} - FALLBACK_TEAM: ${{ inputs.fallback-team }} + MAINTAINER_TEAM: ${{ inputs.maintainer-team }} SHARED_TEAM_THRESHOLD: ${{ inputs.shared-team-threshold }} GUIDE_URL: ${{ inputs.guide-url }} REMINDER_NOTE: ${{ inputs.reminder-note }} diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 73c4b96a..cf1c3258 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -2,7 +2,7 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; // Groups PRs by the teams still requested as reviewers. A PR with more than -// `sharedTeamThreshold` teams has no single owner, so it goes to the fallback +// `sharedTeamThreshold` teams has no single owner, so it goes to the maintainer // team, like a PR with no team. export function classifyPullRequests( pullRequests: PullRequest[], @@ -14,7 +14,7 @@ export function classifyPullRequests( const owners = ownerTeams?.map(normalizeTeamSlug); const reminder: Reminder = { byTeam: {}, - fallback: { sharedByManyTeams: [], noTeam: [] }, + maintainer: { sharedByManyTeams: [], noTeam: [] }, }; for (const pullRequest of pullRequests) { @@ -25,13 +25,13 @@ export function classifyPullRequests( ); if (teams.size > sharedTeamThreshold) { - reminder.fallback.sharedByManyTeams.push(pullRequest); + reminder.maintainer.sharedByManyTeams.push(pullRequest); } else if (teams.size > 0) { for (const team of teams) { (reminder.byTeam[team] ??= []).push(pullRequest); } } else { - reminder.fallback.noTeam.push(pullRequest); + reminder.maintainer.noTeam.push(pullRequest); } } diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 0f72465b..37b671b6 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -10,12 +10,12 @@ import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; async function main(environment: NodeJS.ProcessEnv): Promise<void> { const repository = environment.GITHUB_REPOSITORY; - const fallbackTeam = environment.FALLBACK_TEAM; + const maintainerTeam = environment.MAINTAINER_TEAM; const planningToken = environment.PLANNING_TOKEN; const outputPath = environment.GITHUB_OUTPUT; - if (!repository || !fallbackTeam || !planningToken || !outputPath) { + if (!repository || !maintainerTeam || !planningToken || !outputPath) { throw new Error( - 'GITHUB_REPOSITORY, FALLBACK_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', + 'GITHUB_REPOSITORY, MAINTAINER_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } @@ -48,7 +48,7 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { } const payload = buildSlackPayload(reminder, topology, { - fallbackTeam, + maintainerTeam, repository, guideUrl: environment.GUIDE_URL?.trim(), note: environment.REMINDER_NOTE?.trim(), diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index d2def863..610a7000 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -74,12 +74,12 @@ export function buildSlackPayload( reminder: Reminder, topology: Topology, { - fallbackTeam, + maintainerTeam, repository, guideUrl, note, }: { - fallbackTeam: string; + maintainerTeam: string; repository: string; guideUrl?: string | undefined; note?: string | undefined; @@ -116,8 +116,8 @@ export function buildSlackPayload( own(pullRequest, team); } } - for (const pullRequest of reminder.fallback.noTeam) { - own(pullRequest, fallbackTeam); + for (const pullRequest of reminder.maintainer.noTeam) { + own(pullRequest, maintainerTeam); } // When every PR belongs to the same teams, tag them once instead of under @@ -138,7 +138,7 @@ export function buildSlackPayload( `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describe(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, ); - const shared = reminder.fallback.sharedByManyTeams; + const shared = reminder.maintainer.sharedByManyTeams; const groups = [ packItems( `*${CI.passing.icon} CI passing*`, @@ -154,7 +154,7 @@ export function buildSlackPayload( ), shared.length > 0 ? packItems( - `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([fallbackTeam])}`, + `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([maintainerTeam])}`, shared.map( (pullRequest) => `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describe(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 7cd44b49..434352a1 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -8,7 +8,7 @@ export type PullRequest = { export type Reminder = { byTeam: Record<string, PullRequest[]>; - fallback: { + maintainer: { sharedByManyTeams: PullRequest[]; noTeam: PullRequest[]; }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index 27d8ec99..bdbec9f2 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -15,30 +15,36 @@ describe('classify', () => { expect(byTeam).toStrictEqual({ a: [pullRequest], b: [pullRequest] }); }); - it('puts a PR with no team in the fallback', () => { + it('puts a PR with no team with the maintainer team', () => { const pullRequest = pr(); - const { fallback } = classifyPullRequests([pullRequest], options); + const { maintainer } = classifyPullRequests([pullRequest], options); - expect(fallback.noTeam).toStrictEqual([pullRequest]); + expect(maintainer.noTeam).toStrictEqual([pullRequest]); }); it('keeps a PR with exactly the threshold under its teams', () => { const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + const { byTeam, maintainer } = classifyPullRequests( + [pullRequest], + options, + ); expect(Object.keys(byTeam)).toStrictEqual(['a', 'b', 'c']); - expect(fallback.sharedByManyTeams).toStrictEqual([]); + expect(maintainer.sharedByManyTeams).toStrictEqual([]); }); - it('puts a PR with more teams than the threshold in the fallback', () => { + it('puts a PR with more teams than the threshold with the maintainer team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], options); + const { byTeam, maintainer } = classifyPullRequests( + [pullRequest], + options, + ); expect(byTeam).toStrictEqual({}); - expect(fallback.sharedByManyTeams).toStrictEqual([pullRequest]); + expect(maintainer.sharedByManyTeams).toStrictEqual([pullRequest]); }); it('only counts the owner teams, ignoring case and repeats', () => { @@ -46,25 +52,25 @@ describe('classify', () => { requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], { + const { byTeam, maintainer } = classifyPullRequests([pullRequest], { ...options, ownerTeams: ['@MetaMask/a', 'b'], }); expect(Object.keys(byTeam)).toStrictEqual(['a', 'b']); - expect(fallback.sharedByManyTeams).toStrictEqual([]); + expect(maintainer.sharedByManyTeams).toStrictEqual([]); }); - it('puts a PR in the fallback when no owner team is left', () => { + it('puts a PR with the maintainer team when no owner team is left', () => { const pullRequest = pr({ requestedTeams: ['ui'] }); - const { byTeam, fallback } = classifyPullRequests([pullRequest], { + const { byTeam, maintainer } = classifyPullRequests([pullRequest], { ...options, ownerTeams: ['extension-platform'], }); expect(byTeam).toStrictEqual({}); - expect(fallback.noTeam).toStrictEqual([pullRequest]); + expect(maintainer.noTeam).toStrictEqual([pullRequest]); }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 7c278be2..733089e1 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -7,7 +7,7 @@ import type { } from '../../dependabot-pr-reminder/types.mts'; import { pr, sectionText } from './fixtures.mts'; -const options = { fallbackTeam: 'platform', repository: 'MetaMask/example' }; +const options = { maintainerTeam: 'platform', repository: 'MetaMask/example' }; const topology = { a: { githubHandle: 'MetaMask/a', slackHandle: { team: '@a-team' } }, @@ -25,7 +25,7 @@ function reminder(parts: { }): Reminder { return { byTeam: parts.byTeam ?? {}, - fallback: { + maintainer: { sharedByManyTeams: parts.shared ?? [], noTeam: parts.noTeam ?? [], }, @@ -146,7 +146,7 @@ describe('slack-payload', () => { expect(all.match(/\|#2>/gu)).toHaveLength(1); }); - it('shows a PR with no team under the fallback team', () => { + it('shows a PR with no team under the maintainer team', () => { const [text] = groups({ noTeam: [pr({ number: 5, ciState: 'passing' })], }); @@ -156,7 +156,7 @@ describe('slack-payload', () => { ); }); - it('shows shared PRs with their icon and team count, coordinated by the fallback team', () => { + it('shows shared PRs with their icon and team count, coordinated by the maintainer team', () => { const [text] = groups({ shared: [ pr({ diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index c24f6f37..276d7538 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -19,16 +19,15 @@ on: type: string default: '' description: 'Comma-separated team slugs that own the calling repository' - fallback-team: - required: false + maintainer-team: + required: true type: string - default: 'core-platform' - description: 'Team slug used for PRs that cannot be attributed to a team' + description: 'Team that looks after the PRs no team is requested on, and coordinates the ones many teams share' shared-team-threshold: required: false type: number default: 5 - description: 'A PR requested from more than this many teams is listed under the fallback team' + description: 'A PR requested from more than this many teams is listed under the maintainer team' guide-url: required: false type: string @@ -72,7 +71,7 @@ jobs: github-token: ${{ github.token }} planning-token: ${{ steps.planning-token.outputs.token }} owner-teams: ${{ inputs.owner-teams }} - fallback-team: ${{ inputs.fallback-team }} + maintainer-team: ${{ inputs.maintainer-team }} shared-team-threshold: ${{ inputs.shared-team-threshold }} guide-url: ${{ inputs.guide-url }} reminder-note: ${{ inputs.reminder-note }} From 01c0373815df453c0f12d48ec0c1a0e87e9ddd63 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Wed, 2 Dec 2026 17:28:53 +0100 Subject: [PATCH 46/61] fix: address review feedback on the reminder Fail the Slack step when the webhook rejects the message, read up to 100 review requests, reject a note that is too long once the team tags and guide link are added, and keep teams in a Map so a team named constructor cannot break the report. --- .../dependabot-pr-reminder/classify.mts | 9 ++++-- .../dependabot-pr-reminder/github-api.mts | 2 +- .../dependabot-pr-reminder/slack-payload.mts | 18 +++++++----- .../scripts/dependabot-pr-reminder/types.mts | 2 +- .../dependabot-pr-reminder/classify.test.mts | 23 +++++++++++---- .../slack-payload.test.mts | 28 ++++++++++++++++++- .github/workflows/remind-dependabot-prs.yml | 1 + 7 files changed, 66 insertions(+), 17 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index cf1c3258..4ca5e07a 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -13,7 +13,7 @@ export function classifyPullRequests( ): Reminder { const owners = ownerTeams?.map(normalizeTeamSlug); const reminder: Reminder = { - byTeam: {}, + byTeam: new Map(), maintainer: { sharedByManyTeams: [], noTeam: [] }, }; @@ -28,7 +28,12 @@ export function classifyPullRequests( reminder.maintainer.sharedByManyTeams.push(pullRequest); } else if (teams.size > 0) { for (const team of teams) { - (reminder.byTeam[team] ??= []).push(pullRequest); + const teamPullRequests = reminder.byTeam.get(team); + if (teamPullRequests) { + teamPullRequests.push(pullRequest); + } else { + reminder.byTeam.set(team, [pullRequest]); + } } } else { reminder.maintainer.noTeam.push(pullRequest); diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index cf6b6b04..4d8acb03 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -32,7 +32,7 @@ query($searchQuery: String!, $endCursor: String) { number title url - reviewRequests(first: 20) { + reviewRequests(first: 100) { nodes { requestedReviewer { __typename ... on Team { slug } } } } commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 610a7000..d0769826 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -111,7 +111,7 @@ export function buildSlackPayload( owned.set(pullRequest.number, { pullRequest, teams: [team] }); } }; - for (const [team, pullRequests] of Object.entries(reminder.byTeam)) { + for (const [team, pullRequests] of reminder.byTeam) { for (const pullRequest of pullRequests) { own(pullRequest, team); } @@ -172,12 +172,16 @@ export function buildSlackPayload( }); const noteText = note?.trim() ? note : NOTE; - const noteSection = section( - [ - sharedTeams ? `${tags(sharedTeams)} ${noteText}` : noteText, - ...(guideUrl ? [`<${guideUrl}|Read the full guide>`] : []), - ].join('\n'), - ); + const noteSectionText = [ + sharedTeams ? `${tags(sharedTeams)} ${noteText}` : noteText, + ...(guideUrl ? [`<${guideUrl}|Read the full guide>`] : []), + ].join('\n'); + if (noteSectionText.length > MAX_SECTION_LENGTH) { + throw new Error( + `The reminder note is too long with its team tags and guide link: ${noteSectionText.length} characters, the limit is ${MAX_SECTION_LENGTH}`, + ); + } + const noteSection = section(noteSectionText); return { text: [`Open Dependabot pull requests in ${repository}`, ...mentions].join( diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 434352a1..f77a402b 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -7,7 +7,7 @@ export type PullRequest = { }; export type Reminder = { - byTeam: Record<string, PullRequest[]>; + byTeam: Map<string, PullRequest[]>; maintainer: { sharedByManyTeams: PullRequest[]; noTeam: PullRequest[]; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts index bdbec9f2..f4e8991e 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts @@ -12,7 +12,12 @@ describe('classify', () => { const { byTeam } = classifyPullRequests([pullRequest], options); - expect(byTeam).toStrictEqual({ a: [pullRequest], b: [pullRequest] }); + expect(byTeam).toStrictEqual( + new Map([ + ['a', [pullRequest]], + ['b', [pullRequest]], + ]), + ); }); it('puts a PR with no team with the maintainer team', () => { @@ -31,7 +36,7 @@ describe('classify', () => { options, ); - expect(Object.keys(byTeam)).toStrictEqual(['a', 'b', 'c']); + expect([...byTeam.keys()]).toStrictEqual(['a', 'b', 'c']); expect(maintainer.sharedByManyTeams).toStrictEqual([]); }); @@ -43,7 +48,7 @@ describe('classify', () => { options, ); - expect(byTeam).toStrictEqual({}); + expect(byTeam.size).toBe(0); expect(maintainer.sharedByManyTeams).toStrictEqual([pullRequest]); }); @@ -57,7 +62,7 @@ describe('classify', () => { ownerTeams: ['@MetaMask/a', 'b'], }); - expect(Object.keys(byTeam)).toStrictEqual(['a', 'b']); + expect([...byTeam.keys()]).toStrictEqual(['a', 'b']); expect(maintainer.sharedByManyTeams).toStrictEqual([]); }); @@ -69,8 +74,16 @@ describe('classify', () => { ownerTeams: ['extension-platform'], }); - expect(byTeam).toStrictEqual({}); + expect(byTeam.size).toBe(0); expect(maintainer.noTeam).toStrictEqual([pullRequest]); }); + + it('lists a team named like an object property', () => { + const pullRequest = pr({ requestedTeams: ['constructor'] }); + + const { byTeam } = classifyPullRequests([pullRequest], options); + + expect(byTeam.get('constructor')).toStrictEqual([pullRequest]); + }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index 733089e1..ea3f75c9 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -24,7 +24,7 @@ function reminder(parts: { noTeam?: PullRequest[]; }): Reminder { return { - byTeam: parts.byTeam ?? {}, + byTeam: new Map(Object.entries(parts.byTeam ?? {})), maintainer: { sharedByManyTeams: parts.shared ?? [], noTeam: parts.noTeam ?? [], @@ -307,5 +307,31 @@ describe('slack-payload', () => { '@a-team Custom note.\n<https://example.com/guide|Read the full guide>', ); }); + + it('accepts a note that fits in one section', () => { + const act = (): unknown => + buildSlackPayload(reminder({ byTeam: { a: [pr()] } }), topology, { + ...options, + note: 'x'.repeat(2800), + }); + + expect(act).not.toThrow(); + }); + + it.each([ + ['a note over the limit', { note: 'x'.repeat(2801) }], + [ + 'a note that is too long once the guide link is added', + { note: 'x'.repeat(2790), guideUrl: 'https://example.com/guide' }, + ], + ])('rejects %s', (_name, extra) => { + const act = (): unknown => + buildSlackPayload(reminder({ byTeam: { a: [pr()] } }), topology, { + ...options, + ...extra, + }); + + expect(act).toThrow('The reminder note is too long'); + }); }); }); diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml index 276d7538..434b504a 100644 --- a/.github/workflows/remind-dependabot-prs.yml +++ b/.github/workflows/remind-dependabot-prs.yml @@ -82,4 +82,5 @@ jobs: with: webhook: ${{ secrets.slack-webhook-url }} webhook-type: incoming-webhook + errors: true payload-file-path: ${{ steps.remind.outputs.payload-path }} From bddbed6ee709a792d7724d4d92cf27c5a0ee4176 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 16:06:12 +0100 Subject: [PATCH 47/61] refactor: use Octokit in the reminder The PR search pages through the cursor with Octokit, each token gets its own client, and the action installs the github-tools dependencies first. --- .../actions/remind-dependabot-prs/action.yml | 10 ++ .../scripts/dependabot-pr-reminder/cli.mts | 24 +++-- .../dependabot-pr-reminder/github-api.mts | 95 ++++++++++--------- .../github-api.test.mts | 78 ++++++++++----- 4 files changed, 128 insertions(+), 79 deletions(-) diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml index ea82a1cd..9f6e8aaf 100644 --- a/.github/actions/remind-dependabot-prs/action.yml +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -45,6 +45,16 @@ runs: with: node-version: '24' + # Corepack resolves Yarn from the working directory, so install from the + # github-tools root to use its own pinned Yarn and lockfile. + - name: Install github-tools dependencies + shell: bash + working-directory: ${{ github.action_path }}/../../.. + run: | + set -euo pipefail + corepack enable + corepack yarn install --immutable + - name: Build Dependabot PR reminder id: reminder shell: bash diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 37b671b6..4bb71f65 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -1,6 +1,7 @@ import { appendFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; +import { createOctokit } from '../shared/octokit.mts'; import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import { classifyPullRequests } from './classify.mts'; @@ -11,17 +12,25 @@ import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; async function main(environment: NodeJS.ProcessEnv): Promise<void> { const repository = environment.GITHUB_REPOSITORY; const maintainerTeam = environment.MAINTAINER_TEAM; + const githubToken = environment.GH_TOKEN; const planningToken = environment.PLANNING_TOKEN; const outputPath = environment.GITHUB_OUTPUT; - if (!repository || !maintainerTeam || !planningToken || !outputPath) { + if ( + !repository || + !maintainerTeam || + !githubToken || + !planningToken || + !outputPath + ) { throw new Error( - 'GITHUB_REPOSITORY, MAINTAINER_TEAM, PLANNING_TOKEN and GITHUB_OUTPUT are required', + 'GITHUB_REPOSITORY, MAINTAINER_TEAM, GH_TOKEN, PLANNING_TOKEN and GITHUB_OUTPUT are required', ); } - const pullRequests = await fetchDependabotPullRequests(repository, { - environment, - }); + const pullRequests = await fetchDependabotPullRequests( + createOctokit(githubToken), + repository, + ); if (pullRequests.length === 0) { console.log('No open Dependabot pull requests to report.'); await appendFile(outputPath, 'has-prs=false\n'); @@ -37,10 +46,7 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { // Tags are optional, so the message still goes out without them. let topology: Topology = {}; try { - topology = await fetchTopology({ - environment, - token: planningToken, - }); + topology = await fetchTopology(createOctokit(planningToken)); } catch (error) { console.log( `::warning::Could not read topology.json, posting without Slack tags: ${String(error)}`, diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 4d8acb03..5e10bf79 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -1,24 +1,24 @@ -import { ghGraphqlPages } from '../shared/github-cli.mts'; -import type { GhOptions } from '../shared/github-cli.mts'; +import type { Octokit } from '@octokit/rest'; + +import { retryTransient } from '../shared/octokit.mts'; import type { PullRequest } from './types.mts'; -type SearchPage = { - data: { - search: { - nodes: { - number: number; - title: string; - url: string; - reviewRequests: { - nodes: { - requestedReviewer: { __typename: string; slug?: string } | null; - }[]; - }; - commits: { - nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; - }; - }[]; - }; +type SearchResult = { + search: { + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + nodes: { + number: number; + title: string; + url: string; + reviewRequests: { + nodes: { + requestedReviewer: { __typename: string; slug?: string } | null; + }[]; + }; + commits: { + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + }; + }[]; }; }; @@ -50,32 +50,39 @@ const CI_STATES: Record<string, PullRequest['ciState']> = { }; export async function fetchDependabotPullRequests( + octokit: Octokit, repository: string, - gh: GhOptions, ): Promise<PullRequest[]> { - const pages = await ghGraphqlPages<SearchPage>( - QUERY, - { - searchQuery: `repo:${repository} is:pr is:open draft:false author:app/dependabot`, - }, - gh, - ); + const searchQuery = `repo:${repository} is:pr is:open draft:false author:app/dependabot`; + const fetchPage = async ( + endCursor: string | null, + ): Promise<SearchResult['search']> => { + const { search } = await retryTransient( + async () => + await octokit.graphql<SearchResult>(QUERY, { searchQuery, endCursor }), + ); + return search; + }; + + let page = await fetchPage(null); + const nodes = [...page.nodes]; + while (page.pageInfo.hasNextPage) { + page = await fetchPage(page.pageInfo.endCursor); + nodes.push(...page.nodes); + } - return pages - .flatMap((page) => page.data.search.nodes) - .map((node) => ({ - number: node.number, - title: node.title, - url: node.url, - requestedTeams: node.reviewRequests.nodes.flatMap( - ({ requestedReviewer }) => - requestedReviewer?.__typename === 'Team' && requestedReviewer.slug - ? [requestedReviewer.slug] - : [], - ), - ciState: - CI_STATES[ - node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? '' - ] ?? 'unknown', - })); + return nodes.map((node) => ({ + number: node.number, + title: node.title, + url: node.url, + requestedTeams: node.reviewRequests.nodes.flatMap( + ({ requestedReviewer }) => + requestedReviewer?.__typename === 'Team' && requestedReviewer.slug + ? [requestedReviewer.slug] + : [], + ), + ciState: + CI_STATES[node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? ''] ?? + 'unknown', + })); } diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index 45e61b95..8f84ada9 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -1,3 +1,4 @@ +import type { Octokit } from '@octokit/rest'; import { describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; @@ -29,47 +30,74 @@ function node(overrides: Partial<Node> = {}): Node { }; } -type Run = (args: string[]) => Promise<string>; +type Graphql = (query: string, variables: object) => Promise<unknown>; -function runReturning(...pages: Node[][]): Mock<Run> { - return vi - .fn<Run>() - .mockResolvedValue( - JSON.stringify(pages.map((nodes) => ({ data: { search: { nodes } } }))), - ); +// One response per page, each pointing at the next one except the last. +function octokitReturning(...pages: Node[][]): { + octokit: Octokit; + graphql: Mock<Graphql>; +} { + const graphql = vi.fn<Graphql>(); + pages.forEach((nodes, index) => { + const hasNextPage = index < pages.length - 1; + graphql.mockResolvedValueOnce({ + search: { + pageInfo: { + hasNextPage, + endCursor: hasNextPage ? `cursor-${index}` : null, + }, + nodes, + }, + }); + }); + return { octokit: { graphql } as unknown as Octokit, graphql }; } async function fetchFrom(...pages: Node[][]): Promise<PullRequest[]> { - return await fetchDependabotPullRequests('MetaMask/core', { - environment: {}, - run: runReturning(...pages), - }); + return await fetchDependabotPullRequests( + octokitReturning(...pages).octokit, + 'MetaMask/core', + ); } describe('github-api', () => { describe('fetchDependabotPullRequests', () => { it('needs one request for one page and searches for open Dependabot PRs', async () => { - const run = runReturning([node()]); - await fetchDependabotPullRequests('MetaMask/core', { - environment: {}, - run, - }); + const { octokit, graphql } = octokitReturning([node()]); - expect(run).toHaveBeenCalledTimes(1); - expect(run.mock.calls[0]?.[0]).toContain( - 'searchQuery=repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', - ); + await fetchDependabotPullRequests(octokit, 'MetaMask/core'); + + expect(graphql).toHaveBeenCalledTimes(1); + expect(graphql.mock.calls[0]?.[1]).toStrictEqual({ + searchQuery: + 'repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', + endCursor: null, + }); }); - it('maps the PRs of every page', async () => { - const pullRequests = await fetchFrom( + it('follows the cursor to the next page and maps the PRs of every page', async () => { + const { octokit, graphql } = octokitReturning( [node({ number: 1 })], [node({ number: 2 })], ); + const pullRequests = await fetchDependabotPullRequests( + octokit, + 'MetaMask/core', + ); + expect(pullRequests.map(({ number }) => number)).toStrictEqual([1, 2]); + expect(graphql).toHaveBeenCalledTimes(2); + expect(graphql.mock.calls[1]?.[1]).toMatchObject({ + endCursor: 'cursor-0', + }); + }); + + it('maps a PR', async () => { + const pullRequests = await fetchFrom([node()]); + expect(pullRequests[0]).toStrictEqual({ - number: 1, + number: 7, title: 'Bump foo', url: 'https://github.com/MetaMask/example/pull/7', requestedTeams: [], @@ -102,9 +130,7 @@ describe('github-api', () => { [null, 'unknown'], ])('maps the status %j to %s', async (statusCheckRollup, ciState) => { const pullRequests = await fetchFrom([ - node({ - commits: { nodes: [{ commit: { statusCheckRollup } }] }, - }), + node({ commits: { nodes: [{ commit: { statusCheckRollup } }] } }), ]); expect(pullRequests[0]?.ciState).toBe(ciState); From 819c17d3dad3c8fb5c2815e3110e09c30845faac Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 16:23:00 +0100 Subject: [PATCH 48/61] refactor: rely on the Octokit retry plugin in the PR search --- .github/scripts/dependabot-pr-reminder/github-api.mts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 5e10bf79..b801bce4 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -1,6 +1,5 @@ import type { Octokit } from '@octokit/rest'; -import { retryTransient } from '../shared/octokit.mts'; import type { PullRequest } from './types.mts'; type SearchResult = { @@ -57,10 +56,10 @@ export async function fetchDependabotPullRequests( const fetchPage = async ( endCursor: string | null, ): Promise<SearchResult['search']> => { - const { search } = await retryTransient( - async () => - await octokit.graphql<SearchResult>(QUERY, { searchQuery, endCursor }), - ); + const { search } = await octokit.graphql<SearchResult>(QUERY, { + searchQuery, + endCursor, + }); return search; }; From cbaacdc81f0b13f03e9aadedfd20aa0a2e259549 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 16:34:51 +0100 Subject: [PATCH 49/61] refactor: import the Octokit type from octokit --- .github/scripts/dependabot-pr-reminder/github-api.mts | 2 +- .../scripts/tests/dependabot-pr-reminder/github-api.test.mts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index b801bce4..78970968 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -1,4 +1,4 @@ -import type { Octokit } from '@octokit/rest'; +import type { Octokit } from 'octokit'; import type { PullRequest } from './types.mts'; diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index 8f84ada9..d37053e1 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -1,4 +1,4 @@ -import type { Octokit } from '@octokit/rest'; +import type { Octokit } from 'octokit'; import { describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; From 3b79a3d1ef5227f9f1d97ebb971436537f0704ce Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 17:36:56 +0100 Subject: [PATCH 50/61] chore: lower coverage thresholds to match CI --- vitest.config.mts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vitest.config.mts b/vitest.config.mts index 39796f7f..7e04b4f5 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -49,10 +49,10 @@ export default defineConfig({ thresholds: { // Raises the thresholds in this file when coverage improves. autoUpdate: true, - branches: 42.22, - functions: 51.1, - lines: 41.78, - statements: 41.95, + branches: 43.79, + functions: 53.37, + lines: 43.19, + statements: 43.43, }, }, }, From 7f557f5c3f6982fc6e888f3c4f0af7a47742063d Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 17:42:32 +0100 Subject: [PATCH 51/61] docs: use JSDoc on the reminder helpers --- .../scripts/dependabot-pr-reminder/classify.mts | 14 +++++++++++--- .../dependabot-pr-reminder/dependabot-title.mts | 15 +++++++++++---- .../scripts/dependabot-pr-reminder/github-api.mts | 2 +- .../dependabot-pr-reminder/slack-payload.mts | 10 ++++++++-- .github/scripts/dependabot-pr-reminder/teams.mts | 15 +++++++++++++-- 5 files changed, 44 insertions(+), 12 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify.mts index 4ca5e07a..06184ecf 100644 --- a/.github/scripts/dependabot-pr-reminder/classify.mts +++ b/.github/scripts/dependabot-pr-reminder/classify.mts @@ -1,9 +1,17 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; import type { PullRequest, Reminder } from './types.mts'; -// Groups PRs by the teams still requested as reviewers. A PR with more than -// `sharedTeamThreshold` teams has no single owner, so it goes to the maintainer -// team, like a PR with no team. +/** + * Groups PRs by the teams still requested as reviewers. A PR with more than + * `sharedTeamThreshold` teams has no single owner, so it goes to the maintainer + * team, like a PR with no team. + * + * @param pullRequests - The open Dependabot PRs. + * @param options - The options. + * @param options.ownerTeams - Only these teams are reminded, or every team when omitted. + * @param options.sharedTeamThreshold - The most teams a PR can have and still be owned by them. + * @returns The PRs grouped by team, plus the ones the maintainer team handles. + */ export function classifyPullRequests( pullRequests: PullRequest[], { diff --git a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts index 027c15dd..8839feb5 100644 --- a/.github/scripts/dependabot-pr-reminder/dependabot-title.mts +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts @@ -1,8 +1,10 @@ import { escapeSlack } from '../shared/slack-blocks.mts'; -// `chore(deps-dev): bump foo from 1.0.0 to 2.0.0` and -// `chore(deps): bump the foo group across 1 directory with 7 updates`. The -// scope is captured to tell `deps-dev` from `deps`. +/** + * Matches `chore(deps-dev): bump foo from 1.0.0 to 2.0.0` and + * `chore(deps): bump the foo group across 1 directory with 7 updates`. The + * scope is captured to tell `deps-dev` from `deps`. + */ const PREFIX = String.raw`(?:[a-z]+(?:\(([^)]*)\))?!?:\s*)?`; const PACKAGE = new RegExp( `^${PREFIX}bump\\s+(\\S+)\\s+from\\s+(\\S+)\\s+to\\s+(\\S+?)(?:\\s+in\\s.*)?$`, @@ -16,7 +18,12 @@ const GROUP = new RegExp( const code = (value: string): string => `\`${escapeSlack(value).replaceAll('`', "'")}\``; -// Shortens a Dependabot title to `foo 1.0.0 → 2.0.0`, or undefined if it isn't one. +/** + * Shortens a Dependabot title to `foo 1.0.0 → 2.0.0`. + * + * @param title - The pull request title. + * @returns The short description, or `undefined` if the title isn't a Dependabot one. + */ export function describeUpdate(title: string): string | undefined { const [, scope, name, from, to] = PACKAGE.exec(title.trim()) ?? []; if (name && from && to) { diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 78970968..c36c8461 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -21,7 +21,7 @@ type SearchResult = { }; }; -// One query returns everything needed, so a run costs one request per 100 PRs. +/** One query returns everything needed, so a run costs one request per 100 PRs. */ const QUERY = ` query($searchQuery: String!, $endCursor: String) { search(query: $searchQuery, type: ISSUE, first: 100, after: $endCursor) { diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index d0769826..05849367 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -51,8 +51,14 @@ const context = (text: string): ReminderBlock => ({ const describe = ({ title }: PullRequest): string => describeUpdate(title) ?? escapeAndTruncate(title, MAX_TITLE_LENGTH); -// A section holds at most 3000 characters, so a long group continues in a new -// section with the heading repeated. +/** + * Packs items into sections. A section holds at most 3000 characters, so a long + * group continues in a new section with the heading repeated. + * + * @param heading - The group heading. + * @param items - The group items. + * @returns One or more sections. + */ function packItems(heading: string, items: string[]): ReminderBlock[] { const budget = MAX_SECTION_LENGTH - heading.length - 1; const chunks: string[][] = []; diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts index 3f0a63f9..2091f7ba 100644 --- a/.github/scripts/dependabot-pr-reminder/teams.mts +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -1,4 +1,9 @@ -// Comma separated team slugs, or undefined to keep every team. +/** + * Parses comma separated team slugs. + * + * @param value - The raw input. + * @returns The team slugs, or `undefined` to keep every team. + */ export function parseOwnerTeams( value: string | undefined, ): string[] | undefined { @@ -9,7 +14,13 @@ export function parseOwnerTeams( return teams.length > 0 ? teams : undefined; } -// A positive whole number, or undefined to use the default. +/** + * Parses the shared team threshold. + * + * @param value - The raw input. + * @returns A positive whole number, or `undefined` to use the default. + * @throws If the value is not a positive whole number. + */ export function parseSharedTeamThreshold( value: string | undefined, ): number | undefined { From 43ac93854d406893e53600b8cdfc2634d6cf3685 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 21:43:00 +0100 Subject: [PATCH 52/61] refactor: apply the easy review suggestions in the reminder --- ...lassify.mts => classify-pull-requests.mts} | 0 .../scripts/dependabot-pr-reminder/cli.mts | 20 ++++-- .../dependabot-pr-reminder/github-api.mts | 41 ++++++----- .../dependabot-pr-reminder/slack-payload.mts | 71 +++++++++++++------ .../scripts/dependabot-pr-reminder/types.mts | 2 + ...st.mts => classify-pull-requests.test.mts} | 4 +- 6 files changed, 90 insertions(+), 48 deletions(-) rename .github/scripts/dependabot-pr-reminder/{classify.mts => classify-pull-requests.mts} (100%) rename .github/scripts/tests/dependabot-pr-reminder/{classify.test.mts => classify-pull-requests.test.mts} (97%) diff --git a/.github/scripts/dependabot-pr-reminder/classify.mts b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts similarity index 100% rename from .github/scripts/dependabot-pr-reminder/classify.mts rename to .github/scripts/dependabot-pr-reminder/classify-pull-requests.mts diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index 4bb71f65..c0b3f3e8 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -1,15 +1,20 @@ import { appendFile, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; +import * as path from 'node:path'; import { createOctokit } from '../shared/octokit.mts'; import { fetchTopology } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; -import { classifyPullRequests } from './classify.mts'; +import { classifyPullRequests } from './classify-pull-requests.mts'; import { fetchDependabotPullRequests } from './github-api.mts'; import { buildSlackPayload } from './slack-payload.mts'; import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; -async function main(environment: NodeJS.ProcessEnv): Promise<void> { +/** + * Builds the Slack payload for the open Dependabot PRs and writes it, with the + * step outputs, for the workflow to post. + */ +async function main(): Promise<void> { + const environment = process.env; const repository = environment.GITHUB_REPOSITORY; const maintainerTeam = environment.MAINTAINER_TEAM; const githubToken = environment.GH_TOKEN; @@ -43,7 +48,6 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { parseSharedTeamThreshold(environment.SHARED_TEAM_THRESHOLD) ?? 5, }); - // Tags are optional, so the message still goes out without them. let topology: Topology = {}; try { topology = await fetchTopology(createOctokit(planningToken)); @@ -59,7 +63,7 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { guideUrl: environment.GUIDE_URL?.trim(), note: environment.REMINDER_NOTE?.trim(), }); - const payloadPath = join( + const payloadPath = path.join( environment.RUNNER_TEMP ?? '.', 'dependabot-reminder-payload.json', ); @@ -67,7 +71,9 @@ async function main(environment: NodeJS.ProcessEnv): Promise<void> { await appendFile(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); } -main(process.env).catch((error: unknown) => { +try { + await main(); +} catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; -}); +} diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index c36c8461..5002e9a1 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -2,6 +2,7 @@ import type { Octokit } from 'octokit'; import type { PullRequest } from './types.mts'; +/** The part of the GraphQL search response the reminder reads. */ type SearchResult = { search: { pageInfo: { hasNextPage: boolean; endCursor: string | null }; @@ -40,14 +41,21 @@ query($searchQuery: String!, $endCursor: String) { } }`; -const CI_STATES: Record<string, PullRequest['ciState']> = { +const CI_STATES = { SUCCESS: 'passing', FAILURE: 'failing', ERROR: 'failing', PENDING: 'pending', EXPECTED: 'pending', -}; +} as const satisfies Record<string, PullRequest['ciState']>; +/** + * Fetches the open, non draft Dependabot PRs of a repository. + * + * @param octokit - The Octokit client. + * @param repository - The repository as `owner/name`. + * @returns The PRs with their requested teams and CI state. + */ export async function fetchDependabotPullRequests( octokit: Octokit, repository: string, @@ -70,18 +78,19 @@ export async function fetchDependabotPullRequests( nodes.push(...page.nodes); } - return nodes.map((node) => ({ - number: node.number, - title: node.title, - url: node.url, - requestedTeams: node.reviewRequests.nodes.flatMap( - ({ requestedReviewer }) => - requestedReviewer?.__typename === 'Team' && requestedReviewer.slug - ? [requestedReviewer.slug] - : [], - ), - ciState: - CI_STATES[node.commits.nodes[0]?.commit.statusCheckRollup?.state ?? ''] ?? - 'unknown', - })); + return nodes.map((node) => { + const rollupState = node.commits.nodes[0]?.commit.statusCheckRollup?.state; + return { + number: node.number, + title: node.title, + url: node.url, + requestedTeams: node.reviewRequests.nodes.flatMap( + ({ requestedReviewer }) => + requestedReviewer?.__typename === 'Team' && requestedReviewer.slug + ? [requestedReviewer.slug] + : [], + ), + ciState: CI_STATES[rollupState as keyof typeof CI_STATES] ?? 'unknown', + }; + }); } diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 05849367..99054148 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -10,6 +10,7 @@ import type { Topology } from '../shared/topology.mts'; import { describeUpdate } from './dependabot-title.mts'; import type { PullRequest, Reminder } from './types.mts'; +/** A Slack block the reminder uses. */ type ReminderBlock = | SlackBlock | { @@ -19,9 +20,10 @@ type ReminderBlock = | { type: 'context'; elements: { type: 'mrkdwn'; text: string }[] } | { type: 'divider' }; -type CiState = PullRequest['ciState']; - -const CI: Record<CiState, { icon: string; count: string; legend: string }> = { +const CI: Record< + PullRequest['ciState'], + { icon: string; count: string; legend: string } +> = { passing: { icon: ':white_check_mark:', count: 'passing', @@ -48,7 +50,7 @@ const context = (text: string): ReminderBlock => ({ elements: [{ type: 'mrkdwn', text }], }); -const describe = ({ title }: PullRequest): string => +const describePullRequest = ({ title }: PullRequest): string => describeUpdate(title) ?? escapeAndTruncate(title, MAX_TITLE_LENGTH); /** @@ -76,6 +78,18 @@ function packItems(heading: string, items: string[]): ReminderBlock[] { return chunks.map((chunk) => section(`${heading}\n${chunk.join('\n\n')}`)); } +/** + * Builds the Slack message, tagging the teams that own each PR. + * + * @param reminder - The PRs grouped by team. + * @param topology - The parsed `topology.json`, used for the Slack handles. + * @param options - The options. + * @param options.maintainerTeam - The team that coordinates PRs with no single owner. + * @param options.repository - The repository as `owner/name`. + * @param options.guideUrl - A link to a guide, shown under the note. + * @param options.note - Replaces the default note. + * @returns The message text and blocks. + */ export function buildSlackPayload( reminder: Reminder, topology: Topology, @@ -105,43 +119,52 @@ export function buildSlackPayload( const tags = (teams: string[]): string => teams.map(tag).join(' '); // Each PR is listed once, with every team it was requested from. - const owned = new Map< + const pullRequestsWithOwners = new Map< number, { pullRequest: PullRequest; teams: string[] } >(); - const own = (pullRequest: PullRequest, team: string): void => { - const entry = owned.get(pullRequest.number); + const addOwner = (pullRequest: PullRequest, team: string): void => { + const entry = pullRequestsWithOwners.get(pullRequest.number); if (entry) { entry.teams.push(team); } else { - owned.set(pullRequest.number, { pullRequest, teams: [team] }); + pullRequestsWithOwners.set(pullRequest.number, { + pullRequest, + teams: [team], + }); } }; for (const [team, pullRequests] of reminder.byTeam) { for (const pullRequest of pullRequests) { - own(pullRequest, team); + addOwner(pullRequest, team); } } for (const pullRequest of reminder.maintainer.noTeam) { - own(pullRequest, maintainerTeam); + addOwner(pullRequest, maintainerTeam); } // When every PR belongs to the same teams, tag them once instead of under // each PR. const sharedTeams = - owned.size > 1 && - new Set([...owned.values()].map(({ teams }) => [...teams].sort().join(','))) - .size === 1 - ? [...owned.values()][0]?.teams + pullRequestsWithOwners.size > 1 && + new Set( + [...pullRequestsWithOwners.values()].map(({ teams }) => + [...teams].sort().join(','), + ), + ).size === 1 + ? [...pullRequestsWithOwners.values()][0]?.teams : undefined; const link = ({ url, number }: PullRequest): string => `<${url}|#${number}>`; - const ownedItems = (states: CiState[], withIcon: boolean): string[] => - [...owned.values()] + const ownedItems = ( + states: PullRequest['ciState'][], + withIcon: boolean, + ): string[] => + [...pullRequestsWithOwners.values()] .filter(({ pullRequest }) => states.includes(pullRequest.ciState)) .map( ({ pullRequest, teams }) => - `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describe(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, + `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describePullRequest(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, ); const shared = reminder.maintainer.sharedByManyTeams; @@ -163,19 +186,21 @@ export function buildSlackPayload( `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([maintainerTeam])}`, shared.map( (pullRequest) => - `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describe(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, + `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describePullRequest(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, ), ) : [], ].filter((group) => group.length > 0); - const all = [...owned.values()] + const all = [...pullRequestsWithOwners.values()] .map(({ pullRequest }) => pullRequest) .concat(shared); - const counts = (Object.keys(CI) as CiState[]).flatMap((state) => { - const total = all.filter(({ ciState }) => ciState === state).length; - return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; - }); + const counts = (Object.keys(CI) as PullRequest['ciState'][]).flatMap( + (state) => { + const total = all.filter(({ ciState }) => ciState === state).length; + return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; + }, + ); const noteText = note?.trim() ? note : NOTE; const noteSectionText = [ diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index f77a402b..5807f95a 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -1,3 +1,4 @@ +/** An open Dependabot pull request. */ export type PullRequest = { number: number; title: string; @@ -6,6 +7,7 @@ export type PullRequest = { ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; +/** The PRs to remind about, grouped by who handles them. */ export type Reminder = { byTeam: Map<string, PullRequest[]>; maintainer: { diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts similarity index 97% rename from .github/scripts/tests/dependabot-pr-reminder/classify.test.mts rename to .github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts index f4e8991e..14f54309 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts @@ -1,11 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { classifyPullRequests } from '../../dependabot-pr-reminder/classify.mts'; +import { classifyPullRequests } from '../../dependabot-pr-reminder/classify-pull-requests.mts'; import { pr } from './fixtures.mts'; const options = { sharedTeamThreshold: 3 }; -describe('classify', () => { +describe('classify-pull-requests', () => { describe('classifyPullRequests', () => { it('lists a PR under each requested team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b'] }); From ebe83857ee764450a80f0c432a16511fba2c340a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 21:46:06 +0100 Subject: [PATCH 53/61] chore: lower the branches coverage threshold to match CI --- vitest.config.mts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vitest.config.mts b/vitest.config.mts index 7e04b4f5..d254a357 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -49,7 +49,7 @@ export default defineConfig({ thresholds: { // Raises the thresholds in this file when coverage improves. autoUpdate: true, - branches: 43.79, + branches: 43.74, functions: 53.37, lines: 43.19, statements: 43.43, From fac0641ad4cfe376a6df80791756aeb9c9fc9c1a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 21:50:03 +0100 Subject: [PATCH 54/61] docs: document each property of the reminder types --- .../dependabot-pr-reminder/github-api.mts | 29 +++++++++++++++++-- .../dependabot-pr-reminder/slack-payload.mts | 7 ++++- .../scripts/dependabot-pr-reminder/types.mts | 9 ++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 5002e9a1..36e14064 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -5,18 +5,41 @@ import type { PullRequest } from './types.mts'; /** The part of the GraphQL search response the reminder reads. */ type SearchResult = { search: { - pageInfo: { hasNextPage: boolean; endCursor: string | null }; + /** Tells whether another page follows and where it starts. */ + pageInfo: { + /** Whether more results remain after this page. */ + hasNextPage: boolean; + /** The cursor to pass to get the next page. */ + endCursor: string | null; + }; + /** The matching pull requests. */ nodes: { + /** The pull request number. */ number: number; + /** The pull request title. */ title: string; + /** The link to the pull request. */ url: string; + /** The reviewers still requested. */ reviewRequests: { nodes: { - requestedReviewer: { __typename: string; slug?: string } | null; + /** The requested user or team, `null` when it can't be read. */ + requestedReviewer: { + /** The kind of reviewer, such as `Team` or `User`. */ + __typename: string; + /** The team slug, only set for a team. */ + slug?: string; + } | null; }[]; }; + /** The latest commit, which holds the checks state. */ commits: { - nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; + nodes: { + commit: { + /** The combined state of the checks, `null` when there are none. */ + statusCheckRollup: { state: string } | null; + }; + }[]; }; }[]; }; diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 99054148..b21b4dc1 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -15,9 +15,14 @@ type ReminderBlock = | SlackBlock | { type: 'header'; + /** The heading text. */ text: { type: 'plain_text'; text: string; emoji: true }; } - | { type: 'context'; elements: { type: 'mrkdwn'; text: string }[] } + | { + type: 'context'; + /** The small text shown in the block. */ + elements: { type: 'mrkdwn'; text: string }[]; + } | { type: 'divider' }; const CI: Record< diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 5807f95a..ffe22e2a 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -1,17 +1,26 @@ /** An open Dependabot pull request. */ export type PullRequest = { + /** The pull request number. */ number: number; + /** The pull request title. */ title: string; + /** The link to the pull request. */ url: string; + /** The slugs of the teams still requested as reviewers. */ requestedTeams: string[]; + /** The state of the latest commit's checks, `unknown` when there are none. */ ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; /** The PRs to remind about, grouped by who handles them. */ export type Reminder = { + /** The PRs each team owns, keyed by team slug. */ byTeam: Map<string, PullRequest[]>; + /** The PRs the maintainer team handles. */ maintainer: { + /** The PRs with more teams than the shared team threshold. */ sharedByManyTeams: PullRequest[]; + /** The PRs with no team to own them. */ noTeam: PullRequest[]; }; }; From 936323e0bb68f9fb12aa0876dab6c3f50f5cf3ac Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 21:57:33 +0100 Subject: [PATCH 55/61] chore: raise the coverage thresholds to match CI --- vitest.config.mts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vitest.config.mts b/vitest.config.mts index d254a357..bea9bcac 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -50,8 +50,8 @@ export default defineConfig({ // Raises the thresholds in this file when coverage improves. autoUpdate: true, branches: 43.74, - functions: 53.37, - lines: 43.19, + functions: 53.45, + lines: 43.2, statements: 43.43, }, }, From 1a52d4ed294b940ffcd900bbc38fbdc4793b9ff1 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:00:35 +0100 Subject: [PATCH 56/61] docs: describe the reminder type properties on the type itself --- .../dependabot-pr-reminder/github-api.mts | 44 +++++++------------ .../dependabot-pr-reminder/slack-payload.mts | 12 +++-- .../scripts/dependabot-pr-reminder/types.mts | 28 +++++++----- 3 files changed, 39 insertions(+), 45 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 36e14064..9854a3cf 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -2,44 +2,34 @@ import type { Octokit } from 'octokit'; import type { PullRequest } from './types.mts'; -/** The part of the GraphQL search response the reminder reads. */ +/** + * The part of the GraphQL search response the reminder reads. + * + * @property search - The search result. + * @property search.pageInfo - Tells whether another page follows and where it starts. + * @property search.pageInfo.hasNextPage - Whether more results remain after this page. + * @property search.pageInfo.endCursor - The cursor to pass to get the next page. + * @property search.nodes - The matching pull requests. + * @property search.nodes.number - The pull request number. + * @property search.nodes.title - The pull request title. + * @property search.nodes.url - The link to the pull request. + * @property search.nodes.reviewRequests - The reviewers still requested. + * @property search.nodes.commits - The latest commit, which holds the checks state. + */ type SearchResult = { search: { - /** Tells whether another page follows and where it starts. */ - pageInfo: { - /** Whether more results remain after this page. */ - hasNextPage: boolean; - /** The cursor to pass to get the next page. */ - endCursor: string | null; - }; - /** The matching pull requests. */ + pageInfo: { hasNextPage: boolean; endCursor: string | null }; nodes: { - /** The pull request number. */ number: number; - /** The pull request title. */ title: string; - /** The link to the pull request. */ url: string; - /** The reviewers still requested. */ reviewRequests: { nodes: { - /** The requested user or team, `null` when it can't be read. */ - requestedReviewer: { - /** The kind of reviewer, such as `Team` or `User`. */ - __typename: string; - /** The team slug, only set for a team. */ - slug?: string; - } | null; + requestedReviewer: { __typename: string; slug?: string } | null; }[]; }; - /** The latest commit, which holds the checks state. */ commits: { - nodes: { - commit: { - /** The combined state of the checks, `null` when there are none. */ - statusCheckRollup: { state: string } | null; - }; - }[]; + nodes: { commit: { statusCheckRollup: { state: string } | null } }[]; }; }[]; }; diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index b21b4dc1..cdbafeb1 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -10,19 +10,17 @@ import type { Topology } from '../shared/topology.mts'; import { describeUpdate } from './dependabot-title.mts'; import type { PullRequest, Reminder } from './types.mts'; -/** A Slack block the reminder uses. */ +/** + * A Slack block the reminder uses: a text block, a header whose `text` is the + * heading, a context block whose `elements` are the small text, or a divider. + */ type ReminderBlock = | SlackBlock | { type: 'header'; - /** The heading text. */ text: { type: 'plain_text'; text: string; emoji: true }; } - | { - type: 'context'; - /** The small text shown in the block. */ - elements: { type: 'mrkdwn'; text: string }[]; - } + | { type: 'context'; elements: { type: 'mrkdwn'; text: string }[] } | { type: 'divider' }; const CI: Record< diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index ffe22e2a..42098c9f 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -1,26 +1,32 @@ -/** An open Dependabot pull request. */ +/** + * An open Dependabot pull request. + * + * @property number - The pull request number. + * @property title - The pull request title. + * @property url - The link to the pull request. + * @property requestedTeams - The slugs of the teams still requested as reviewers. + * @property ciState - The state of the latest commit's checks, `unknown` when there are none. + */ export type PullRequest = { - /** The pull request number. */ number: number; - /** The pull request title. */ title: string; - /** The link to the pull request. */ url: string; - /** The slugs of the teams still requested as reviewers. */ requestedTeams: string[]; - /** The state of the latest commit's checks, `unknown` when there are none. */ ciState: 'passing' | 'failing' | 'pending' | 'unknown'; }; -/** The PRs to remind about, grouped by who handles them. */ +/** + * The PRs to remind about, grouped by who handles them. + * + * @property byTeam - The PRs each team owns, keyed by team slug. + * @property maintainer - The PRs the maintainer team handles. + * @property maintainer.sharedByManyTeams - The PRs with more teams than the shared team threshold. + * @property maintainer.noTeam - The PRs with no team to own them. + */ export type Reminder = { - /** The PRs each team owns, keyed by team slug. */ byTeam: Map<string, PullRequest[]>; - /** The PRs the maintainer team handles. */ maintainer: { - /** The PRs with more teams than the shared team threshold. */ sharedByManyTeams: PullRequest[]; - /** The PRs with no team to own them. */ noTeam: PullRequest[]; }; }; From 2164cb6987ba37942e606fd1b9bc7ad599513bef Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:08:54 +0100 Subject: [PATCH 57/61] refactor: group the reminder PRs by owner --- .../classify-pull-requests.mts | 45 ++++++------- .../scripts/dependabot-pr-reminder/cli.mts | 4 +- .../dependabot-pr-reminder/slack-payload.mts | 14 ++-- .../scripts/dependabot-pr-reminder/types.mts | 19 +++--- .../classify-pull-requests.test.mts | 45 +++++++------ .../slack-payload.test.mts | 64 +++++++++---------- 6 files changed, 96 insertions(+), 95 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts index 06184ecf..f4f39f8b 100644 --- a/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts +++ b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts @@ -1,16 +1,16 @@ import { normalizeTeamSlug } from '../shared/topology.mts'; -import type { PullRequest, Reminder } from './types.mts'; +import type { PullRequest, PullRequests } from './types.mts'; /** * Groups PRs by the teams still requested as reviewers. A PR with more than - * `sharedTeamThreshold` teams has no single owner, so it goes to the maintainer - * team, like a PR with no team. + * `sharedTeamThreshold` owners has no single owner, so the maintainer team + * handles it, like a PR with no owner. * * @param pullRequests - The open Dependabot PRs. * @param options - The options. * @param options.ownerTeams - Only these teams are reminded, or every team when omitted. - * @param options.sharedTeamThreshold - The most teams a PR can have and still be owned by them. - * @returns The PRs grouped by team, plus the ones the maintainer team handles. + * @param options.sharedTeamThreshold - The most owners a PR can have and still be owned by them. + * @returns The PRs grouped by owner. */ export function classifyPullRequests( pullRequests: PullRequest[], @@ -18,35 +18,36 @@ export function classifyPullRequests( ownerTeams, sharedTeamThreshold, }: { ownerTeams?: string[] | undefined; sharedTeamThreshold: number }, -): Reminder { - const owners = ownerTeams?.map(normalizeTeamSlug); - const reminder: Reminder = { - byTeam: new Map(), - maintainer: { sharedByManyTeams: [], noTeam: [] }, +): PullRequests { + const allowedOwners = ownerTeams?.map(normalizeTeamSlug); + const grouped: PullRequests = { + byOwner: new Map(), + sharedByManyOwners: [], + withNoOwners: [], }; for (const pullRequest of pullRequests) { - const teams = new Set( + const requestedOwners = new Set( pullRequest.requestedTeams .map(normalizeTeamSlug) - .filter((team) => !owners || owners.includes(team)), + .filter((team) => !allowedOwners || allowedOwners.includes(team)), ); - if (teams.size > sharedTeamThreshold) { - reminder.maintainer.sharedByManyTeams.push(pullRequest); - } else if (teams.size > 0) { - for (const team of teams) { - const teamPullRequests = reminder.byTeam.get(team); - if (teamPullRequests) { - teamPullRequests.push(pullRequest); + if (requestedOwners.size > sharedTeamThreshold) { + grouped.sharedByManyOwners.push(pullRequest); + } else if (requestedOwners.size > 0) { + for (const owner of requestedOwners) { + const ownerPullRequests = grouped.byOwner.get(owner); + if (ownerPullRequests) { + ownerPullRequests.push(pullRequest); } else { - reminder.byTeam.set(team, [pullRequest]); + grouped.byOwner.set(owner, [pullRequest]); } } } else { - reminder.maintainer.noTeam.push(pullRequest); + grouped.withNoOwners.push(pullRequest); } } - return reminder; + return grouped; } diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts index c0b3f3e8..eab91a51 100644 --- a/.github/scripts/dependabot-pr-reminder/cli.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -42,7 +42,7 @@ async function main(): Promise<void> { return; } - const reminder = classifyPullRequests(pullRequests, { + const grouped = classifyPullRequests(pullRequests, { ownerTeams: parseOwnerTeams(environment.OWNER_TEAMS), sharedTeamThreshold: parseSharedTeamThreshold(environment.SHARED_TEAM_THRESHOLD) ?? 5, @@ -57,7 +57,7 @@ async function main(): Promise<void> { ); } - const payload = buildSlackPayload(reminder, topology, { + const payload = buildSlackPayload(grouped, topology, { maintainerTeam, repository, guideUrl: environment.GUIDE_URL?.trim(), diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index cdbafeb1..111b47b6 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -8,7 +8,7 @@ import type { SlackBlock } from '../shared/slack-blocks.mts'; import { getSlackHandle, normalizeTeamSlug } from '../shared/topology.mts'; import type { Topology } from '../shared/topology.mts'; import { describeUpdate } from './dependabot-title.mts'; -import type { PullRequest, Reminder } from './types.mts'; +import type { PullRequest, PullRequests } from './types.mts'; /** * A Slack block the reminder uses: a text block, a header whose `text` is the @@ -84,7 +84,7 @@ function packItems(heading: string, items: string[]): ReminderBlock[] { /** * Builds the Slack message, tagging the teams that own each PR. * - * @param reminder - The PRs grouped by team. + * @param pullRequests - The PRs grouped by owner. * @param topology - The parsed `topology.json`, used for the Slack handles. * @param options - The options. * @param options.maintainerTeam - The team that coordinates PRs with no single owner. @@ -94,7 +94,7 @@ function packItems(heading: string, items: string[]): ReminderBlock[] { * @returns The message text and blocks. */ export function buildSlackPayload( - reminder: Reminder, + pullRequests: PullRequests, topology: Topology, { maintainerTeam, @@ -137,12 +137,12 @@ export function buildSlackPayload( }); } }; - for (const [team, pullRequests] of reminder.byTeam) { - for (const pullRequest of pullRequests) { + for (const [team, ownedPullRequests] of pullRequests.byOwner) { + for (const pullRequest of ownedPullRequests) { addOwner(pullRequest, team); } } - for (const pullRequest of reminder.maintainer.noTeam) { + for (const pullRequest of pullRequests.withNoOwners) { addOwner(pullRequest, maintainerTeam); } @@ -170,7 +170,7 @@ export function buildSlackPayload( `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describePullRequest(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, ); - const shared = reminder.maintainer.sharedByManyTeams; + const shared = pullRequests.sharedByManyOwners; const groups = [ packItems( `*${CI.passing.icon} CI passing*`, diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts index 42098c9f..0e12c7a0 100644 --- a/.github/scripts/dependabot-pr-reminder/types.mts +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -16,17 +16,14 @@ export type PullRequest = { }; /** - * The PRs to remind about, grouped by who handles them. + * The PRs to remind about, grouped by who owns them. * - * @property byTeam - The PRs each team owns, keyed by team slug. - * @property maintainer - The PRs the maintainer team handles. - * @property maintainer.sharedByManyTeams - The PRs with more teams than the shared team threshold. - * @property maintainer.noTeam - The PRs with no team to own them. + * @property byOwner - The PRs each owner has, keyed by team slug. + * @property sharedByManyOwners - The PRs with more owners than the shared team threshold. + * @property withNoOwners - The PRs with no owner. */ -export type Reminder = { - byTeam: Map<string, PullRequest[]>; - maintainer: { - sharedByManyTeams: PullRequest[]; - noTeam: PullRequest[]; - }; +export type PullRequests = { + byOwner: Map<string, PullRequest[]>; + sharedByManyOwners: PullRequest[]; + withNoOwners: PullRequest[]; }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts b/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts index 14f54309..0f5f9618 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts @@ -10,9 +10,9 @@ describe('classify-pull-requests', () => { it('lists a PR under each requested team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b'] }); - const { byTeam } = classifyPullRequests([pullRequest], options); + const { byOwner } = classifyPullRequests([pullRequest], options); - expect(byTeam).toStrictEqual( + expect(byOwner).toStrictEqual( new Map([ ['a', [pullRequest]], ['b', [pullRequest]], @@ -23,33 +23,33 @@ describe('classify-pull-requests', () => { it('puts a PR with no team with the maintainer team', () => { const pullRequest = pr(); - const { maintainer } = classifyPullRequests([pullRequest], options); + const { withNoOwners } = classifyPullRequests([pullRequest], options); - expect(maintainer.noTeam).toStrictEqual([pullRequest]); + expect(withNoOwners).toStrictEqual([pullRequest]); }); it('keeps a PR with exactly the threshold under its teams', () => { const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); - const { byTeam, maintainer } = classifyPullRequests( + const { byOwner, sharedByManyOwners } = classifyPullRequests( [pullRequest], options, ); - expect([...byTeam.keys()]).toStrictEqual(['a', 'b', 'c']); - expect(maintainer.sharedByManyTeams).toStrictEqual([]); + expect([...byOwner.keys()]).toStrictEqual(['a', 'b', 'c']); + expect(sharedByManyOwners).toStrictEqual([]); }); it('puts a PR with more teams than the threshold with the maintainer team', () => { const pullRequest = pr({ requestedTeams: ['a', 'b', 'c', 'd'] }); - const { byTeam, maintainer } = classifyPullRequests( + const { byOwner, sharedByManyOwners } = classifyPullRequests( [pullRequest], options, ); - expect(byTeam.size).toBe(0); - expect(maintainer.sharedByManyTeams).toStrictEqual([pullRequest]); + expect(byOwner.size).toBe(0); + expect(sharedByManyOwners).toStrictEqual([pullRequest]); }); it('only counts the owner teams, ignoring case and repeats', () => { @@ -57,33 +57,36 @@ describe('classify-pull-requests', () => { requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], }); - const { byTeam, maintainer } = classifyPullRequests([pullRequest], { - ...options, - ownerTeams: ['@MetaMask/a', 'b'], - }); + const { byOwner, sharedByManyOwners } = classifyPullRequests( + [pullRequest], + { + ...options, + ownerTeams: ['@MetaMask/a', 'b'], + }, + ); - expect([...byTeam.keys()]).toStrictEqual(['a', 'b']); - expect(maintainer.sharedByManyTeams).toStrictEqual([]); + expect([...byOwner.keys()]).toStrictEqual(['a', 'b']); + expect(sharedByManyOwners).toStrictEqual([]); }); it('puts a PR with the maintainer team when no owner team is left', () => { const pullRequest = pr({ requestedTeams: ['ui'] }); - const { byTeam, maintainer } = classifyPullRequests([pullRequest], { + const { byOwner, withNoOwners } = classifyPullRequests([pullRequest], { ...options, ownerTeams: ['extension-platform'], }); - expect(byTeam.size).toBe(0); - expect(maintainer.noTeam).toStrictEqual([pullRequest]); + expect(byOwner.size).toBe(0); + expect(withNoOwners).toStrictEqual([pullRequest]); }); it('lists a team named like an object property', () => { const pullRequest = pr({ requestedTeams: ['constructor'] }); - const { byTeam } = classifyPullRequests([pullRequest], options); + const { byOwner } = classifyPullRequests([pullRequest], options); - expect(byTeam.get('constructor')).toStrictEqual([pullRequest]); + expect(byOwner.get('constructor')).toStrictEqual([pullRequest]); }); }); }); diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts index ea3f75c9..f55197a6 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; import type { PullRequest, - Reminder, + PullRequests, } from '../../dependabot-pr-reminder/types.mts'; import { pr, sectionText } from './fixtures.mts'; @@ -18,32 +18,30 @@ const topology = { }, }; -function reminder(parts: { - byTeam?: Record<string, PullRequest[]>; +function grouped(parts: { + byOwner?: Record<string, PullRequest[]>; shared?: PullRequest[]; - noTeam?: PullRequest[]; -}): Reminder { + withNoOwners?: PullRequest[]; +}): PullRequests { return { - byTeam: new Map(Object.entries(parts.byTeam ?? {})), - maintainer: { - sharedByManyTeams: parts.shared ?? [], - noTeam: parts.noTeam ?? [], - }, + byOwner: new Map(Object.entries(parts.byOwner ?? {})), + sharedByManyOwners: parts.shared ?? [], + withNoOwners: parts.withNoOwners ?? [], }; } function build( - parts: Parameters<typeof reminder>[0], + parts: Parameters<typeof grouped>[0], extra = {}, ): ReturnType<typeof buildSlackPayload> { - return buildSlackPayload(reminder(parts), topology, { + return buildSlackPayload(grouped(parts), topology, { ...options, ...extra, }); } // The blocks after the header, counts, note and first divider. -function groups(parts: Parameters<typeof reminder>[0]): string[] { +function groups(parts: Parameters<typeof grouped>[0]): string[] { return build(parts) .blocks.slice(4, -2) .map((block) => sectionText(block) || '---'); @@ -52,7 +50,9 @@ function groups(parts: Parameters<typeof reminder>[0]): string[] { describe('slack-payload', () => { describe('buildSlackPayload', () => { it('puts the header, counts and note above the groups and the legend below', () => { - const { blocks } = build({ byTeam: { a: [pr({ ciState: 'failing' })] } }); + const { blocks } = build({ + byOwner: { a: [pr({ ciState: 'failing' })] }, + }); const types = blocks.map(({ type }) => type); @@ -69,7 +69,7 @@ describe('slack-payload', () => { it('counts the open PRs by CI state', () => { const { blocks } = build({ - byTeam: { + byOwner: { a: [ pr({ number: 1, ciState: 'passing' }), pr({ number: 2, ciState: 'failing' }), @@ -87,7 +87,7 @@ describe('slack-payload', () => { it('links the guide under the note when there is one', () => { const { blocks } = build( - { byTeam: { a: [pr()] } }, + { byOwner: { a: [pr()] } }, { guideUrl: 'https://example.com/guide' }, ); @@ -98,7 +98,7 @@ describe('slack-payload', () => { it('groups PRs by CI state, with the shared ones last', () => { const headings = groups({ - byTeam: { + byOwner: { a: [ pr({ number: 1, ciState: 'passing' }), pr({ number: 2, ciState: 'failing' }), @@ -121,7 +121,7 @@ describe('slack-payload', () => { it('shows the package, versions and teams of each PR', () => { const [text] = groups({ - byTeam: { + byOwner: { a: [pr({ number: 7, ciState: 'failing' })], b: [pr({ number: 7, ciState: 'failing' })], plain: [pr({ number: 7, ciState: 'failing' })], @@ -135,7 +135,7 @@ describe('slack-payload', () => { it('lists each PR once, even when many teams share it', () => { const { blocks } = build({ - byTeam: { + byOwner: { a: [pr({ number: 1 }), pr({ number: 2 })], b: [pr({ number: 2 })], }, @@ -148,7 +148,7 @@ describe('slack-payload', () => { it('shows a PR with no team under the maintainer team', () => { const [text] = groups({ - noTeam: [pr({ number: 5, ciState: 'passing' })], + withNoOwners: [pr({ number: 5, ciState: 'passing' })], }); expect(text).toBe( @@ -178,7 +178,7 @@ describe('slack-payload', () => { it('shows an icon on each PR in the in progress group', () => { const [text] = groups({ - byTeam: { + byOwner: { a: [ pr({ number: 1, ciState: 'pending' }), pr({ number: 2, ciState: 'unknown' }), @@ -192,7 +192,7 @@ describe('slack-payload', () => { it('mentions the teams that have a handle in the text', () => { const { text } = build({ - byTeam: { a: [pr()], b: [pr()], plain: [pr()] }, + byOwner: { a: [pr()], b: [pr()], plain: [pr()] }, }); expect(text).toBe( @@ -202,7 +202,7 @@ describe('slack-payload', () => { it('escapes and shortens the title of a PR it cannot read', () => { const [text] = groups({ - byTeam: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, + byOwner: { a: [pr({ title: `Odd <title> & ${'x'.repeat(500)}` })] }, }); expect(text).toContain('Odd <title> & '); @@ -219,7 +219,7 @@ describe('slack-payload', () => { }), ); - const sections = groups({ byTeam: { a: pullRequests } }); + const sections = groups({ byOwner: { a: pullRequests } }); expect(sections.length).toBeGreaterThan(1); for (const text of sections) { @@ -231,7 +231,7 @@ describe('slack-payload', () => { it('tags a team that owns every PR once at the top, not under each PR', () => { const { blocks } = build({ - byTeam: { + byOwner: { a: [ pr({ number: 1, ciState: 'failing' }), pr({ number: 2, ciState: 'failing' }), @@ -249,7 +249,7 @@ describe('slack-payload', () => { it('tags several teams once at the top when every PR has the same teams', () => { const { blocks, text } = build({ - byTeam: { + byOwner: { a: [pr({ number: 1 }), pr({ number: 2 })], b: [pr({ number: 1 }), pr({ number: 2 })], }, @@ -265,7 +265,7 @@ describe('slack-payload', () => { it('keeps the teams under each PR when the PRs have different teams', () => { const { blocks } = build({ - byTeam: { a: [pr({ number: 1 })], b: [pr({ number: 2 })] }, + byOwner: { a: [pr({ number: 1 })], b: [pr({ number: 2 })] }, }); const note = sectionText(blocks[2]); @@ -278,7 +278,7 @@ describe('slack-payload', () => { it('uses the note it is given instead of the built in one', () => { const { blocks } = build( - { byTeam: { a: [pr()] } }, + { byOwner: { a: [pr()] } }, { note: 'Custom note.' }, ); @@ -288,7 +288,7 @@ describe('slack-payload', () => { }); it('keeps the built in note when the given note is blank', () => { - const { blocks } = build({ byTeam: { a: [pr()] } }, { note: ' ' }); + const { blocks } = build({ byOwner: { a: [pr()] } }, { note: ' ' }); const note = sectionText(blocks[2]); @@ -297,7 +297,7 @@ describe('slack-payload', () => { it('tags a shared owner before a custom note and links the guide after it', () => { const { blocks } = build( - { byTeam: { a: [pr({ number: 1 }), pr({ number: 2 })] } }, + { byOwner: { a: [pr({ number: 1 }), pr({ number: 2 })] } }, { note: 'Custom note.', guideUrl: 'https://example.com/guide' }, ); @@ -310,7 +310,7 @@ describe('slack-payload', () => { it('accepts a note that fits in one section', () => { const act = (): unknown => - buildSlackPayload(reminder({ byTeam: { a: [pr()] } }), topology, { + buildSlackPayload(grouped({ byOwner: { a: [pr()] } }), topology, { ...options, note: 'x'.repeat(2800), }); @@ -326,7 +326,7 @@ describe('slack-payload', () => { ], ])('rejects %s', (_name, extra) => { const act = (): unknown => - buildSlackPayload(reminder({ byTeam: { a: [pr()] } }), topology, { + buildSlackPayload(grouped({ byOwner: { a: [pr()] } }), topology, { ...options, ...extra, }); From 066a5a051e24a8e9571178aaaf65bf283a375635 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:10:39 +0100 Subject: [PATCH 58/61] refactor: split building the Slack message into functions --- .../dependabot-pr-reminder/slack-payload.mts | 281 +++++++++++++----- 1 file changed, 204 insertions(+), 77 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/slack-payload.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.mts index 111b47b6..904302c8 100644 --- a/.github/scripts/dependabot-pr-reminder/slack-payload.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -53,9 +53,42 @@ const context = (text: string): ReminderBlock => ({ elements: [{ type: 'mrkdwn', text }], }); +/** + * A PR with every team it is listed under. + * + * @property pullRequest - The pull request. + * @property teams - The teams that own it. + */ +type OwnedPullRequest = { pullRequest: PullRequest; teams: string[] }; + +/** Turns team slugs into the text that tags them. */ +type Tags = (teams: string[]) => string; + +/** + * Makes a Slack link. + * + * @param url - Where the link goes. + * @param label - The link text. + * @returns The Slack link markup. + */ +const link = (url: string, label: string): string => `<${url}|${label}>`; + const describePullRequest = ({ title }: PullRequest): string => describeUpdate(title) ?? escapeAndTruncate(title, MAX_TITLE_LENGTH); +/** + * Describes a PR as its link and a short summary of the update. + * + * @param pullRequest - The pull request. + * @param withIcon - Whether to start with the CI icon. + * @returns The line for the PR. + */ +const formatPullRequest = ( + pullRequest: PullRequest, + withIcon: boolean, +): string => + `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest.url, `#${pullRequest.number}`)} ${describePullRequest(pullRequest)}`; + /** * Packs items into sections. A section holds at most 3000 characters, so a long * group continues in a new section with the heading repeated. @@ -82,59 +115,49 @@ function packItems(heading: string, items: string[]): ReminderBlock[] { } /** - * Builds the Slack message, tagging the teams that own each PR. + * Makes the function that tags teams. A handle in the text becomes a Slack + * mention, and teams without one stay plain. * - * @param pullRequests - The PRs grouped by owner. * @param topology - The parsed `topology.json`, used for the Slack handles. - * @param options - The options. - * @param options.maintainerTeam - The team that coordinates PRs with no single owner. - * @param options.repository - The repository as `owner/name`. - * @param options.guideUrl - A link to a guide, shown under the note. - * @param options.note - Replaces the default note. - * @returns The message text and blocks. + * @returns The `tags` function and the set of handles it mentioned so far. */ -export function buildSlackPayload( - pullRequests: PullRequests, - topology: Topology, - { - maintainerTeam, - repository, - guideUrl, - note, - }: { - maintainerTeam: string; - repository: string; - guideUrl?: string | undefined; - note?: string | undefined; - }, -): { text: string; blocks: ReminderBlock[] } { - // A handle in the text becomes a Slack mention. Teams without one stay plain. +function createTagger(topology: Topology): { + tags: Tags; + mentions: Set<string>; +} { const mentions = new Set<string>(); - const tag = (team: string): string => { - const handle = getSlackHandle(topology, team); - if (!handle) { - return escapeSlack(normalizeTeamSlug(team)); - } - mentions.add(escapeSlack(handle)); - return escapeSlack(handle); - }; - - const tags = (teams: string[]): string => teams.map(tag).join(' '); + const tags: Tags = (teams) => + teams + .map((team) => { + const handle = getSlackHandle(topology, team); + if (!handle) { + return escapeSlack(team); + } + mentions.add(escapeSlack(handle)); + return escapeSlack(handle); + }) + .join(' '); + return { tags, mentions }; +} - // Each PR is listed once, with every team it was requested from. - const pullRequestsWithOwners = new Map< - number, - { pullRequest: PullRequest; teams: string[] } - >(); +/** + * Lists each PR once, with every team it was requested from. + * + * @param pullRequests - The PRs grouped by owner. + * @param maintainerTeam - The team that owns the PRs with no owner. + * @returns The PRs with their teams. + */ +function collectOwned( + pullRequests: PullRequests, + maintainerTeam: string, +): OwnedPullRequest[] { + const byNumber = new Map<number, OwnedPullRequest>(); const addOwner = (pullRequest: PullRequest, team: string): void => { - const entry = pullRequestsWithOwners.get(pullRequest.number); + const entry = byNumber.get(pullRequest.number); if (entry) { entry.teams.push(team); } else { - pullRequestsWithOwners.set(pullRequest.number, { - pullRequest, - teams: [team], - }); + byNumber.set(pullRequest.number, { pullRequest, teams: [team] }); } }; for (const [team, ownedPullRequests] of pullRequests.byOwner) { @@ -145,33 +168,59 @@ export function buildSlackPayload( for (const pullRequest of pullRequests.withNoOwners) { addOwner(pullRequest, maintainerTeam); } + return [...byNumber.values()]; +} - // When every PR belongs to the same teams, tag them once instead of under - // each PR. - const sharedTeams = - pullRequestsWithOwners.size > 1 && - new Set( - [...pullRequestsWithOwners.values()].map(({ teams }) => - [...teams].sort().join(','), - ), - ).size === 1 - ? [...pullRequestsWithOwners.values()][0]?.teams - : undefined; +/** + * Finds the teams to tag once when every PR belongs to the same teams, instead + * of under each PR. + * + * @param owned - The PRs with their teams. + * @returns The shared teams, or `undefined` when the PRs differ. + */ +function findSharedTeams(owned: OwnedPullRequest[]): string[] | undefined { + const teamSets = new Set( + owned.map(({ teams }) => [...teams].sort().join(',')), + ); + return owned.length > 1 && teamSets.size === 1 ? owned[0]?.teams : undefined; +} - const link = ({ url, number }: PullRequest): string => `<${url}|#${number}>`; +/** + * Builds the groups of PRs, in the order they are shown. + * + * @param options - The options. + * @param options.owned - The PRs with their teams. + * @param options.shared - The PRs with more owners than the shared team threshold. + * @param options.sharedTeams - The teams tagged once at the top, if any. + * @param options.maintainerTeam - The team that coordinates the shared PRs. + * @param options.tags - Tags teams. + * @returns The groups, with the empty ones left out. + */ +function buildGroups({ + owned, + shared, + sharedTeams, + maintainerTeam, + tags, +}: { + owned: OwnedPullRequest[]; + shared: PullRequest[]; + sharedTeams: string[] | undefined; + maintainerTeam: string; + tags: Tags; +}): ReminderBlock[][] { const ownedItems = ( states: PullRequest['ciState'][], withIcon: boolean, ): string[] => - [...pullRequestsWithOwners.values()] + owned .filter(({ pullRequest }) => states.includes(pullRequest.ciState)) .map( ({ pullRequest, teams }) => - `${withIcon ? `${CI[pullRequest.ciState].icon} ` : ''}${link(pullRequest)} ${describePullRequest(pullRequest)}${sharedTeams ? '' : `\n${tags(teams)}`}`, + `${formatPullRequest(pullRequest, withIcon)}${sharedTeams ? '' : `\n${tags(teams)}`}`, ); - const shared = pullRequests.sharedByManyOwners; - const groups = [ + return [ packItems( `*${CI.passing.icon} CI passing*`, ownedItems(['passing'], false), @@ -189,33 +238,111 @@ export function buildSlackPayload( `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([maintainerTeam])}`, shared.map( (pullRequest) => - `${CI[pullRequest.ciState].icon} ${link(pullRequest)} ${describePullRequest(pullRequest)} · ${pullRequest.requestedTeams.length} teams`, + `${formatPullRequest(pullRequest, true)} · ${pullRequest.requestedTeams.length} teams`, ), ) : [], ].filter((group) => group.length > 0); +} - const all = [...pullRequestsWithOwners.values()] - .map(({ pullRequest }) => pullRequest) - .concat(shared); - const counts = (Object.keys(CI) as PullRequest['ciState'][]).flatMap( - (state) => { - const total = all.filter(({ ciState }) => ciState === state).length; - return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; - }, - ); +/** + * Counts the PRs by CI state. + * + * @param pullRequests - The PRs to count. + * @returns One entry per CI state that has PRs, such as `:x: 2 failing`. + */ +function countByCiState(pullRequests: PullRequest[]): string[] { + return (Object.keys(CI) as PullRequest['ciState'][]).flatMap((state) => { + const total = pullRequests.filter( + ({ ciState }) => ciState === state, + ).length; + return total > 0 ? [`${CI[state].icon} ${total} ${CI[state].count}`] : []; + }); +} +/** + * Builds the note under the header, with the shared teams tagged in front and + * the guide link below. + * + * @param options - The options. + * @param options.sharedTeams - The teams tagged once at the top, if any. + * @param options.tags - Tags teams. + * @param options.note - Replaces the default note. + * @param options.guideUrl - A link to a guide, shown under the note. + * @returns The note section. + * @throws If the note is too long for one section. + */ +function buildNoteSection({ + sharedTeams, + tags, + note, + guideUrl, +}: { + sharedTeams: string[] | undefined; + tags: Tags; + note: string | undefined; + guideUrl: string | undefined; +}): SlackBlock { const noteText = note?.trim() ? note : NOTE; - const noteSectionText = [ + const text = [ sharedTeams ? `${tags(sharedTeams)} ${noteText}` : noteText, - ...(guideUrl ? [`<${guideUrl}|Read the full guide>`] : []), + ...(guideUrl ? [link(guideUrl, 'Read the full guide')] : []), ].join('\n'); - if (noteSectionText.length > MAX_SECTION_LENGTH) { + if (text.length > MAX_SECTION_LENGTH) { throw new Error( - `The reminder note is too long with its team tags and guide link: ${noteSectionText.length} characters, the limit is ${MAX_SECTION_LENGTH}`, + `The reminder note is too long with its team tags and guide link: ${text.length} characters, the limit is ${MAX_SECTION_LENGTH}`, ); } - const noteSection = section(noteSectionText); + return section(text); +} + +/** + * Builds the Slack message, tagging the teams that own each PR. + * + * @param pullRequests - The PRs grouped by owner. + * @param topology - The parsed `topology.json`, used for the Slack handles. + * @param options - The options. + * @param options.maintainerTeam - The team that coordinates PRs with no single owner. + * @param options.repository - The repository as `owner/name`. + * @param options.guideUrl - A link to a guide, shown under the note. + * @param options.note - Replaces the default note. + * @returns The message text and blocks. + */ +export function buildSlackPayload( + pullRequests: PullRequests, + topology: Topology, + { + maintainerTeam, + repository, + guideUrl, + note, + }: { + maintainerTeam: string; + repository: string; + guideUrl?: string | undefined; + note?: string | undefined; + }, +): { text: string; blocks: ReminderBlock[] } { + const { tags, mentions } = createTagger(topology); + const maintainer = normalizeTeamSlug(maintainerTeam); + const owned = collectOwned(pullRequests, maintainer); + const shared = pullRequests.sharedByManyOwners; + const sharedTeams = findSharedTeams(owned); + + const groups = buildGroups({ + owned, + shared, + sharedTeams, + maintainerTeam: maintainer, + tags, + }); + const all = owned.map(({ pullRequest }) => pullRequest).concat(shared); + const noteSection = buildNoteSection({ + sharedTeams, + tags, + note, + guideUrl, + }); return { text: [`Open Dependabot pull requests in ${repository}`, ...mentions].join( @@ -232,9 +359,9 @@ export function buildSlackPayload( }, context( [ - `<https://github.com/${repository}|${escapeSlack(repository)}>`, + link(`https://github.com/${repository}`, escapeSlack(repository)), `*${all.length}* open`, - ...counts, + ...countByCiState(all), ].join(' · '), ), noteSection, From 4250f9ba08542a37b7bd3ce2da02841d53dfbeb1 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:13:53 +0100 Subject: [PATCH 59/61] refactor: paginate the PR search with Octokit --- .../dependabot-pr-reminder/github-api.mts | 26 +++------ .../github-api.test.mts | 53 ++++--------------- 2 files changed, 17 insertions(+), 62 deletions(-) diff --git a/.github/scripts/dependabot-pr-reminder/github-api.mts b/.github/scripts/dependabot-pr-reminder/github-api.mts index 9854a3cf..c418e646 100644 --- a/.github/scripts/dependabot-pr-reminder/github-api.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -37,8 +37,8 @@ type SearchResult = { /** One query returns everything needed, so a run costs one request per 100 PRs. */ const QUERY = ` -query($searchQuery: String!, $endCursor: String) { - search(query: $searchQuery, type: ISSUE, first: 100, after: $endCursor) { +query($searchQuery: String!, $cursor: String) { + search(query: $searchQuery, type: ISSUE, first: 100, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ... on PullRequest { @@ -73,25 +73,11 @@ export async function fetchDependabotPullRequests( octokit: Octokit, repository: string, ): Promise<PullRequest[]> { - const searchQuery = `repo:${repository} is:pr is:open draft:false author:app/dependabot`; - const fetchPage = async ( - endCursor: string | null, - ): Promise<SearchResult['search']> => { - const { search } = await octokit.graphql<SearchResult>(QUERY, { - searchQuery, - endCursor, - }); - return search; - }; - - let page = await fetchPage(null); - const nodes = [...page.nodes]; - while (page.pageInfo.hasNextPage) { - page = await fetchPage(page.pageInfo.endCursor); - nodes.push(...page.nodes); - } + const { search } = await octokit.graphql.paginate<SearchResult>(QUERY, { + searchQuery: `repo:${repository} is:pr is:open draft:false author:app/dependabot`, + }); - return nodes.map((node) => { + return search.nodes.map((node) => { const rollupState = node.commits.nodes[0]?.commit.statusCheckRollup?.state; return { number: node.number, diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts index d37053e1..3284d7fa 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts @@ -30,66 +30,35 @@ function node(overrides: Partial<Node> = {}): Node { }; } -type Graphql = (query: string, variables: object) => Promise<unknown>; +type Paginate = (query: string, variables: object) => Promise<unknown>; -// One response per page, each pointing at the next one except the last. -function octokitReturning(...pages: Node[][]): { +function octokitReturning(nodes: Node[]): { octokit: Octokit; - graphql: Mock<Graphql>; + paginate: Mock<Paginate>; } { - const graphql = vi.fn<Graphql>(); - pages.forEach((nodes, index) => { - const hasNextPage = index < pages.length - 1; - graphql.mockResolvedValueOnce({ - search: { - pageInfo: { - hasNextPage, - endCursor: hasNextPage ? `cursor-${index}` : null, - }, - nodes, - }, - }); + const paginate = vi.fn<Paginate>().mockResolvedValue({ + search: { pageInfo: { hasNextPage: false, endCursor: null }, nodes }, }); - return { octokit: { graphql } as unknown as Octokit, graphql }; + return { octokit: { graphql: { paginate } } as unknown as Octokit, paginate }; } -async function fetchFrom(...pages: Node[][]): Promise<PullRequest[]> { +async function fetchFrom(nodes: Node[]): Promise<PullRequest[]> { return await fetchDependabotPullRequests( - octokitReturning(...pages).octokit, + octokitReturning(nodes).octokit, 'MetaMask/core', ); } describe('github-api', () => { describe('fetchDependabotPullRequests', () => { - it('needs one request for one page and searches for open Dependabot PRs', async () => { - const { octokit, graphql } = octokitReturning([node()]); + it('searches for open Dependabot PRs', async () => { + const { octokit, paginate } = octokitReturning([node()]); await fetchDependabotPullRequests(octokit, 'MetaMask/core'); - expect(graphql).toHaveBeenCalledTimes(1); - expect(graphql.mock.calls[0]?.[1]).toStrictEqual({ + expect(paginate.mock.calls[0]?.[1]).toStrictEqual({ searchQuery: 'repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', - endCursor: null, - }); - }); - - it('follows the cursor to the next page and maps the PRs of every page', async () => { - const { octokit, graphql } = octokitReturning( - [node({ number: 1 })], - [node({ number: 2 })], - ); - - const pullRequests = await fetchDependabotPullRequests( - octokit, - 'MetaMask/core', - ); - - expect(pullRequests.map(({ number }) => number)).toStrictEqual([1, 2]); - expect(graphql).toHaveBeenCalledTimes(2); - expect(graphql.mock.calls[1]?.[1]).toMatchObject({ - endCursor: 'cursor-0', }); }); From 7e04f214a5836f3e07b62edda29cd184835dbd97 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:16:46 +0100 Subject: [PATCH 60/61] chore: update the coverage thresholds to match CI --- vitest.config.mts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vitest.config.mts b/vitest.config.mts index bea9bcac..47085782 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -50,9 +50,9 @@ export default defineConfig({ // Raises the thresholds in this file when coverage improves. autoUpdate: true, branches: 43.74, - functions: 53.45, - lines: 43.2, - statements: 43.43, + functions: 53.86, + lines: 43.24, + statements: 43.45, }, }, }, From 977f6f099315de67aa2f1e3f71dfcc4a615a12d1 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun <salah-eddine.saakoun@consensys.net> Date: Thu, 3 Dec 2026 22:33:29 +0100 Subject: [PATCH 61/61] refactor: keep the reminder tests next to the source --- .../dependabot-pr-reminder/classify-pull-requests.test.mts | 2 +- .../{tests => }/dependabot-pr-reminder/cli.test.mts | 4 +--- .../dependabot-pr-reminder/dependabot-title.test.mts | 2 +- .../{tests => }/dependabot-pr-reminder/fixtures.mts | 4 ++-- .../{tests => }/dependabot-pr-reminder/github-api.test.mts | 4 ++-- .../dependabot-pr-reminder/slack-payload.test.mts | 7 ++----- .../{tests => }/dependabot-pr-reminder/teams.test.mts | 5 +---- vitest.config.mts | 2 +- 8 files changed, 11 insertions(+), 19 deletions(-) rename .github/scripts/{tests => }/dependabot-pr-reminder/classify-pull-requests.test.mts (96%) rename .github/scripts/{tests => }/dependabot-pr-reminder/cli.test.mts (84%) rename .github/scripts/{tests => }/dependabot-pr-reminder/dependabot-title.test.mts (93%) rename .github/scripts/{tests => }/dependabot-pr-reminder/fixtures.mts (73%) rename .github/scripts/{tests => }/dependabot-pr-reminder/github-api.test.mts (94%) rename .github/scripts/{tests => }/dependabot-pr-reminder/slack-payload.test.mts (98%) rename .github/scripts/{tests => }/dependabot-pr-reminder/teams.test.mts (91%) diff --git a/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts similarity index 96% rename from .github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts rename to .github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts index 0f5f9618..9cc23693 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/classify-pull-requests.test.mts +++ b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { classifyPullRequests } from '../../dependabot-pr-reminder/classify-pull-requests.mts'; +import { classifyPullRequests } from './classify-pull-requests.mts'; import { pr } from './fixtures.mts'; const options = { sharedTeamThreshold: 3 }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts b/.github/scripts/dependabot-pr-reminder/cli.test.mts similarity index 84% rename from .github/scripts/tests/dependabot-pr-reminder/cli.test.mts rename to .github/scripts/dependabot-pr-reminder/cli.test.mts index 0e6815ec..99906d07 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/cli.test.mts +++ b/.github/scripts/dependabot-pr-reminder/cli.test.mts @@ -5,9 +5,7 @@ import { describe, expect, it } from 'vitest'; const execFileAsync = promisify(execFile); -const SCRIPT = fileURLToPath( - new URL('../../dependabot-pr-reminder/cli.mts', import.meta.url), -); +const SCRIPT = fileURLToPath(new URL('./cli.mts', import.meta.url)); describe('cli', () => { it('stops with a message when the required settings are missing', async () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.test.mts similarity index 93% rename from .github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts rename to .github/scripts/dependabot-pr-reminder/dependabot-title.test.mts index 8edf3f15..c61047d4 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/dependabot-title.test.mts +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.test.mts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { describeUpdate } from '../../dependabot-pr-reminder/dependabot-title.mts'; +import { describeUpdate } from './dependabot-title.mts'; describe('dependabot-title', () => { describe('describeUpdate', () => { diff --git a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts b/.github/scripts/dependabot-pr-reminder/fixtures.mts similarity index 73% rename from .github/scripts/tests/dependabot-pr-reminder/fixtures.mts rename to .github/scripts/dependabot-pr-reminder/fixtures.mts index 445fa28e..af9212e4 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/fixtures.mts +++ b/.github/scripts/dependabot-pr-reminder/fixtures.mts @@ -1,5 +1,5 @@ -import type { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; -import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; +import type { buildSlackPayload } from './slack-payload.mts'; +import type { PullRequest } from './types.mts'; export function pr(overrides: Partial<PullRequest> = {}): PullRequest { return { diff --git a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts b/.github/scripts/dependabot-pr-reminder/github-api.test.mts similarity index 94% rename from .github/scripts/tests/dependabot-pr-reminder/github-api.test.mts rename to .github/scripts/dependabot-pr-reminder/github-api.test.mts index 3284d7fa..bd814d16 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/github-api.test.mts +++ b/.github/scripts/dependabot-pr-reminder/github-api.test.mts @@ -2,8 +2,8 @@ import type { Octokit } from 'octokit'; import { describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; -import { fetchDependabotPullRequests } from '../../dependabot-pr-reminder/github-api.mts'; -import type { PullRequest } from '../../dependabot-pr-reminder/types.mts'; +import { fetchDependabotPullRequests } from './github-api.mts'; +import type { PullRequest } from './types.mts'; type Node = { number: number; diff --git a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.test.mts similarity index 98% rename from .github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts rename to .github/scripts/dependabot-pr-reminder/slack-payload.test.mts index f55197a6..8ea75da0 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/slack-payload.test.mts +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.test.mts @@ -1,11 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { buildSlackPayload } from '../../dependabot-pr-reminder/slack-payload.mts'; -import type { - PullRequest, - PullRequests, -} from '../../dependabot-pr-reminder/types.mts'; import { pr, sectionText } from './fixtures.mts'; +import { buildSlackPayload } from './slack-payload.mts'; +import type { PullRequest, PullRequests } from './types.mts'; const options = { maintainerTeam: 'platform', repository: 'MetaMask/example' }; diff --git a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts b/.github/scripts/dependabot-pr-reminder/teams.test.mts similarity index 91% rename from .github/scripts/tests/dependabot-pr-reminder/teams.test.mts rename to .github/scripts/dependabot-pr-reminder/teams.test.mts index 6884364d..779d9e32 100644 --- a/.github/scripts/tests/dependabot-pr-reminder/teams.test.mts +++ b/.github/scripts/dependabot-pr-reminder/teams.test.mts @@ -1,9 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { - parseOwnerTeams, - parseSharedTeamThreshold, -} from '../../dependabot-pr-reminder/teams.mts'; +import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; describe('teams', () => { describe('parseOwnerTeams', () => { diff --git a/vitest.config.mts b/vitest.config.mts index 47085782..1bcd298a 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -42,7 +42,7 @@ export default defineConfig({ provider: 'v8', include: ['src/**/*.ts', '.github/**/*.{js,mjs,mts,ts}'], - exclude: ['**/*.test.*', '.github/scripts/tests/**'], + exclude: ['**/*.test.*', '**/fixtures.mts', '.github/scripts/tests/**'], reporter: ['text', 'html', 'json-summary'], reportsDirectory: 'coverage',