Repository navigation
ci: require a Team Mobile approval unless a member wrote a low-risk change #777
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import fs from 'node:fs'; | ||
| import { fileURLToPath } from 'node:url'; | ||
|
|
||
| import { codeOwnerApproval } from './code-owner-approval.mjs'; | ||
| import { client, paged } from './github.mjs'; | ||
|
|
||
| const TEAM_FILE = new URL('../team-mobile', import.meta.url); | ||
| const CODERABBIT = 'coderabbitai[bot]'; | ||
| const HIGH_RISK = new Set(['high', 'critical']); | ||
|
|
||
| function parseTeam(text) { | ||
| return text | ||
| .split('\n') | ||
| .map(line => line.replace(/#.*$/, '').trim()) | ||
| .filter(line => line !== ''); | ||
| } | ||
|
|
||
| // CodeRabbit's summary comment carries its merge risk for the commit it last reviewed, and rewrites it after each review. | ||
| function ratedHighRisk(comments, head) { | ||
| return comments.some(comment => { | ||
| if (comment.user?.login !== CODERABBIT) { | ||
| return false; | ||
| } | ||
| const body = comment.body ?? ''; | ||
| const covered = /<!-- final_review_risk_coverage:(\{.*?\}) -->/.exec(body)?.[1]; | ||
| const level = /<!-- final_review_risk_label\s*\*\*Merge Risk:\*\*\s*\*\*[^A-Za-z]*([A-Za-z]+)\*\*/.exec(body)?.[1]; | ||
| return covered !== undefined && level !== undefined && JSON.parse(covered).coveredCommitId === head && HIGH_RISK.has(level.toLowerCase()); | ||
| }); | ||
| } | ||
|
|
||
| async function teamReviewRequest({ fetch, api, token, repo, number, team }) { | ||
| const get = client({ fetch, api, token, repo }); | ||
| const pull = await get(`/pulls/${number}`); | ||
| if (pull.state !== 'open' || pull.draft) { | ||
| return 'The pull request is closed or a draft.'; | ||
| } | ||
| const author = pull.user.login; | ||
| const check = await codeOwnerApproval({ fetch, api, token, repo, number, author, baseRef: pull.base.ref }); | ||
| if (check.pass) { | ||
| return `No review request needed. ${check.message}`; | ||
| } | ||
| if (check.reason === 'coderabbit' && !ratedHighRisk(await paged(get, `/issues/${number}/comments`), pull.head.sha)) { | ||
| return 'Waiting on CodeRabbit, which hasn\'t rated this commit high or critical risk.'; | ||
| } | ||
| const asked = new Set([author, ...pull.requested_reviewers.map(user => user.login)]); | ||
| for (const review of await paged(get, `/pulls/${number}/reviews`)) { | ||
| asked.add(review.user?.login); | ||
| } | ||
| const reviewers = team.filter(login => !asked.has(login)); | ||
| if (reviewers.length === 0) { | ||
| return 'Every Team Mobile member is already requested or has reviewed.'; | ||
| } | ||
| await get(`/pulls/${number}/requested_reviewers`, { method: 'POST', body: { reviewers } }); | ||
| const why = check.reason === 'coderabbit' ? 'CodeRabbit rated this commit high or critical risk.' : check.message; | ||
| return `Requested ${reviewers.join(', ')}. ${why}`; | ||
| } | ||
|
|
||
| async function main(env, { fetch = globalThis.fetch, out = process.stdout, teamText = fs.readFileSync(TEAM_FILE, 'utf8') } = {}) { | ||
| const missing = ['GITHUB_REPOSITORY', 'GITHUB_TOKEN', 'PR_NUMBER'].filter(name => !env[name]); | ||
| if (missing.length > 0) { | ||
| throw new Error(`missing ${missing.join(', ')}`); | ||
| } | ||
| const message = await teamReviewRequest({ | ||
| fetch, | ||
| api: env.GITHUB_API_URL || 'https://api.github.com', | ||
| token: env.GITHUB_TOKEN, | ||
| repo: env.GITHUB_REPOSITORY, | ||
| number: env.PR_NUMBER, | ||
| team: parseTeam(teamText), | ||
| }); | ||
| out.write(`${message}\n`); | ||
| } | ||
|
|
||
| export { main, parseTeam, ratedHighRisk }; | ||
|
|
||
| if (process.argv[1] !== undefined && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) { | ||
| try { | ||
| await main(process.env); | ||
| } catch (error) { | ||
| process.stderr.write(`${error.message}\n`); | ||
| process.exitCode = 1; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import fs from 'node:fs'; | ||
| import { describe, it } from 'node:test'; | ||
|
|
||
| import { main, parseTeam, ratedHighRisk } from './team-review-request.mjs'; | ||
|
|
||
| const REPO = 'clerk/clerk-ios'; | ||
| const API = 'https://api.github.test'; | ||
| const HEAD = 'c14cacc2763d2dfc271d9c286b09376a90c5b9ff'; | ||
| const TEAM = '# Team Mobile\nmikepitre\nseanperez29\nswolfand\nwobsoriano\n'; | ||
| const ROLES = { mikepitre: 'admin', seanperez29: 'admin', swolfand: 'maintain', wobsoriano: 'maintain', 'outside-dev': 'write' }; | ||
|
|
||
| // The shape CodeRabbit writes into its summary comment. | ||
| const riskComment = (level, commit = HEAD) => ({ | ||
| user: { login: 'coderabbitai[bot]' }, | ||
| body: `<!-- final_review_risk_start -->\n<!-- final_review_risk_label\n**Merge Risk:** **🔴 ${level}** · up to \`${commit.slice(0, 5)}\`\n-->\n<!-- final_review_risk_coverage:{"sourceCommitId":"${commit}","coveredCommitId":"${commit}","kind":"reviewed"} -->\n<!-- final_review_risk_end -->`, | ||
| }); | ||
| const review = (login, state) => ({ user: { login }, state }); | ||
|
|
||
| function fakeGitHub({ author = 'outside-dev', draft = false, state = 'open', files = [{ filename: 'Sources/ClerkKit/Clerk.swift' }], pending = [], reviews = [], comments = [] }) { | ||
| const requested = []; | ||
| const reply = body => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }); | ||
| const notFound = { ok: false, status: 404, json: async () => ({}), text: async () => 'Not Found' }; | ||
| const fetch = async (url, { method = 'GET', body }) => { | ||
| const { pathname, searchParams } = new URL(url); | ||
| const path = pathname.replace(`/repos/${REPO}`, ''); | ||
| if (method === 'POST' && path === '/pulls/7/requested_reviewers') { | ||
| requested.push(...JSON.parse(body).reviewers); | ||
| return reply({}); | ||
| } | ||
| if (path === '/pulls/7') { | ||
| return reply({ state, draft, user: { login: author }, head: { sha: HEAD }, base: { ref: 'main' }, changed_files: files.length, requested_reviewers: pending.map(login => ({ login })) }); | ||
| } | ||
| if (path === '/contents/.github/protected-paths') { | ||
| return reply({ content: Buffer.from('/.github/workflows/\n').toString('base64') }); | ||
| } | ||
| const lists = { '/pulls/7/files': files, '/pulls/7/reviews': reviews, '/issues/7/comments': comments }; | ||
| if (path in lists) { | ||
| const page = Number(searchParams.get('page')); | ||
| return reply(lists[path].slice((page - 1) * 100, page * 100)); | ||
| } | ||
| const match = /^\/collaborators\/([^/]+)\/permission$/.exec(path); | ||
| if (match) { | ||
| return match[1] in ROLES ? reply({ role_name: ROLES[match[1]] }) : notFound; | ||
| } | ||
| throw new Error(`unexpected ${method} ${path}`); | ||
| }; | ||
| return { fetch, requested }; | ||
| } | ||
|
|
||
| async function run(github) { | ||
| const { fetch, requested } = fakeGitHub(github); | ||
| const lines = []; | ||
| await main( | ||
| { GITHUB_API_URL: API, GITHUB_REPOSITORY: REPO, GITHUB_TOKEN: 'test-token', PR_NUMBER: '7' }, | ||
| { fetch, out: { write: line => lines.push(line) }, teamText: TEAM }, | ||
| ); | ||
| return { requested, output: lines.join('') }; | ||
| } | ||
|
|
||
| describe('ratedHighRisk', () => { | ||
| it('reads a high or critical rating for the head commit', () => { | ||
| assert.equal(ratedHighRisk([riskComment('High')], HEAD), true); | ||
| assert.equal(ratedHighRisk([riskComment('Critical')], HEAD), true); | ||
| }); | ||
|
|
||
| it('ignores a lower rating, a rating of an older commit, and the same text from someone else', () => { | ||
| assert.equal(ratedHighRisk([riskComment('Moderate')], HEAD), false); | ||
| assert.equal(ratedHighRisk([riskComment('High', 'e225ce56d448093f7910a36cf47bcc9a664e04d0')], HEAD), false); | ||
| assert.equal(ratedHighRisk([{ ...riskComment('High'), user: { login: 'outside-dev' } }], HEAD), false); | ||
| }); | ||
| }); | ||
|
|
||
| describe('team review request', () => { | ||
| it('lists GitHub logins in the committed team file', () => { | ||
| const team = parseTeam(fs.readFileSync(new URL('../team-mobile', import.meta.url), 'utf8')); | ||
| assert.ok(team.length > 0); | ||
| assert.ok(team.every(login => /^[A-Za-z0-9-]+$/.test(login))); | ||
| }); | ||
|
|
||
| it('requests nobody for a Team Mobile author on ordinary files while CodeRabbit reviews', async () => { | ||
| const { requested, output } = await run({ author: 'swolfand' }); | ||
| assert.deepEqual(requested, []); | ||
| assert.match(output, /Waiting on CodeRabbit/); | ||
| }); | ||
|
|
||
| it('requests the other members when CodeRabbit rates a Team Mobile author\'s commit high risk', async () => { | ||
| const { requested, output } = await run({ author: 'swolfand', comments: [riskComment('High')] }); | ||
| assert.deepEqual(requested, ['mikepitre', 'seanperez29', 'wobsoriano']); | ||
| assert.match(output, /CodeRabbit rated this commit high or critical risk/); | ||
| }); | ||
|
|
||
| it('requests the other members when a Team Mobile author changes a protected file', async () => { | ||
| const { requested } = await run({ author: 'mikepitre', files: [{ filename: '.github/workflows/pr-ci.yml' }] }); | ||
| assert.deepEqual(requested, ['seanperez29', 'swolfand', 'wobsoriano']); | ||
| }); | ||
|
|
||
| it('requests Team Mobile for an author with write access, a fork contributor and a bot', async () => { | ||
| for (const author of ['outside-dev', 'fork-contributor', 'dependabot[bot]']) { | ||
| const { requested } = await run({ author }); | ||
| assert.deepEqual(requested, ['mikepitre', 'seanperez29', 'swolfand', 'wobsoriano']); | ||
| } | ||
| }); | ||
|
|
||
| it('skips members who are already requested or have reviewed', async () => { | ||
| const { requested } = await run({ pending: ['mikepitre'], reviews: [review('swolfand', 'COMMENTED')] }); | ||
| assert.deepEqual(requested, ['seanperez29', 'wobsoriano']); | ||
| }); | ||
|
|
||
| it('requests nobody once Team Mobile approved', async () => { | ||
| const { requested } = await run({ reviews: [review('wobsoriano', 'APPROVED')] }); | ||
| assert.deepEqual(requested, []); | ||
| }); | ||
|
|
||
| it('skips drafts and closed pull requests', async () => { | ||
| for (const github of [{ draft: true }, { state: 'closed' }]) { | ||
| const { requested } = await run(github); | ||
| assert.deepEqual(requested, []); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # GitHub logins that Team review request asks to review a pull request from someone without maintain or admin access. | ||
| # Keep this in step with the @clerk/team-mobile team. | ||
| mikepitre | ||
| seanperez29 | ||
| swolfand | ||
| wobsoriano |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.