Skip to content

Commit 4644149

Browse files
committed
Create React sync automatically
1 parent 53cf8e2 commit 4644149

File tree

2 files changed

+163
-20
lines changed

2 files changed

+163
-20
lines changed

.github/workflows/update_react.yml

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ on:
1515

1616
env:
1717
NODE_LTS_VERSION: 20
18+
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
1819

1920
jobs:
2021
create-pull-request:
@@ -27,6 +28,11 @@ jobs:
2728
# See: https://docs.github.com/en/actions/security-guides/automatic-token-authentication#using-the-github_token-in-a-workflow
2829
token: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
2930

31+
- name: Set Git author
32+
run: |
33+
git config user.name "vercel-release-bot"
34+
git config user.email "[email protected]"
35+
3036
- name: Setup node
3137
uses: actions/setup-node@v4
3238
with:
@@ -37,4 +43,11 @@ jobs:
3743

3844
- name: Install dependencies
3945
shell: bash
40-
run: pnpm i
46+
# Just need scripts/ but those dependencies are listed in the workspace root.
47+
run: pnpm install --filter .
48+
49+
- name: Create Pull Request
50+
shell: bash
51+
run: pnpm sync-react --actor "${{ github.actor }}" --version "${{ inputs.version }}" --create-pull
52+
env:
53+
GITHUB_TOKEN: ${{ secrets.GH_TOKEN_PULL_REQUESTS }}

scripts/sync-react.js

Lines changed: 149 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,17 @@ const path = require('path')
44
const fsp = require('fs/promises')
55
const process = require('process')
66
const execa = require('execa')
7+
const { Octokit } = require('octokit')
78
const yargs = require('yargs')
89

910
/** @type {any} */
1011
const fetch = require('node-fetch')
1112

13+
const repoOwner = 'vercel'
14+
const repoName = 'next.js'
15+
const pullRequestLabels = ['type: react-sync']
16+
const pullRequestReviewers = ['eps1lon']
17+
1218
const filesReferencingReactPeerDependencyVersion = [
1319
'run-tests.js',
1420
'packages/create-next-app/templates/index.ts',
@@ -155,12 +161,49 @@ async function main() {
155161
const errors = []
156162
const argv = await yargs(process.argv.slice(2))
157163
.version(false)
164+
.options('actor', {
165+
type: 'string',
166+
description:
167+
'Required with `--create-pull`. The actor (GitHub username) that runs this script. Will be used for notifications but not commit attribution.',
168+
})
169+
.options('create-pull', {
170+
default: false,
171+
type: 'boolean',
172+
description: 'Create a Pull Request in vercel/next.js',
173+
})
174+
.options('commit', {
175+
default: true,
176+
type: 'boolean',
177+
description: 'Will not create any commit',
178+
})
158179
.options('install', { default: true, type: 'boolean' })
159180
.options('version', { default: null, type: 'string' }).argv
160-
const { install, version } = argv
181+
const { actor, createPull, commit, install, version } = argv
182+
183+
async function commitEverything(message) {
184+
await execa('git', ['add', '-A'])
185+
await execa('git', ['commit', '--message', message, '--no-verify'])
186+
}
187+
188+
if (createPull && !actor) {
189+
throw new Error(
190+
`Pull Request cannot be created without a GitHub actor (received '${String(actor)}'). ` +
191+
'Pass an actor via `--actor "some-actor"`.'
192+
)
193+
}
194+
const githubToken = process.env.GITHUB_TOKEN
195+
if (createPull && !githubToken) {
196+
throw new Error(
197+
`Environment variable 'GITHUB_TOKEN' not specified but required when --create-pull is specified.`
198+
)
199+
}
161200

162201
let newVersionStr = version
163-
if (newVersionStr === null) {
202+
if (
203+
newVersionStr === null ||
204+
// TODO: Fork arguments in GitHub workflow to ensure `--version ""` is considered a mistake
205+
newVersionStr === ''
206+
) {
164207
const { stdout, stderr } = await execa(
165208
'npm',
166209
['view', 'react@canary', 'version'],
@@ -174,6 +217,9 @@ async function main() {
174217
throw new Error('Failed to read latest React canary version from npm.')
175218
}
176219
newVersionStr = stdout.trim()
220+
console.log(
221+
`--version was not provided. Using react@canary: ${newVersionStr}`
222+
)
177223
}
178224

179225
const newVersionInfo = extractInfoFromReactVersion(newVersionStr)
@@ -188,6 +234,32 @@ Or, run this command with no arguments to use the most recently published versio
188234
)
189235
}
190236
const { sha: newSha, dateString: newDateString } = newVersionInfo
237+
238+
const branchName = `update/react/${newSha}-${newDateString}`
239+
if (createPull) {
240+
const { exitCode, all, command } = await execa('git', [
241+
'ls-remote',
242+
'--heads',
243+
'origin',
244+
`refs/heads/${branchName}`,
245+
'--exit-code',
246+
])
247+
248+
if (exitCode === 2) {
249+
console.log(
250+
`No sync in progress in branch '${branchName}' according to '${command}'. Starting a new one.`
251+
)
252+
} else if (exitCode === 0) {
253+
throw new Error(
254+
`An existing sync already exists in branch '${branchName}'. Delete the branch to start a new sync.`
255+
)
256+
} else {
257+
throw new Error(
258+
`Failed to check if the branch already existed:\n${command}: ${all}`
259+
)
260+
}
261+
}
262+
191263
const rootManifest = JSON.parse(
192264
await fsp.readFile(path.join(cwd, 'package.json'), 'utf-8')
193265
)
@@ -203,13 +275,19 @@ Or, run this command with no arguments to use the most recently published versio
203275
noInstall: !install,
204276
channel: 'experimental',
205277
})
278+
if (commit) {
279+
await commitEverything('Update `react@experimental`')
280+
}
206281
await sync({
207282
newDateString,
208283
newSha,
209284
newVersionStr,
210285
noInstall: !install,
211286
channel: 'rc',
212287
})
288+
if (commit) {
289+
await commitEverything('Update `react@rc`')
290+
}
213291

214292
const baseVersionInfo = extractInfoFromReactVersion(baseVersionStr)
215293
if (!baseVersionInfo) {
@@ -269,13 +347,22 @@ Or, run this command with no arguments to use the most recently published versio
269347
)
270348
}
271349

350+
if (commit) {
351+
await commitEverything('Updated peer dependency references')
352+
}
353+
272354
// Install the updated dependencies and build the vendored React files.
273355
if (!install) {
274356
console.log('Skipping install step because --no-install flag was passed.\n')
275357
} else {
276358
console.log('Installing dependencies...\n')
277359

278-
const installSubprocess = execa('pnpm', ['install'])
360+
const installSubprocess = execa('pnpm', [
361+
'install',
362+
// Pnpm freezes the lockfile by default in CI.
363+
// However, we just changed versions so the lockfile is expected to be changed.
364+
'--no-frozen-lockfile',
365+
])
279366
if (installSubprocess.stdout) {
280367
installSubprocess.stdout.pipe(process.stdout)
281368
}
@@ -286,6 +373,10 @@ Or, run this command with no arguments to use the most recently published versio
286373
throw new Error('Failed to install updated dependencies.')
287374
}
288375

376+
if (commit) {
377+
await commitEverything('Update lockfile')
378+
}
379+
289380
console.log('Building vendored React files...\n')
290381
const nccSubprocess = execa('pnpm', ['ncc-compiled'], {
291382
cwd: path.join(cwd, 'packages', 'next'),
@@ -300,34 +391,29 @@ Or, run this command with no arguments to use the most recently published versio
300391
throw new Error('Failed to run ncc.')
301392
}
302393

394+
if (commit) {
395+
await commitEverything('ncc-compiled')
396+
}
397+
303398
// Print extra newline after ncc output
304399
console.log()
305400
}
306401

307-
console.log(
308-
`**breaking change for canary users: Bumps peer dependency of React from \`${baseVersionStr}\` to \`${newVersionStr}\`**`
309-
)
402+
let prDescription = `**breaking change for canary users: Bumps peer dependency of React from \`${baseVersionStr}\` to \`${newVersionStr}\`**\n\n`
310403

311404
// Fetch the changelog from GitHub and print it to the console.
312-
console.log(
313-
`[diff facebook/react@${baseSha}...${newSha}](https://github.com/facebook/react/compare/${baseSha}...${newSha})`
314-
)
405+
prDescription += `[diff facebook/react@${baseSha}...${newSha}](https://github.com/facebook/react/compare/${baseSha}...${newSha})\n\n`
315406
try {
316407
const changelog = await getChangelogFromGitHub(baseSha, newSha)
317408
if (changelog === null) {
318-
console.log(
319-
`GitHub reported no changes between ${baseSha} and ${newSha}.`
320-
)
409+
prDescription += `GitHub reported no changes between ${baseSha} and ${newSha}.`
321410
} else {
322-
console.log(
323-
`<details>\n<summary>React upstream changes</summary>\n\n${changelog}\n\n</details>`
324-
)
411+
prDescription += `<details>\n<summary>React upstream changes</summary>\n\n${changelog}\n\n</details>`
325412
}
326413
} catch (error) {
327414
console.error(error)
328-
console.log(
415+
prDescription +=
329416
'\nFailed to fetch changelog from GitHub. Changes were applied, anyway.\n'
330-
)
331417
}
332418

333419
if (!install) {
@@ -343,13 +429,57 @@ Or run this command again without the --no-install flag to do both automatically
343429
)
344430
}
345431

346-
await fsp.writeFile(path.join(cwd, '.github/.react-version'), newVersionStr)
347-
348432
if (errors.length) {
349433
// eslint-disable-next-line no-undef -- Defined in Node.js
350434
throw new AggregateError(errors)
351435
}
352436

437+
if (createPull) {
438+
const octokit = new Octokit({ auth: githubToken })
439+
const prTitle = `Upgrade React from \`${baseSha}-${baseDateString}\` to \`${newSha}-${newDateString}\``
440+
441+
await execa('git', ['checkout', '-b', branchName])
442+
// We didn't commit intermediate steps yet so now we need to commit to create a PR.
443+
if (!commit) {
444+
commitEverything(prTitle)
445+
}
446+
await execa('git', ['push', 'origin', branchName])
447+
const pullRequest = await octokit.rest.pulls.create({
448+
owner: repoOwner,
449+
repo: repoName,
450+
head: branchName,
451+
base: 'canary',
452+
draft: false,
453+
title: prTitle,
454+
body: prDescription,
455+
})
456+
console.log('Created pull request %s', pullRequest.data.html_url)
457+
458+
await Promise.all([
459+
actor
460+
? octokit.rest.issues.addAssignees({
461+
owner: repoOwner,
462+
repo: repoName,
463+
issue_number: pullRequest.data.number,
464+
assignees: [actor],
465+
})
466+
: Promise.resolve(),
467+
octokit.rest.pulls.requestReviewers({
468+
owner: repoOwner,
469+
repo: repoName,
470+
pull_number: pullRequest.data.number,
471+
reviewers: pullRequestReviewers,
472+
}),
473+
octokit.rest.issues.addLabels({
474+
owner: repoOwner,
475+
repo: repoName,
476+
issue_number: pullRequest.data.number,
477+
labels: pullRequestLabels,
478+
}),
479+
])
480+
}
481+
482+
console.log(prDescription)
353483
console.log(
354484
`Successfully updated React from \`${baseSha}-${baseDateString}\` to \`${newSha}-${newDateString}\``
355485
)

0 commit comments

Comments
 (0)