diff --git a/.github/actions/remind-dependabot-prs/action.yml b/.github/actions/remind-dependabot-prs/action.yml new file mode 100644 index 00000000..9f6e8aaf --- /dev/null +++ b/.github/actions/remind-dependabot-prs/action.yml @@ -0,0 +1,72 @@ +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 the pull requests of this 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: '' + 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 maintainer team.' + required: false + default: '5' + guide-url: + 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: + 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.18+ to run directly. + - name: Set up Node + uses: actions/setup-node@v6 + 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 + env: + GITHUB_REPOSITORY: ${{ github.repository }} + GH_TOKEN: ${{ inputs.github-token }} + PLANNING_TOKEN: ${{ inputs.planning-token }} + OWNER_TEAMS: ${{ inputs.owner-teams }} + MAINTAINER_TEAM: ${{ inputs.maintainer-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/classify-pull-requests.mts b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts new file mode 100644 index 00000000..f4f39f8b --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.mts @@ -0,0 +1,53 @@ +import { normalizeTeamSlug } from '../shared/topology.mts'; +import type { PullRequest, PullRequests } from './types.mts'; + +/** + * Groups PRs by the teams still requested as reviewers. A PR with more than + * `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 owners a PR can have and still be owned by them. + * @returns The PRs grouped by owner. + */ +export function classifyPullRequests( + pullRequests: PullRequest[], + { + ownerTeams, + sharedTeamThreshold, + }: { ownerTeams?: string[] | undefined; sharedTeamThreshold: number }, +): PullRequests { + const allowedOwners = ownerTeams?.map(normalizeTeamSlug); + const grouped: PullRequests = { + byOwner: new Map(), + sharedByManyOwners: [], + withNoOwners: [], + }; + + for (const pullRequest of pullRequests) { + const requestedOwners = new Set( + pullRequest.requestedTeams + .map(normalizeTeamSlug) + .filter((team) => !allowedOwners || allowedOwners.includes(team)), + ); + + 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 { + grouped.byOwner.set(owner, [pullRequest]); + } + } + } else { + grouped.withNoOwners.push(pullRequest); + } + } + + return grouped; +} diff --git a/.github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts new file mode 100644 index 00000000..9cc23693 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/classify-pull-requests.test.mts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; + +import { classifyPullRequests } from './classify-pull-requests.mts'; +import { pr } from './fixtures.mts'; + +const options = { sharedTeamThreshold: 3 }; + +describe('classify-pull-requests', () => { + describe('classifyPullRequests', () => { + it('lists a PR under each requested team', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b'] }); + + const { byOwner } = classifyPullRequests([pullRequest], options); + + expect(byOwner).toStrictEqual( + new Map([ + ['a', [pullRequest]], + ['b', [pullRequest]], + ]), + ); + }); + + it('puts a PR with no team with the maintainer team', () => { + const pullRequest = pr(); + + const { withNoOwners } = classifyPullRequests([pullRequest], options); + + expect(withNoOwners).toStrictEqual([pullRequest]); + }); + + it('keeps a PR with exactly the threshold under its teams', () => { + const pullRequest = pr({ requestedTeams: ['a', 'b', 'c'] }); + + const { byOwner, sharedByManyOwners } = classifyPullRequests( + [pullRequest], + options, + ); + + 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 { byOwner, sharedByManyOwners } = classifyPullRequests( + [pullRequest], + options, + ); + + expect(byOwner.size).toBe(0); + expect(sharedByManyOwners).toStrictEqual([pullRequest]); + }); + + it('only counts the owner teams, ignoring case and repeats', () => { + const pullRequest = pr({ + requestedTeams: ['a', 'A', 'b', 'x', 'y', 'z'], + }); + + const { byOwner, sharedByManyOwners } = classifyPullRequests( + [pullRequest], + { + ...options, + ownerTeams: ['@MetaMask/a', 'b'], + }, + ); + + 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 { byOwner, withNoOwners } = classifyPullRequests([pullRequest], { + ...options, + ownerTeams: ['extension-platform'], + }); + + expect(byOwner.size).toBe(0); + expect(withNoOwners).toStrictEqual([pullRequest]); + }); + + it('lists a team named like an object property', () => { + const pullRequest = pr({ requestedTeams: ['constructor'] }); + + const { byOwner } = classifyPullRequests([pullRequest], options); + + expect(byOwner.get('constructor')).toStrictEqual([pullRequest]); + }); + }); +}); diff --git a/.github/scripts/dependabot-pr-reminder/cli.mts b/.github/scripts/dependabot-pr-reminder/cli.mts new file mode 100644 index 00000000..eab91a51 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/cli.mts @@ -0,0 +1,79 @@ +import { appendFile, writeFile } from 'node:fs/promises'; +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-pull-requests.mts'; +import { fetchDependabotPullRequests } from './github-api.mts'; +import { buildSlackPayload } from './slack-payload.mts'; +import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; + +/** + * 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 { + const environment = process.env; + 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 || + !githubToken || + !planningToken || + !outputPath + ) { + throw new Error( + 'GITHUB_REPOSITORY, MAINTAINER_TEAM, GH_TOKEN, PLANNING_TOKEN and GITHUB_OUTPUT are required', + ); + } + + 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'); + return; + } + + const grouped = classifyPullRequests(pullRequests, { + ownerTeams: parseOwnerTeams(environment.OWNER_TEAMS), + sharedTeamThreshold: + parseSharedTeamThreshold(environment.SHARED_TEAM_THRESHOLD) ?? 5, + }); + + let topology: Topology = {}; + try { + topology = await fetchTopology(createOctokit(planningToken)); + } catch (error) { + console.log( + `::warning::Could not read topology.json, posting without Slack tags: ${String(error)}`, + ); + } + + const payload = buildSlackPayload(grouped, topology, { + maintainerTeam, + repository, + guideUrl: environment.GUIDE_URL?.trim(), + note: environment.REMINDER_NOTE?.trim(), + }); + const payloadPath = path.join( + environment.RUNNER_TEMP ?? '.', + 'dependabot-reminder-payload.json', + ); + await writeFile(payloadPath, JSON.stringify(payload)); + await appendFile(outputPath, `has-prs=true\npayload-path=${payloadPath}\n`); +} + +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/cli.test.mts b/.github/scripts/dependabot-pr-reminder/cli.test.mts new file mode 100644 index 00000000..99906d07 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/cli.test.mts @@ -0,0 +1,20 @@ +import { execFile } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { describe, expect, it } from 'vitest'; + +const execFileAsync = promisify(execFile); + +const SCRIPT = fileURLToPath(new URL('./cli.mts', import.meta.url)); + +describe('cli', () => { + it('stops with a message when the required settings are missing', async () => { + const run = execFileAsync(process.execPath, [SCRIPT], { + env: { PATH: process.env.PATH }, + }); + + await expect(run).rejects.toMatchObject({ + stderr: expect.stringContaining('are required'), + }); + }); +}); 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..8839feb5 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.mts @@ -0,0 +1,39 @@ +import { escapeSlack } from '../shared/slack-blocks.mts'; + +/** + * 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.*)?$`, + 'iu', +); +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', +); + +const code = (value: string): string => + `\`${escapeSlack(value).replaceAll('`', "'")}\``; + +/** + * 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) { + return `${code(name)} ${escapeSlack(from)} → ${escapeSlack(to)}${scope?.includes('dev') ? ' (dev)' : ''}`; + } + + 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/dependabot-title.test.mts b/.github/scripts/dependabot-pr-reminder/dependabot-title.test.mts new file mode 100644 index 00000000..c61047d4 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/dependabot-title.test.mts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; + +import { describeUpdate } from './dependabot-title.mts'; + +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); + }); + + it.each(['Bump a and b', 'Something else entirely'])( + 'does not read %s', + (title) => { + const description = describeUpdate(title); + + expect(description).toBeUndefined(); + }, + ); + }); +}); diff --git a/.github/scripts/dependabot-pr-reminder/fixtures.mts b/.github/scripts/dependabot-pr-reminder/fixtures.mts new file mode 100644 index 00000000..af9212e4 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/fixtures.mts @@ -0,0 +1,19 @@ +import type { buildSlackPayload } from './slack-payload.mts'; +import type { PullRequest } from './types.mts'; + +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: [], + ciState: 'unknown', + ...overrides, + }; +} + +type Block = ReturnType['blocks'][number]; + +export function sectionText(block: Block | undefined): string { + return block && 'text' in block ? block.text.text : ''; +} 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..c418e646 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/github-api.mts @@ -0,0 +1,95 @@ +import type { Octokit } from 'octokit'; + +import type { PullRequest } from './types.mts'; + +/** + * 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: { + 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 } }[]; + }; + }[]; + }; +}; + +/** One query returns everything needed, so a run costs one request per 100 PRs. */ +const QUERY = ` +query($searchQuery: String!, $cursor: String) { + search(query: $searchQuery, type: ISSUE, first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + ... on PullRequest { + number + title + url + reviewRequests(first: 100) { + nodes { requestedReviewer { __typename ... on Team { slug } } } + } + commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } + } + } + } +}`; + +const CI_STATES = { + SUCCESS: 'passing', + FAILURE: 'failing', + ERROR: 'failing', + PENDING: 'pending', + EXPECTED: 'pending', +} as const satisfies Record; + +/** + * 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, +): Promise { + const { search } = await octokit.graphql.paginate(QUERY, { + searchQuery: `repo:${repository} is:pr is:open draft:false author:app/dependabot`, + }); + + return search.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/github-api.test.mts b/.github/scripts/dependabot-pr-reminder/github-api.test.mts new file mode 100644 index 00000000..bd814d16 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/github-api.test.mts @@ -0,0 +1,108 @@ +import type { Octokit } from 'octokit'; +import { describe, expect, it, vi } from 'vitest'; +import type { Mock } from 'vitest'; + +import { fetchDependabotPullRequests } from './github-api.mts'; +import type { PullRequest } from './types.mts'; + +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 { + return { + number: 7, + title: 'Bump foo', + url: 'https://github.com/MetaMask/example/pull/7', + reviewRequests: { nodes: [] }, + commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, + ...overrides, + }; +} + +type Paginate = (query: string, variables: object) => Promise; + +function octokitReturning(nodes: Node[]): { + octokit: Octokit; + paginate: Mock; +} { + const paginate = vi.fn().mockResolvedValue({ + search: { pageInfo: { hasNextPage: false, endCursor: null }, nodes }, + }); + return { octokit: { graphql: { paginate } } as unknown as Octokit, paginate }; +} + +async function fetchFrom(nodes: Node[]): Promise { + return await fetchDependabotPullRequests( + octokitReturning(nodes).octokit, + 'MetaMask/core', + ); +} + +describe('github-api', () => { + describe('fetchDependabotPullRequests', () => { + it('searches for open Dependabot PRs', async () => { + const { octokit, paginate } = octokitReturning([node()]); + + await fetchDependabotPullRequests(octokit, 'MetaMask/core'); + + expect(paginate.mock.calls[0]?.[1]).toStrictEqual({ + searchQuery: + 'repo:MetaMask/core is:pr is:open draft:false author:app/dependabot', + }); + }); + + it('maps a PR', async () => { + const pullRequests = await fetchFrom([node()]); + + expect(pullRequests[0]).toStrictEqual({ + number: 7, + 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 }, + ], + }, + }), + ]); + + 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 } }] } }), + ]); + + expect(pullRequests[0]?.ciState).toBe(ciState); + }); + }); +}); 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..904302c8 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.mts @@ -0,0 +1,380 @@ +import { + MAX_SECTION_LENGTH, + escapeAndTruncate, + escapeSlack, + section, +} from '../shared/slack-blocks.mts'; +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, PullRequests } from './types.mts'; + +/** + * 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'; + text: { type: 'plain_text'; text: string; emoji: true }; + } + | { type: 'context'; elements: { type: 'mrkdwn'; text: string }[] } + | { type: 'divider' }; + +const CI: Record< + PullRequest['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 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 MAX_TITLE_LENGTH = 200; + +const divider: ReminderBlock = { type: 'divider' }; + +const context = (text: string): ReminderBlock => ({ + type: 'context', + 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. + * + * @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[][] = []; + let length = 0; + for (const item of items) { + 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; + } + } + return chunks.map((chunk) => section(`${heading}\n${chunk.join('\n\n')}`)); +} + +/** + * Makes the function that tags teams. A handle in the text becomes a Slack + * mention, and teams without one stay plain. + * + * @param topology - The parsed `topology.json`, used for the Slack handles. + * @returns The `tags` function and the set of handles it mentioned so far. + */ +function createTagger(topology: Topology): { + tags: Tags; + mentions: Set; +} { + const mentions = new Set(); + 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 }; +} + +/** + * 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(); + const addOwner = (pullRequest: PullRequest, team: string): void => { + const entry = byNumber.get(pullRequest.number); + if (entry) { + entry.teams.push(team); + } else { + byNumber.set(pullRequest.number, { pullRequest, teams: [team] }); + } + }; + for (const [team, ownedPullRequests] of pullRequests.byOwner) { + for (const pullRequest of ownedPullRequests) { + addOwner(pullRequest, team); + } + } + for (const pullRequest of pullRequests.withNoOwners) { + addOwner(pullRequest, maintainerTeam); + } + return [...byNumber.values()]; +} + +/** + * 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; +} + +/** + * 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[] => + owned + .filter(({ pullRequest }) => states.includes(pullRequest.ciState)) + .map( + ({ pullRequest, teams }) => + `${formatPullRequest(pullRequest, withIcon)}${sharedTeams ? '' : `\n${tags(teams)}`}`, + ); + + return [ + packItems( + `*${CI.passing.icon} CI passing*`, + ownedItems(['passing'], false), + ), + packItems( + `*${CI.failing.icon} Needs a fix*`, + ownedItems(['failing'], false), + ), + packItems( + `*${CI.pending.icon} In progress*`, + ownedItems(['pending', 'unknown'], true), + ), + shared.length > 0 + ? packItems( + `*:busts_in_silhouette: Shared by many teams*\nCoordinated by ${tags([maintainerTeam])}`, + shared.map( + (pullRequest) => + `${formatPullRequest(pullRequest, true)} · ${pullRequest.requestedTeams.length} teams`, + ), + ) + : [], + ].filter((group) => group.length > 0); +} + +/** + * 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 text = [ + sharedTeams ? `${tags(sharedTeams)} ${noteText}` : noteText, + ...(guideUrl ? [link(guideUrl, 'Read the full guide')] : []), + ].join('\n'); + if (text.length > MAX_SECTION_LENGTH) { + throw new Error( + `The reminder note is too long with its team tags and guide link: ${text.length} characters, the limit is ${MAX_SECTION_LENGTH}`, + ); + } + 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( + ' ', + ), + blocks: [ + { + type: 'header', + text: { + type: 'plain_text', + text: ':dependabot: Open Dependabot pull requests', + emoji: true, + }, + }, + context( + [ + link(`https://github.com/${repository}`, escapeSlack(repository)), + `*${all.length}* open`, + ...countByCiState(all), + ].join(' · '), + ), + noteSection, + 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/slack-payload.test.mts b/.github/scripts/dependabot-pr-reminder/slack-payload.test.mts new file mode 100644 index 00000000..8ea75da0 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/slack-payload.test.mts @@ -0,0 +1,334 @@ +import { describe, expect, it } from 'vitest'; + +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' }; + +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' }, + }, +}; + +function grouped(parts: { + byOwner?: Record; + shared?: PullRequest[]; + withNoOwners?: PullRequest[]; +}): PullRequests { + return { + byOwner: new Map(Object.entries(parts.byOwner ?? {})), + sharedByManyOwners: parts.shared ?? [], + withNoOwners: parts.withNoOwners ?? [], + }; +} + +function build( + parts: Parameters[0], + extra = {}, +): ReturnType { + return buildSlackPayload(grouped(parts), topology, { + ...options, + ...extra, + }); +} + +// The blocks after the header, counts, note and first divider. +function groups(parts: Parameters[0]): string[] { + return build(parts) + .blocks.slice(4, -2) + .map((block) => sectionText(block) || '---'); +} + +describe('slack-payload', () => { + describe('buildSlackPayload', () => { + it('puts the header, counts and note above the groups and the legend below', () => { + const { blocks } = build({ + byOwner: { a: [pr({ ciState: 'failing' })] }, + }); + + const types = blocks.map(({ type }) => type); + + expect(types).toStrictEqual([ + 'header', + 'context', + 'section', + 'divider', + 'section', + 'divider', + 'context', + ]); + }); + + it('counts the open PRs by CI state', () => { + const { blocks } = build({ + byOwner: { + 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( + ' · *3* open · :white_check_mark: 1 passing · :x: 2 failing', + ); + }); + + it('links the guide under the note when there is one', () => { + const { blocks } = build( + { byOwner: { a: [pr()] } }, + { guideUrl: 'https://example.com/guide' }, + ); + + expect(sectionText(blocks[2])).toMatch( + /\n$/u, + ); + }); + + it('groups PRs by CI state, with the shared ones last', () => { + const headings = groups({ + byOwner: { + 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('shows the package, versions and teams of each PR', () => { + const [text] = groups({ + byOwner: { + 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 `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({ + byOwner: { + 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 maintainer team', () => { + const [text] = groups({ + withNoOwners: [pr({ number: 5, ciState: 'passing' })], + }); + + expect(text).toBe( + '*:white_check_mark: CI passing*\n `foo` 1.0.0 → 1.0.1\n@platform-team', + ); + }); + + it('shows shared PRs with their icon and team count, coordinated by the maintainer 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, + ); + }); + + it('shows an icon on each PR in the in progress group', () => { + const [text] = groups({ + byOwner: { + 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({ + byOwner: { a: [pr()], b: [pr()], plain: [pr()] }, + }); + + 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({ + byOwner: { a: [pr({ title: `Odd & ${'x'.repeat(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({ byOwner: { 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>'); + }); + + it('tags a team that owns every PR once at the top, not under each PR', () => { + const { blocks } = build({ + byOwner: { + 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({ + byOwner: { + 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({ + byOwner: { 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'); + }); + + it('uses the note it is given instead of the built in one', () => { + const { blocks } = build( + { byOwner: { 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({ byOwner: { 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( + { byOwner: { 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>', + ); + }); + + it('accepts a note that fits in one section', () => { + const act = (): unknown => + buildSlackPayload(grouped({ byOwner: { 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(grouped({ byOwner: { a: [pr()] } }), topology, { + ...options, + ...extra, + }); + + expect(act).toThrow('The reminder note is too long'); + }); + }); +}); diff --git a/.github/scripts/dependabot-pr-reminder/teams.mts b/.github/scripts/dependabot-pr-reminder/teams.mts new file mode 100644 index 00000000..2091f7ba --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/teams.mts @@ -0,0 +1,36 @@ +/** + * 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 { + const teams = (value ?? '') + .split(',') + .map((team) => team.trim()) + .filter(Boolean); + return teams.length > 0 ? teams : undefined; +} + +/** + * 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 { + 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/teams.test.mts b/.github/scripts/dependabot-pr-reminder/teams.test.mts new file mode 100644 index 00000000..779d9e32 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/teams.test.mts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; + +import { parseOwnerTeams, parseSharedTeamThreshold } from './teams.mts'; + +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); + + expect(threshold).toBeUndefined(); + }); + + it('parses a positive whole number', () => { + const threshold = parseSharedTeamThreshold(' 4 '); + + expect(threshold).toBe(4); + }); + + it.each(['0', '-1', '2.5', 'many'])('rejects %s', (value) => { + const parse = (): number | undefined => parseSharedTeamThreshold(value); + + expect(parse).toThrow('SHARED_TEAM_THRESHOLD'); + }); + }); +}); diff --git a/.github/scripts/dependabot-pr-reminder/types.mts b/.github/scripts/dependabot-pr-reminder/types.mts new file mode 100644 index 00000000..0e12c7a0 --- /dev/null +++ b/.github/scripts/dependabot-pr-reminder/types.mts @@ -0,0 +1,29 @@ +/** + * 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 = { + number: number; + title: string; + url: string; + requestedTeams: string[]; + ciState: 'passing' | 'failing' | 'pending' | 'unknown'; +}; + +/** + * The PRs to remind about, grouped by who owns 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 PullRequests = { + byOwner: Map<string, PullRequest[]>; + sharedByManyOwners: PullRequest[]; + withNoOwners: PullRequest[]; +}; diff --git a/.github/workflows/remind-dependabot-prs.yml b/.github/workflows/remind-dependabot-prs.yml new file mode 100644 index 00000000..434b504a --- /dev/null +++ b/.github/workflows/remind-dependabot-prs.yml @@ -0,0 +1,86 @@ +name: Remind Dependabot PRs + +# Posts a Slack message of open Dependabot PRs, grouped by owning team. +# +# 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. +# +# The `@v1` refs below only resolve after a release. To try a branch first, +# point them at it. + +on: + workflow_call: + inputs: + owner-teams: + required: false + type: string + default: '' + description: 'Comma-separated team slugs that own the calling repository' + maintainer-team: + required: true + type: string + 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 maintainer team' + guide-url: + required: false + 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 + description: 'Slack incoming webhook URL' + +jobs: + remind: + name: Remind Dependabot PRs + runs-on: ubuntu-latest + environment: default-branch + permissions: + contents: read + pull-requests: read + checks: read + statuses: 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 }} + maintainer-team: ${{ inputs.maintainer-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' + uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1 + with: + webhook: ${{ secrets.slack-webhook-url }} + webhook-type: incoming-webhook + errors: true + payload-file-path: ${{ steps.remind.outputs.payload-path }} diff --git a/vitest.config.mts b/vitest.config.mts index 39796f7f..1bcd298a 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -42,17 +42,17 @@ 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', 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.74, + functions: 53.86, + lines: 43.24, + statements: 43.45, }, }, },