release.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. // @ts-check
  2. import fs from 'node:fs'
  3. import path from 'node:path'
  4. import pico from 'picocolors'
  5. import semver from 'semver'
  6. import enquirer from 'enquirer'
  7. import { createRequire } from 'node:module'
  8. import { fileURLToPath } from 'node:url'
  9. import { exec } from './utils.js'
  10. import { parseArgs } from 'node:util'
  11. /**
  12. * @typedef {{
  13. * name: string
  14. * version: string
  15. * dependencies?: { [dependenciesPackageName: string]: string }
  16. * peerDependencies?: { [peerDependenciesPackageName: string]: string }
  17. * }} Package
  18. */
  19. let versionUpdated = false
  20. const { prompt } = enquirer
  21. const currentVersion = createRequire(import.meta.url)('../package.json').version
  22. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  23. const { values: args, positionals } = parseArgs({
  24. allowPositionals: true,
  25. options: {
  26. preid: {
  27. type: 'string',
  28. },
  29. dry: {
  30. type: 'boolean',
  31. },
  32. tag: {
  33. type: 'string',
  34. },
  35. canary: {
  36. type: 'boolean',
  37. },
  38. skipBuild: {
  39. type: 'boolean',
  40. },
  41. skipTests: {
  42. type: 'boolean',
  43. },
  44. skipGit: {
  45. type: 'boolean',
  46. },
  47. skipPrompts: {
  48. type: 'boolean',
  49. },
  50. publish: {
  51. type: 'boolean',
  52. default: false,
  53. },
  54. publishOnly: {
  55. type: 'boolean',
  56. },
  57. registry: {
  58. type: 'string',
  59. },
  60. },
  61. })
  62. const preId = args.preid || semver.prerelease(currentVersion)?.[0]
  63. const isDryRun = args.dry
  64. /** @type {boolean | undefined} */
  65. let skipTests = args.skipTests
  66. const skipBuild = args.skipBuild
  67. const isCanary = args.canary
  68. const skipPrompts = args.skipPrompts || args.canary
  69. const skipGit = args.skipGit || args.canary
  70. const packages = fs
  71. .readdirSync(path.resolve(__dirname, '../packages'))
  72. .filter(p => {
  73. const pkgRoot = path.resolve(__dirname, '../packages', p)
  74. if (fs.statSync(pkgRoot).isDirectory()) {
  75. const pkg = JSON.parse(
  76. fs.readFileSync(path.resolve(pkgRoot, 'package.json'), 'utf-8'),
  77. )
  78. return !pkg.private
  79. }
  80. })
  81. const isCorePackage = (/** @type {string} */ pkgName) => {
  82. if (!pkgName) return
  83. if (pkgName === 'vue' || pkgName === '@vue/compat') {
  84. return true
  85. }
  86. return (
  87. pkgName.startsWith('@vue') &&
  88. packages.includes(pkgName.replace(/^@vue\//, ''))
  89. )
  90. }
  91. const renamePackageToCanary = (/** @type {string} */ pkgName) => {
  92. if (pkgName === 'vue') {
  93. return '@vue/canary'
  94. }
  95. if (isCorePackage(pkgName)) {
  96. return `${pkgName}-canary`
  97. }
  98. return pkgName
  99. }
  100. const keepThePackageName = (/** @type {string} */ pkgName) => pkgName
  101. /** @type {string[]} */
  102. const skippedPackages = []
  103. /** @type {ReadonlyArray<import('semver').ReleaseType>} */
  104. const versionIncrements = [
  105. 'patch',
  106. 'minor',
  107. 'major',
  108. ...(preId
  109. ? /** @type {const} */ (['prepatch', 'preminor', 'premajor', 'prerelease'])
  110. : []),
  111. ]
  112. const inc = (/** @type {import('semver').ReleaseType} */ i) =>
  113. semver.inc(currentVersion, i, typeof preId === 'string' ? preId : undefined)
  114. const run = async (
  115. /** @type {string} */ bin,
  116. /** @type {ReadonlyArray<string>} */ args,
  117. /** @type {import('node:child_process').SpawnOptions} */ opts = {},
  118. ) => exec(bin, args, { stdio: 'inherit', ...opts })
  119. const dryRun = async (
  120. /** @type {string} */ bin,
  121. /** @type {ReadonlyArray<string>} */ args,
  122. /** @type {import('node:child_process').SpawnOptions} */ opts = {},
  123. ) => console.log(pico.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts)
  124. const runIfNotDry = isDryRun ? dryRun : run
  125. const getPkgRoot = (/** @type {string} */ pkg) =>
  126. path.resolve(__dirname, '../packages/' + pkg)
  127. const step = (/** @type {string} */ msg) => console.log(pico.cyan(msg))
  128. async function main() {
  129. if (!(await isInSyncWithRemote())) {
  130. return
  131. } else {
  132. console.log(`${pico.green(`✓`)} commit is up-to-date with remote.\n`)
  133. }
  134. let targetVersion = positionals[0]
  135. if (isCanary) {
  136. // The canary version string format is `3.yyyyMMdd.0` (or `3.yyyyMMdd.0-minor.0` for minor)
  137. // Use UTC date so that it's consistent across CI and maintainers' machines
  138. const date = new Date()
  139. const yyyy = date.getUTCFullYear()
  140. const MM = (date.getUTCMonth() + 1).toString().padStart(2, '0')
  141. const dd = date.getUTCDate().toString().padStart(2, '0')
  142. const major = semver.major(currentVersion)
  143. const datestamp = `${yyyy}${MM}${dd}`
  144. let canaryVersion
  145. canaryVersion = `${major}.${datestamp}.0`
  146. if (args.tag && args.tag !== 'latest') {
  147. canaryVersion = `${major}.${datestamp}.0-${args.tag}.0`
  148. }
  149. // check the registry to avoid version collision
  150. // in case we need to publish more than one canary versions in a day
  151. try {
  152. const pkgName = renamePackageToCanary('vue')
  153. const { stdout } = await run(
  154. 'pnpm',
  155. ['view', `${pkgName}@~${canaryVersion}`, 'version', '--json'],
  156. { stdio: 'pipe' },
  157. )
  158. let versions = JSON.parse(/** @type {string} */ (stdout))
  159. versions = Array.isArray(versions) ? versions : [versions]
  160. const latestSameDayPatch = /** @type {string} */ (
  161. semver.maxSatisfying(versions, `~${canaryVersion}`)
  162. )
  163. canaryVersion = /** @type {string} */ (
  164. semver.inc(latestSameDayPatch, 'patch')
  165. )
  166. if (args.tag && args.tag !== 'latest') {
  167. canaryVersion = /** @type {string} */ (
  168. semver.inc(latestSameDayPatch, 'prerelease', args.tag)
  169. )
  170. }
  171. } catch (/** @type {any} */ e) {
  172. if (/E404/.test(e.message)) {
  173. // the first patch version on that day
  174. } else {
  175. throw e
  176. }
  177. }
  178. targetVersion = canaryVersion
  179. }
  180. if (!targetVersion) {
  181. // no explicit version, offer suggestions
  182. /** @type {{ release: string }} */
  183. const { release } = await prompt({
  184. type: 'select',
  185. name: 'release',
  186. message: 'Select release type',
  187. choices: versionIncrements
  188. .map(i => `${i} (${inc(i)})`)
  189. .concat(['custom']),
  190. })
  191. if (release === 'custom') {
  192. /** @type {{ version: string }} */
  193. const result = await prompt({
  194. type: 'input',
  195. name: 'version',
  196. message: 'Input custom version',
  197. initial: currentVersion,
  198. })
  199. targetVersion = result.version
  200. } else {
  201. targetVersion = release.match(/\((.*)\)/)?.[1] ?? ''
  202. }
  203. }
  204. // @ts-expect-error
  205. if (versionIncrements.includes(targetVersion)) {
  206. // @ts-expect-error
  207. targetVersion = inc(targetVersion)
  208. }
  209. if (!semver.valid(targetVersion)) {
  210. throw new Error(`invalid target version: ${targetVersion}`)
  211. }
  212. if (skipPrompts) {
  213. step(
  214. isCanary
  215. ? `Releasing canary version v${targetVersion}...`
  216. : `Releasing v${targetVersion}...`,
  217. )
  218. } else {
  219. /** @type {{ yes: boolean }} */
  220. const { yes: confirmRelease } = await prompt({
  221. type: 'confirm',
  222. name: 'yes',
  223. message: `Releasing v${targetVersion}. Confirm?`,
  224. })
  225. if (!confirmRelease) {
  226. return
  227. }
  228. }
  229. await runTestsIfNeeded()
  230. // update all package versions and inter-dependencies
  231. step('\nUpdating cross dependencies...')
  232. updateVersions(
  233. targetVersion,
  234. isCanary ? renamePackageToCanary : keepThePackageName,
  235. )
  236. versionUpdated = true
  237. // generate changelog
  238. step('\nGenerating changelog...')
  239. await run(`pnpm`, ['run', 'changelog'])
  240. if (!skipPrompts) {
  241. /** @type {{ yes: boolean }} */
  242. const { yes: changelogOk } = await prompt({
  243. type: 'confirm',
  244. name: 'yes',
  245. message: `Changelog generated. Does it look good?`,
  246. })
  247. if (!changelogOk) {
  248. return
  249. }
  250. }
  251. // update pnpm-lock.yaml
  252. // skipped during canary release because the package names changed and installing with `workspace:*` would fail
  253. if (!isCanary) {
  254. step('\nUpdating lockfile...')
  255. await run(`pnpm`, ['install', '--prefer-offline'])
  256. }
  257. if (!skipGit) {
  258. const { stdout } = await run('git', ['diff'], { stdio: 'pipe' })
  259. if (stdout) {
  260. step('\nCommitting changes...')
  261. await runIfNotDry('git', ['add', '-A'])
  262. await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`])
  263. } else {
  264. console.log('No changes to commit.')
  265. }
  266. }
  267. // publish packages
  268. if (args.publish) {
  269. await buildPackages()
  270. await publishPackages(targetVersion)
  271. }
  272. // push to GitHub
  273. if (!skipGit) {
  274. step('\nPushing to GitHub...')
  275. await runIfNotDry('git', ['tag', `v${targetVersion}`])
  276. await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
  277. await runIfNotDry('git', ['push'])
  278. }
  279. if (!args.publish) {
  280. console.log(
  281. pico.yellow(
  282. '\nRelease will be done via GitHub Actions.\n' +
  283. 'Check status at https://github.com/vuejs/core/actions/workflows/release.yml',
  284. ),
  285. )
  286. }
  287. if (isDryRun) {
  288. console.log(`\nDry run finished - run git diff to see package changes.`)
  289. }
  290. if (skippedPackages.length) {
  291. console.log(
  292. pico.yellow(
  293. `The following packages are skipped and NOT published:\n- ${skippedPackages.join(
  294. '\n- ',
  295. )}`,
  296. ),
  297. )
  298. }
  299. console.log()
  300. }
  301. async function runTestsIfNeeded() {
  302. if (!skipTests) {
  303. step('Checking CI status for HEAD...')
  304. let isCIPassed = await getCIResult()
  305. skipTests ||= isCIPassed
  306. if (isCIPassed) {
  307. if (!skipPrompts) {
  308. /** @type {{ yes: boolean }} */
  309. const { yes: promptSkipTests } = await prompt({
  310. type: 'confirm',
  311. name: 'yes',
  312. message: `CI for this commit passed. Skip local tests?`,
  313. })
  314. skipTests = promptSkipTests
  315. } else {
  316. skipTests = true
  317. }
  318. } else if (skipPrompts) {
  319. throw new Error(
  320. 'CI for the latest commit has not passed yet. ' +
  321. 'Only run the release workflow after the CI has passed.',
  322. )
  323. }
  324. }
  325. if (!skipTests) {
  326. step('\nRunning tests...')
  327. if (!isDryRun) {
  328. await run('pnpm', ['run', 'test', '--run'])
  329. } else {
  330. console.log(`Skipped (dry run)`)
  331. }
  332. } else {
  333. step('Tests skipped.')
  334. }
  335. }
  336. async function getCIResult() {
  337. try {
  338. const sha = await getSha()
  339. const res = await fetch(
  340. `https://api.github.com/repos/vuejs/core/actions/runs?head_sha=${sha}` +
  341. `&status=success&exclude_pull_requests=true`,
  342. )
  343. /** @type {{ workflow_runs: ({ name: string, conclusion: string })[] }} */
  344. const data = await res.json()
  345. return data.workflow_runs.some(({ name, conclusion }) => {
  346. return name === 'ci' && conclusion === 'success'
  347. })
  348. } catch {
  349. console.error('Failed to get CI status for current commit.')
  350. return false
  351. }
  352. }
  353. async function isInSyncWithRemote() {
  354. try {
  355. const branch = await getBranch()
  356. const res = await fetch(
  357. `https://api.github.com/repos/vuejs/core/commits/${branch}?per_page=1`,
  358. )
  359. const data = await res.json()
  360. if (data.sha === (await getSha())) {
  361. return true
  362. } else {
  363. /** @type {{ yes: boolean }} */
  364. const { yes } = await prompt({
  365. type: 'confirm',
  366. name: 'yes',
  367. message: pico.red(
  368. `Local HEAD is not up-to-date with remote. Are you sure you want to continue?`,
  369. ),
  370. })
  371. return yes
  372. }
  373. } catch {
  374. console.error(
  375. pico.red('Failed to check whether local HEAD is up-to-date with remote.'),
  376. )
  377. return false
  378. }
  379. }
  380. async function getSha() {
  381. return (await exec('git', ['rev-parse', 'HEAD'])).stdout
  382. }
  383. async function getBranch() {
  384. return (await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout
  385. }
  386. /**
  387. * @param {string} version
  388. * @param {(pkgName: string) => string} getNewPackageName
  389. */
  390. function updateVersions(version, getNewPackageName = keepThePackageName) {
  391. // 1. update root package.json
  392. updatePackage(path.resolve(__dirname, '..'), version, getNewPackageName)
  393. // 2. update all packages
  394. packages.forEach(p =>
  395. updatePackage(getPkgRoot(p), version, getNewPackageName),
  396. )
  397. }
  398. /**
  399. * @param {string} pkgRoot
  400. * @param {string} version
  401. * @param {(pkgName: string) => string} getNewPackageName
  402. */
  403. function updatePackage(pkgRoot, version, getNewPackageName) {
  404. const pkgPath = path.resolve(pkgRoot, 'package.json')
  405. /** @type {Package} */
  406. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  407. pkg.name = getNewPackageName(pkg.name)
  408. pkg.version = version
  409. if (isCanary) {
  410. updateDeps(pkg, 'dependencies', version, getNewPackageName)
  411. updateDeps(pkg, 'peerDependencies', version, getNewPackageName)
  412. }
  413. fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
  414. }
  415. /**
  416. * @param {Package} pkg
  417. * @param {'dependencies' | 'peerDependencies'} depType
  418. * @param {string} version
  419. * @param {(pkgName: string) => string} getNewPackageName
  420. */
  421. function updateDeps(pkg, depType, version, getNewPackageName) {
  422. const deps = pkg[depType]
  423. if (!deps) return
  424. Object.keys(deps).forEach(dep => {
  425. if (isCorePackage(dep)) {
  426. const newName = getNewPackageName(dep)
  427. const newVersion = newName === dep ? version : `npm:${newName}@${version}`
  428. console.log(
  429. pico.yellow(`${pkg.name} -> ${depType} -> ${dep}@${newVersion}`),
  430. )
  431. deps[dep] = newVersion
  432. }
  433. })
  434. }
  435. async function buildPackages() {
  436. step('\nBuilding all packages...')
  437. if (!skipBuild) {
  438. await run('pnpm', ['run', 'build', '--withTypes'])
  439. } else {
  440. console.log(`(skipped)`)
  441. }
  442. }
  443. /**
  444. * @param {string} version
  445. */
  446. async function publishPackages(version) {
  447. // publish packages
  448. step('\nPublishing packages...')
  449. const additionalPublishFlags = []
  450. if (isDryRun) {
  451. additionalPublishFlags.push('--dry-run')
  452. }
  453. if (isDryRun || skipGit || process.env.CI) {
  454. additionalPublishFlags.push('--no-git-checks')
  455. }
  456. // add provenance metadata when releasing from CI
  457. // canary release commits are not pushed therefore we don't need to add provenance
  458. // also skip provenance if not publishing to actual npm
  459. if (process.env.CI && !isCanary && !args.registry) {
  460. additionalPublishFlags.push('--provenance')
  461. }
  462. for (const pkg of packages) {
  463. await publishPackage(pkg, version, additionalPublishFlags)
  464. }
  465. }
  466. /**
  467. * @param {string} pkgName
  468. * @param {string} version
  469. * @param {ReadonlyArray<string>} additionalFlags
  470. */
  471. async function publishPackage(pkgName, version, additionalFlags) {
  472. if (skippedPackages.includes(pkgName)) {
  473. return
  474. }
  475. let releaseTag = null
  476. if (args.tag) {
  477. releaseTag = args.tag
  478. } else if (version.includes('alpha')) {
  479. releaseTag = 'alpha'
  480. } else if (version.includes('beta')) {
  481. releaseTag = 'beta'
  482. } else if (version.includes('rc')) {
  483. releaseTag = 'rc'
  484. }
  485. step(`Publishing ${pkgName}...`)
  486. try {
  487. // Don't change the package manager here as we rely on pnpm to handle
  488. // workspace:* deps
  489. await run(
  490. 'pnpm',
  491. [
  492. 'publish',
  493. ...(releaseTag ? ['--tag', releaseTag] : []),
  494. '--access',
  495. 'public',
  496. ...(args.registry ? ['--registry', args.registry] : []),
  497. ...additionalFlags,
  498. ],
  499. {
  500. cwd: getPkgRoot(pkgName),
  501. stdio: 'pipe',
  502. },
  503. )
  504. console.log(pico.green(`Successfully published ${pkgName}@${version}`))
  505. } catch (/** @type {any} */ e) {
  506. if (e.message?.match(/previously published/)) {
  507. console.log(pico.red(`Skipping already published: ${pkgName}`))
  508. } else {
  509. throw e
  510. }
  511. }
  512. }
  513. async function publishOnly() {
  514. const targetVersion = positionals[0]
  515. if (targetVersion) {
  516. updateVersions(targetVersion)
  517. }
  518. await buildPackages()
  519. await publishPackages(currentVersion)
  520. }
  521. const fnToRun = args.publishOnly ? publishOnly : main
  522. fnToRun().catch(err => {
  523. if (versionUpdated) {
  524. // revert to current version on failed releases
  525. updateVersions(currentVersion)
  526. }
  527. console.error(err)
  528. process.exit(1)
  529. })