Unverified Commit d111e258 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[cd] Use pnpm to manage the version (#99041)

lerna's last job was bumping the version, and it needed a dependency
graph of exact pins to do it. Internal dependencies now use the
`workspace:*` protocol instead, which pnpm substitutes for the concrete
version when packing, so published manifests are unchanged.

`workspace:*` resolves to the same bare exact version that was pinned
before.
    
That leaves the bump itself, which `scripts/version-bump.js` now does:
write one version field per package, commit, tag. It stays small because
every package is versioned in lockstep and releases always bumped all of
them (`--force-publish`), so there is no changed-detection to
reimplement.
    
`packages/next/package.json` replaces `lerna.json` as the version source
of truth.
The release branch gate moves to `scripts/release-branches.json`.
    
Three things fall out:
    
- `normalize-version-bump.js` no longer has to normalize internal
dependency specs, since `workspace:*` carries no version. Those specs
also stop contributing to turbo input hashes.
- `set-preview-version.js` no longer needs to check out a branch first.
That only existed because `lerna version` refused to run on a detached
HEAD.
- no more lockfile regeneration after a release which means we can reuse
n_m caches
    

`create-preview-tarballs.js` keeps `npm pack`: it rewrites internal
dependencies
to tarball URLs rather than versions, because that is what preview
installs need, so pnpm's substitution would be the wrong transform. It
now throws if any `workspace:` specifier survives that rewrite.


## test plan

```
$ git switch -c scratch/release-dry-run sebbie/remove-lerna
$ node scripts/start-release.js --release-type canary --dry-run
Dry run: keeping commits locally, skipping git push and GitHub release creation
Running release-canary...
Bumping 16.4.0-canary.39 -> 16.4.0-canary.40
Updated 20 packages
[...]
Creating GitHub release v16.4.0-canary.40 (changelog range v16.4.0-canary.39..v16.4.0-canary.40, 30 commits)
[dry-run] GitHub API POST /repos/vercel/next.js/releases {"tag_name":"v16.4.0-canary.40","name":"v16.4.0-canary.40","body":"### Misc Changes\n\n- Remove lerna\n- [PPF] Implement `unstable_ensureStatic = \"shell\" | \"prefetch\"` (#98191)\n- [PPF] Valid… (1939 chars)","prerelease":true,"draft":true}
Created draft prerelease v16.4.0-canary.40
Release process is finished
$ git show HEAD --oneline
c198fa45fae (HEAD -> scratch/release-dry-run, tag: v16.4.0-canary.40) v16.4.0-canary.40
$ node scripts/publish-release.js --dry-run
$ git diff
diff --git a/packages/next/package.json b/packages/next/package.json
[...]
   "optionalDependencies": {
-    "sharp": "^0.35.4"
+    "sharp": "^0.35.4",
+    "@next/swc-darwin-arm64": "16.4.0-canary.40",
+    "@next/swc-darwin-x64": "16.4.0-canary.40",
+    "@next/swc-linux-arm64-gnu": "16.4.0-canary.40",
+    "@next/swc-linux-arm64-musl": "16.4.0-canary.40",
+    "@next/swc-linux-x64-gnu": "16.4.0-canary.40",
+    "@next/swc-linux-x64-musl": "16.4.0-canary.40",
+    "@next/swc-win32-arm64-msvc": "16.4.0-canary.40",
+    "@next/swc-win32-x64-msvc": "16.4.0-canary.40"
   },
[...]

diff --git a/packages/third-parties/package.json b/packages/third-parties/package
.json
index 7a7fab8790..8cbf23b9cd 100644
--- a/packages/third-parties/package.json
+++ b/packages/third-parties/package.json
@@ -32,7 +32,7 @@
     "typescript": "6.0.2"
   },
   "peerDependencies": {
-    "next": "^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0",
+    "next": "^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || 16.4.0-canary.40",
     "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0"
   }
```
parent 20192237
...@@ -10,7 +10,6 @@ compiled/ ...@@ -10,7 +10,6 @@ compiled/
# ast-grep snapshots (managed by ast-grep, not prettier) # ast-grep snapshots (managed by ast-grep, not prettier)
.config/ast-grep/rule-tests/__snapshots__/ .config/ast-grep/rule-tests/__snapshots__/
lerna.json
test-timings.json test-timings.json
pnpm-lock.yaml pnpm-lock.yaml
......
...@@ -37,5 +37,5 @@ which builds the packages and publishes them to npm under the dist-tag matching ...@@ -37,5 +37,5 @@ which builds the packages and publishes them to npm under the dist-tag matching
the channel. the channel.
Version bumps are restricted to the release branches listed in Version bumps are restricted to the release branches listed in
`command.version.allowBranch` in `lerna.json`. `scripts/create-release-branch.js` `scripts/release-branches.json`. `scripts/create-release-branch.js` adds a new
adds a new release branch to that list when one is created. release branch to that list when one is created.
{
"npmClient": "pnpm",
"packages": [
"packages/*"
],
"command": {
"version": {
"exact": true,
"allowBranch": [
"canary"
]
}
},
"version": "16.5.0-canary.1"
}
\ No newline at end of file
...@@ -88,7 +88,6 @@ ...@@ -88,7 +88,6 @@
"debug-brk": "cross-env NEXT_PRIVATE_LOCAL_DEV=1 NEXT_TELEMETRY_DISABLED=1 node --inspect-brk --trace-deprecation --enable-source-maps packages/next/dist/bin/next", "debug-brk": "cross-env NEXT_PRIVATE_LOCAL_DEV=1 NEXT_TELEMETRY_DISABLED=1 node --inspect-brk --trace-deprecation --enable-source-maps packages/next/dist/bin/next",
"pnpm:devPreinstall": "node scripts/create-next-bin-placeholder.mjs", "pnpm:devPreinstall": "node scripts/create-next-bin-placeholder.mjs",
"postinstall": "node scripts/git-configure.mjs && node scripts/install-native.mjs", "postinstall": "node scripts/git-configure.mjs && node scripts/install-native.mjs",
"version": "pnpm install --no-frozen-lockfile && git add .",
"prepare": "husky", "prepare": "husky",
"sync-react": "node ./scripts/sync-react.js", "sync-react": "node ./scripts/sync-react.js",
"update-google-fonts": "node ./scripts/update-google-fonts.js", "update-google-fonts": "node ./scripts/update-google-fonts.js",
...@@ -233,7 +232,6 @@ ...@@ -233,7 +232,6 @@
"kleur": "^4.1.0", "kleur": "^4.1.0",
"ky": "0.19.1", "ky": "0.19.1",
"ky-universal": "0.6.0", "ky-universal": "0.6.0",
"lerna": "9.0.3",
"lint-staged": "15.2.2", "lint-staged": "15.2.2",
"lodash": "4.18.1", "lodash": "4.18.1",
"lost": "8.3.1", "lost": "8.3.1",
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
"dist" "dist"
], ],
"dependencies": { "dependencies": {
"@next/eslint-plugin-next": "16.5.0-canary.1", "@next/eslint-plugin-next": "workspace:*",
"eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2", "eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0", "eslint-plugin-import": "^2.32.0",
......
...@@ -101,7 +101,7 @@ ...@@ -101,7 +101,7 @@
] ]
}, },
"dependencies": { "dependencies": {
"@next/env": "16.5.0-canary.1", "@next/env": "workspace:*",
"@swc/helpers": "0.5.23", "@swc/helpers": "0.5.23",
"baseline-browser-mapping": "^2.9.19", "baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579", "caniuse-lite": "^1.0.30001579",
...@@ -165,11 +165,11 @@ ...@@ -165,11 +165,11 @@
"@modelcontextprotocol/sdk": "1.18.1", "@modelcontextprotocol/sdk": "1.18.1",
"@mswjs/interceptors": "0.42.6", "@mswjs/interceptors": "0.42.6",
"@napi-rs/triples": "1.2.0", "@napi-rs/triples": "1.2.0",
"@next/font": "16.5.0-canary.1", "@next/font": "workspace:*",
"@next/polyfill-module": "16.5.0-canary.1", "@next/polyfill-module": "workspace:*",
"@next/polyfill-nomodule": "16.5.0-canary.1", "@next/polyfill-nomodule": "workspace:*",
"@next/react-refresh-utils": "16.5.0-canary.1", "@next/react-refresh-utils": "workspace:*",
"@next/swc": "16.5.0-canary.1", "@next/swc": "workspace:*",
"@opentelemetry/api": "1.6.0", "@opentelemetry/api": "1.6.0",
"@playwright/test": "1.61.0", "@playwright/test": "1.61.0",
"@rspack/core": "1.6.7", "@rspack/core": "1.6.7",
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
"third-party-capital": "1.0.20" "third-party-capital": "1.0.20"
}, },
"devDependencies": { "devDependencies": {
"next": "16.5.0-canary.1", "next": "workspace:*",
"outdent": "0.8.0", "outdent": "0.8.0",
"prettier": "2.5.1", "prettier": "2.5.1",
"typescript": "6.0.2" "typescript": "6.0.2"
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
// @ts-check // @ts-check
const fs = require('fs/promises') const fs = require('fs/promises')
const path = require('path')
const semver = require('semver') const semver = require('semver')
const { const {
getGitHubToken, getGitHubToken,
getGitHubTokenMissingMessage, getGitHubTokenMissingMessage,
} = require('./release-github-auth') } = require('./release-github-auth')
const { readReleaseVersion } = require('./release-version')
const PUBLISH_RELEASE_JOB_NAME = 'Potentially publish release' const PUBLISH_RELEASE_JOB_NAME = 'Potentially publish release'
const TRIGGER_RELEASE_WORKFLOW = 'trigger_release.yml' const TRIGGER_RELEASE_WORKFLOW = 'trigger_release.yml'
...@@ -148,9 +148,7 @@ async function main() { ...@@ -148,9 +148,7 @@ async function main() {
} }
const [owner, repo] = repoFullName.split('/') const [owner, repo] = repoFullName.split('/')
const currentCanaryVersion = JSON.parse( const currentCanaryVersion = readReleaseVersion()
await fs.readFile(path.join(process.cwd(), 'lerna.json'), 'utf8')
).version
const releaseCommitMessage = const releaseCommitMessage =
headCommitMessage || (await getCommitMessage(owner, repo, headSha, token)) headCommitMessage || (await getCommitMessage(owner, repo, headSha, token))
......
...@@ -151,6 +151,29 @@ async function main() { ...@@ -151,6 +151,29 @@ async function main() {
} }
} }
// Internal dependencies are `workspace:*` in the repo, and the loop above
// is what resolves them -- to a tarball URL, not a version, because that is
// what preview installs need. `npm pack` below does not understand the
// protocol, so anything left unresolved would ship a broken manifest.
for (const field of [
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies',
]) {
for (const [dependencyName, specifier] of Object.entries(
manifest[field] ?? {}
)) {
if (typeof specifier === 'string' && specifier.includes('workspace:')) {
throw new Error(
`${manifest.name} has an unresolved workspace dependency ` +
`${field}.${dependencyName} ("${specifier}"). It is missing from ` +
`the release package list.`
)
}
}
}
await fs.writeFile( await fs.writeFile(
packageJsonPath, packageJsonPath,
JSON.stringify(manifest, null, 2) + JSON.stringify(manifest, null, 2) +
......
...@@ -84,15 +84,18 @@ async function main() { ...@@ -84,15 +84,18 @@ async function main() {
await execa('git', ['reset', '--hard', tagName], { await execa('git', ['reset', '--hard', tagName], {
stdio: 'inherit', stdio: 'inherit',
}) })
const lernaPath = path.join(__dirname, '..', 'lerna.json') // Release branches need to be added here or `scripts/version-bump.js`
const existingLerna = JSON.parse( // refuses to run on them.
await fs.promises.readFile(lernaPath, 'utf8') const releaseBranchesPath = path.join(__dirname, 'release-branches.json')
const releaseBranches = JSON.parse(
await fs.promises.readFile(releaseBranchesPath, 'utf8')
) )
// `allowBranch` gates `lerna version`, so it lives under `command.version`. releaseBranches.push(branchName)
// Release branches need to be added here or the version bump refuses to run.
existingLerna.command.version.allowBranch.push(branchName)
await fs.promises.writeFile(lernaPath, JSON.stringify(existingLerna, null, 2)) await fs.promises.writeFile(
releaseBranchesPath,
JSON.stringify(releaseBranches, null, 2) + '\n'
)
const buildAndDeployPath = path.join( const buildAndDeployPath = path.join(
__dirname, __dirname,
......
...@@ -21,35 +21,21 @@ const writeJson = async (filePath, data) => ...@@ -21,35 +21,21 @@ const writeJson = async (filePath, data) =>
const packages = await fs.readdir(path.join(cwd, 'packages')) const packages = await fs.readdir(path.join(cwd, 'packages'))
const pkgJsonData = new Map() const pkgJsonData = new Map()
const pkgNames = []
await Promise.all( await Promise.all(
packages.map(async (pkgDir) => { packages.map(async (pkgDir) => {
const data = await readJson( const data = await readJson(
path.join(cwd, 'packages', pkgDir, 'package.json') path.join(cwd, 'packages', pkgDir, 'package.json')
) )
pkgNames.push(data.name)
pkgJsonData.set(pkgDir, data) pkgJsonData.set(pkgDir, data)
}) })
) )
// Internal dependencies use the `workspace:*` protocol, so they carry no
// version to normalize -- only each package's own `version` field does.
const normalizeVersions = async (filePath, data) => { const normalizeVersions = async (filePath, data) => {
data = data || (await readJson(filePath)) data = data || (await readJson(filePath))
const version = data.version
if (version) { if (data.version) {
data.version = NORMALIZED_VERSION data.version = NORMALIZED_VERSION
const normalizeEntry = (type, key) => {
const pkgVersion = data[type][key]
if (pkgNames.includes(key) && pkgVersion === version) {
data[type][key] = NORMALIZED_VERSION
}
}
for (const key of Object.keys(data.dependencies || {})) {
normalizeEntry('dependencies', key)
}
for (const key of Object.keys(data.devDependencies || {})) {
normalizeEntry('devDependencies', key)
}
await writeJson(filePath, data) await writeJson(filePath, data)
} }
} }
...@@ -61,7 +47,6 @@ const writeJson = async (filePath, data) => ...@@ -61,7 +47,6 @@ const writeJson = async (filePath, data) =>
) )
) )
) )
await normalizeVersions(path.join(cwd, 'lerna.json'))
await fs.unlink(path.join(cwd, 'pnpm-lock.yaml')) await fs.unlink(path.join(cwd, 'pnpm-lock.yaml'))
await fs.writeFile(path.join(cwd, 'pnpm-lock.yaml'), '') await fs.writeFile(path.join(cwd, 'pnpm-lock.yaml'), '')
......
...@@ -10,6 +10,7 @@ const { ...@@ -10,6 +10,7 @@ const {
getGitHubToken, getGitHubToken,
getGitHubTokenMissingMessage, getGitHubTokenMissingMessage,
} = require('./release-github-auth') } = require('./release-github-auth')
const { readReleaseVersion } = require('./release-version')
const cwd = process.cwd() const cwd = process.cwd()
const dryRun = process.argv.includes('--dry-run') const dryRun = process.argv.includes('--dry-run')
...@@ -22,12 +23,10 @@ const publishRetryDelaySeconds = 15 ...@@ -22,12 +23,10 @@ const publishRetryDelaySeconds = 15
} }
const publishSema = new Sema(2) const publishSema = new Sema(2)
const { version } = JSON.parse( const version = readReleaseVersion()
await fs.readFile(path.join(cwd, 'lerna.json'), 'utf-8')
)
const parsedVersion = semver.parse(version) const parsedVersion = semver.parse(version)
if (parsedVersion === null) { if (parsedVersion === null) {
throw new Error(`Invalid version in lerna.json: ${version}`) throw new Error(`Invalid version: ${version}`)
} }
const prereleaseChannel = parsedVersion.prerelease[0] const prereleaseChannel = parsedVersion.prerelease[0]
const isPrerelease = prereleaseChannel != null const isPrerelease = prereleaseChannel != null
......
// @ts-check // @ts-check
const execa = require('execa') const execa = require('execa')
const fs = require('fs/promises')
const semver = require('semver') const semver = require('semver')
const { const {
replayLocalCommitsAsSigned, replayLocalCommitsAsSigned,
...@@ -9,6 +8,7 @@ const { ...@@ -9,6 +8,7 @@ const {
alignLocalBranchWithSignedCommit, alignLocalBranchWithSignedCommit,
} = require('./github-utils/signed-commit') } = require('./github-utils/signed-commit')
const { generateChangelog } = require('./release-changelog') const { generateChangelog } = require('./release-changelog')
const { readReleaseVersion } = require('./release-version')
const REPO_API_PATH = '/repos/vercel/next.js' const REPO_API_PATH = '/repos/vercel/next.js'
...@@ -23,12 +23,11 @@ async function git(args, options = {}) { ...@@ -23,12 +23,11 @@ async function git(args, options = {}) {
} }
/** /**
* Verify the local Lerna release commit has the version tag implied by * Verify the local release commit has the version tag implied by the version
* lerna.json, then return that tag name for GitHub ref creation. * source of truth, then return that tag name for GitHub ref creation.
*/ */
async function getLocalReleaseTagName(commitSha) { async function getLocalReleaseTagName(commitSha) {
const { version } = JSON.parse(await fs.readFile('lerna.json', 'utf8')) const expectedTagName = `v${readReleaseVersion()}`
const expectedTagName = `v${version}`
const tags = String( const tags = String(
await git(['tag', '--points-at', commitSha], { captureOutput: true }) await git(['tag', '--points-at', commitSha], { captureOutput: true })
) )
...@@ -38,7 +37,7 @@ async function getLocalReleaseTagName(commitSha) { ...@@ -38,7 +37,7 @@ async function getLocalReleaseTagName(commitSha) {
if (!tags.includes(expectedTagName)) { if (!tags.includes(expectedTagName)) {
throw new Error( throw new Error(
`Expected local Lerna release commit ${commitSha} to be tagged with ${expectedTagName}; found ${tags.join( `Expected local release commit ${commitSha} to be tagged with ${expectedTagName}; found ${tags.join(
', ' ', '
)}` )}`
) )
...@@ -48,7 +47,7 @@ async function getLocalReleaseTagName(commitSha) { ...@@ -48,7 +47,7 @@ async function getLocalReleaseTagName(commitSha) {
} }
/** /**
* Return the local Lerna release commit's single parent so the GitHub-created * Return the local release commit's single parent so the GitHub-created
* commit can replay the same tree change on top of the same base commit. * commit can replay the same tree change on top of the same base commit.
*/ */
async function getSingleParent(commitSha) { async function getSingleParent(commitSha) {
...@@ -70,12 +69,12 @@ async function getSingleParent(commitSha) { ...@@ -70,12 +69,12 @@ async function getSingleParent(commitSha) {
} }
/** /**
* Replace Lerna's local release commit(s) with equivalent GitHub-signed * Replace the local release commit(s) with equivalent GitHub-signed
* commits, then move the release tag and current branch in a single branch * commits, then move the release tag and current branch in a single branch
* push. * push.
* *
* Signs every local commit between the remote base and local HEAD. The release * Signs every local commit between the remote base and local HEAD. The release
* tag is placed on the signed commit that corresponds to the local Lerna * tag is placed on the signed commit that corresponds to the local
* release commit; the branch is fast-forwarded to the final signed commit. * release commit; the branch is fast-forwarded to the final signed commit.
* *
* For a normal release this is a single commit (tag == branch head). For an * For a normal release this is a single commit (tag == branch head). For an
...@@ -83,8 +82,8 @@ async function getSingleParent(commitSha) { ...@@ -83,8 +82,8 @@ async function getSingleParent(commitSha) {
* version bump (tagged) followed by a revert restoring the canary version — so * version bump (tagged) followed by a revert restoring the canary version — so
* the tag points at the preview commit while the branch ends on the revert. * the tag points at the preview commit while the branch ends on the revert.
* `options.baseSha` and `options.tagName` let the caller pin both explicitly * `options.baseSha` and `options.tagName` let the caller pin both explicitly
* (required for preview, since after the revert `lerna.json` no longer matches * (required for preview, since after the revert the version source of truth no
* HEAD). * longer matches HEAD).
* *
* `options.githubRequest` * `options.githubRequest`
* @param {string} token GitHub API token with repo access * @param {string} token GitHub API token with repo access
...@@ -214,7 +213,7 @@ async function getPreviousReleaseTag(tagCommitSha, newVersion) { ...@@ -214,7 +213,7 @@ async function getPreviousReleaseTag(tagCommitSha, newVersion) {
/** /**
* List the commits that make up a release, newest range endpoint inclusive, * List the commits that make up a release, newest range endpoint inclusive,
* excluding merge commits and the version-bump commits Lerna creates (whose * excluding merge commits and the version-bump commits the release creates (whose
* title is itself a version like `v16.3.0-canary.62`). * title is itself a version like `v16.3.0-canary.62`).
*/ */
async function getReleaseCommits(fromTag, tagCommitSha) { async function getReleaseCommits(fromTag, tagCommitSha) {
......
// @ts-check
const fs = require('fs')
const path = require('path')
/**
* Every package in this repo is versioned in lockstep, so any of their
* manifests carries the release version. `packages/next/package.json` is the
* canonical one: it is always published and is not going to be renamed.
*/
const VERSION_SOURCE_PATH = path.join(
__dirname,
'..',
'packages',
'next',
'package.json'
)
/**
* @returns {string} the current release version e.g. `16.4.0-canary.22`
*/
function readReleaseVersion() {
const { version } = JSON.parse(fs.readFileSync(VERSION_SOURCE_PATH, 'utf8'))
if (typeof version !== 'string' || version === '') {
throw new Error(`Invalid version in ${VERSION_SOURCE_PATH}`)
}
return version
}
module.exports = { readReleaseVersion }
// @ts-check // @ts-check
const execa = require('execa') const execa = require('execa')
const fs = require('node:fs/promises')
const path = require('node:path') const path = require('node:path')
const { readReleaseVersion } = require('./release-version')
async function main() { async function main() {
const [githubSha] = process.argv.slice(2) const [githubSha] = process.argv.slice(2)
...@@ -24,34 +24,22 @@ async function main() { ...@@ -24,34 +24,22 @@ async function main() {
]), ]),
]) ])
const lernaConfigPath = path.join(repoRoot, 'lerna.json')
const lernaConfig = JSON.parse(await fs.readFile(lernaConfigPath, 'utf8'))
// 15.0.0-canary.17 -> 15.0.0 // 15.0.0-canary.17 -> 15.0.0
// 15.0.0 -> 15.0.0 // 15.0.0 -> 15.0.0
const [semverStableVersion] = lernaConfig.version.split('-') const [semverStableVersion] = readReleaseVersion().split('-')
// This can create colliding versions between different forks which should be incredibly rare. // This can create colliding versions between different forks which should be incredibly rare.
// Preview builds are installed by URL anyway which is unique between forks by // Preview builds are installed by URL anyway which is unique between forks by
// controlling the repo var setting the preview builds base url. // controlling the repo var setting the preview builds base url.
const version = `${semverStableVersion}-preview-${shortSha}-${dateString}` const version = `${semverStableVersion}-preview-${shortSha}-${dateString}`
//
// Lerna version requires a non-detached HEAD
await execa('git', ['checkout', '-B', `preview/${shortSha}`, githubSha], {
cwd: repoRoot,
stdio: 'inherit',
})
await execa( await execa(
'pnpm', 'node',
[ [
'lerna', 'scripts/version-bump.js',
'version',
version, version,
'--no-git-tag-version', '--no-git-tag-version',
'--no-push',
'--allow-branch', '--allow-branch',
'**', '**',
'--yes',
], ],
{ cwd: repoRoot, stdio: 'inherit' } { cwd: repoRoot, stdio: 'inherit' }
) )
......
// @ts-check // @ts-check
const path = require('path')
const execa = require('execa') const execa = require('execa')
const fs = require('fs/promises')
const semver = require('semver') const semver = require('semver')
const { const {
configureGitHubAuth, configureGitHubAuth,
...@@ -13,6 +11,7 @@ const { ...@@ -13,6 +11,7 @@ const {
createGitHubReleaseCommit, createGitHubReleaseCommit,
createGitHubRelease, createGitHubRelease,
} = require('./release-github-api') } = require('./release-github-api')
const { readReleaseVersion } = require('./release-version')
const SEMVER_TYPES = ['patch', 'minor', 'major'] const SEMVER_TYPES = ['patch', 'minor', 'major']
...@@ -67,7 +66,7 @@ function createMockGitHubRequest() { ...@@ -67,7 +66,7 @@ function createMockGitHubRequest() {
async function computePreviewVersion(canaryVersion) { async function computePreviewVersion(canaryVersion) {
const parsed = semver.parse(canaryVersion) const parsed = semver.parse(canaryVersion)
if (!parsed) { if (!parsed) {
throw new Error(`Invalid version in lerna.json: ${canaryVersion}`) throw new Error(`Invalid version: ${canaryVersion}`)
} }
const canaryBase = `${parsed.major}.${parsed.minor}.${parsed.patch}` const canaryBase = `${parsed.major}.${parsed.minor}.${parsed.patch}`
...@@ -159,17 +158,15 @@ async function main() { ...@@ -159,17 +158,15 @@ async function main() {
console.log(`Running release-${releaseType}...`) console.log(`Running release-${releaseType}...`)
const { version: canaryVersion } = JSON.parse( const canaryVersion = readReleaseVersion()
await fs.readFile(path.join(process.cwd(), 'lerna.json'), 'utf-8')
)
// The current branch tip, captured before Lerna creates the release // The current branch tip, captured before the version bump creates the
// commit(s). For a preview release this is the base that both the // release commit(s). For a preview release this is the base that both the
// preview-bump and the revert-to-canary commits are signed on top of. // preview-bump and the revert-to-canary commits are signed on top of.
const { stdout: baseSha } = await execa('git', ['rev-parse', 'HEAD']) const { stdout: baseSha } = await execa('git', ['rev-parse', 'HEAD'])
// Preview cuts ad-hoc from canary use an explicit, computed version rather // Preview cuts ad-hoc from canary use an explicit, computed version rather
// than a Lerna prerelease bump (see computePreviewVersion). // than a semver prerelease bump (see computePreviewVersion).
const previewVersion = isPreview const previewVersion = isPreview
? await computePreviewVersion(canaryVersion) ? await computePreviewVersion(canaryVersion)
: null : null
...@@ -185,33 +182,31 @@ async function main() { ...@@ -185,33 +182,31 @@ async function main() {
previewVersion ?? previewVersion ??
(isCanary || isReleaseCandidate || isBeta ? preleaseType : semverType) (isCanary || isReleaseCandidate || isBeta ? preleaseType : semverType)
const lernaArgs = ['lerna', 'version', versionArg] const versionBumpArgs = ['scripts/version-bump.js', versionArg]
if (isCanary) { if (isCanary) {
lernaArgs.push('--preid', 'canary') versionBumpArgs.push('--preid', 'canary')
} else if (isReleaseCandidate) { } else if (isReleaseCandidate) {
lernaArgs.push('--preid', 'rc') versionBumpArgs.push('--preid', 'rc')
} else if (isBeta) { } else if (isBeta) {
lernaArgs.push('--preid', 'beta') versionBumpArgs.push('--preid', 'beta')
} }
lernaArgs.push('--force-publish', '-y', '--no-push')
if (dryRun) { if (dryRun) {
// So the dry-run can be exercised outside // So the dry-run can be exercised outside
// of the release branches `command.version.allowBranch` in lerna.json // of the release branches scripts/release-branches.json restricts
// restricts real version bumps to. // real version bumps to.
lernaArgs.push('--allow-branch', '**') versionBumpArgs.push('--allow-branch', '**')
} }
const child = execa('pnpm', lernaArgs, { const child = execa('node', versionBumpArgs, {
stdio: 'inherit', stdio: 'inherit',
}) })
await child await child
if (isPreview) { if (isPreview) {
// Lerna's bump commit (now HEAD, tagged v<previewVersion>) carries the // The bump commit (now HEAD, tagged v<previewVersion>) carries the
// preview versions. Add a second commit that restores the canary versions // preview versions. Add a second commit that restores the canary versions
// so `canary` keeps advancing its own line; the preview tag still points at // so `canary` keeps advancing its own line; the preview tag still points at
// the bump commit. Both land in a single push (see // the bump commit. Both land in a single push (see
......
#!/usr/bin/env node
// @ts-check
/*
Bumps the version of every package in `packages/*` in lockstep and creates
the release commit and tag.
It stays small because of two properties of this repo: every package shares
one version, and a release always bumps all of them, so there is no
changed-detection to do. Internal dependencies use the
`workspace:*` protocol, so dependents need no rewriting either -- pnpm
substitutes the concrete version when packing.
Usage:
node scripts/version-bump.js <version|increment> [options]
<version|increment> an explicit version (`16.4.0-preview-abc-2026`) or a
semver increment (`prerelease`, `preminor`, `patch`,
...)
--preid <id> prerelease identifier for pre* increments
--no-git-tag-version update the manifests but do not commit or tag
--allow-branch <glob> override the branches releases may run from;
repeatable, `**` allows any branch
*/
const fs = require('fs/promises')
const path = require('path')
const execa = require('execa')
const semver = require('semver')
const { readReleaseVersion } = require('./release-version')
const repoRoot = path.join(__dirname, '..')
const packagesDir = path.join(repoRoot, 'packages')
const releaseBranchesPath = path.join(__dirname, 'release-branches.json')
const SEMVER_INCREMENTS = new Set([
'major',
'minor',
'patch',
'premajor',
'preminor',
'prepatch',
'prerelease',
])
/**
* @param {string[]} argv
*/
function parseArgs(argv) {
/** @type {string | undefined} */
let versionArg
/** @type {string | undefined} */
let preid
let gitTagVersion = true
/** @type {string[]} */
const allowBranch = []
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]
switch (arg) {
case '--preid':
preid = argv[++i]
break
case '--allow-branch':
allowBranch.push(argv[++i])
break
case '--no-git-tag-version':
gitTagVersion = false
break
default:
if (arg.startsWith('-')) {
throw new Error(`Unknown option: ${arg}`)
}
if (versionArg !== undefined) {
throw new Error(
`Unexpected second version argument: ${arg} (already got ${versionArg})`
)
}
versionArg = arg
}
}
if (versionArg === undefined) {
throw new Error('Missing <version|increment> argument')
}
return { versionArg, preid, gitTagVersion, allowBranch }
}
/**
* Releases are restricted to `canary` and the release branches.
* `scripts/create-release-branch.js` adds new release branches to the list.
*
* @param {string[]} allowBranchOverride
*/
async function assertBranchIsAllowed(allowBranchOverride) {
const patterns =
allowBranchOverride.length > 0
? allowBranchOverride
: JSON.parse(await fs.readFile(releaseBranchesPath, 'utf8'))
if (patterns.includes('**')) {
return
}
const { stdout: currentBranch } = await execa('git', [
'rev-parse',
'--abbrev-ref',
'HEAD',
])
if (!patterns.includes(currentBranch.trim())) {
throw new Error(
`Refusing to bump the version on branch "${currentBranch.trim()}". ` +
`Allowed branches: ${patterns.join(', ')}. ` +
`Pass \`--allow-branch **\` to override.`
)
}
}
/**
* @param {string} currentVersion
* @param {string} versionArg
* @param {string | undefined} preid
*/
function computeNextVersion(currentVersion, versionArg, preid) {
// An explicit version, as used by preview releases.
if (semver.valid(versionArg)) {
return versionArg
}
if (!SEMVER_INCREMENTS.has(versionArg)) {
throw new Error(
`"${versionArg}" is neither a valid version nor a semver increment ` +
`(${[...SEMVER_INCREMENTS].join(', ')})`
)
}
const nextVersion = semver.inc(
currentVersion,
/** @type {semver.ReleaseType} */ (versionArg),
preid
)
if (nextVersion === null) {
throw new Error(
`Could not apply "${versionArg}" to current version ${currentVersion}`
)
}
return nextVersion
}
/**
* @param {string} nextVersion
* @returns {Promise<string[]>} the names of the packages that were updated
*/
async function writeVersionToPackages(nextVersion) {
const packageDirs = await fs.readdir(packagesDir)
/** @type {string[]} */
const updated = []
for (const packageDir of packageDirs) {
const manifestPath = path.join(packagesDir, packageDir, 'package.json')
/** @type {string} */
let raw
try {
raw = await fs.readFile(manifestPath, 'utf8')
} catch (error) {
// Not every directory under packages/ is necessarily a package.
if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') {
continue
}
throw error
}
const manifest = JSON.parse(raw)
manifest.version = nextVersion
await fs.writeFile(
manifestPath,
JSON.stringify(manifest, null, 2) + (raw.endsWith('\n') ? '\n' : '')
)
updated.push(manifest.name)
}
if (updated.length === 0) {
throw new Error(`Found no packages to version in ${packagesDir}`)
}
return updated
}
async function main() {
const { versionArg, preid, gitTagVersion, allowBranch } = parseArgs(
process.argv.slice(2)
)
await assertBranchIsAllowed(allowBranch)
const currentVersion = readReleaseVersion()
const nextVersion = computeNextVersion(currentVersion, versionArg, preid)
console.log(`Bumping ${currentVersion} -> ${nextVersion}`)
const updated = await writeVersionToPackages(nextVersion)
console.log(`Updated ${updated.length} packages`)
// `workspace:*` specifiers record no versions in the lockfile, so a version
// bump never stales it and there is nothing to refresh here.
// An unchanged lockfile is important since that means we can reuse
// node_modules caches keyed on the hash of the lockfile.
await execa('git', ['add', '.'], { cwd: repoRoot, stdio: 'inherit' })
if (!gitTagVersion) {
console.log('Skipping release commit and tag (--no-git-tag-version)')
return
}
// `check-backport-canary-release.js` and `release-github-api.js` both
// identify release commits by a subject that is exactly `v<version>`.
const tagName = `v${nextVersion}`
await execa('git', ['commit', '-m', tagName], {
cwd: repoRoot,
stdio: 'inherit',
})
await execa('git', ['tag', tagName], { cwd: repoRoot, stdio: 'inherit' })
console.log(`Created release commit and tag ${tagName}`)
}
if (require.main === module) {
main().catch((error) => {
console.error(error)
process.exit(1)
})
}
module.exports = {
parseArgs,
computeNextVersion,
assertBranchIsAllowed,
writeVersionToPackages,
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment