release.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. } else {
  272. console.log(
  273. pico.yellow(
  274. '\nPublish step skipped (will be done in GitHub actions on successful push)',
  275. ),
  276. )
  277. }
  278. // push to GitHub
  279. if (!skipGit) {
  280. step('\nPushing to GitHub...')
  281. await runIfNotDry('git', ['tag', `v${targetVersion}`])
  282. await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
  283. await runIfNotDry('git', ['push'])
  284. }
  285. if (isDryRun) {
  286. console.log(`\nDry run finished - run git diff to see package changes.`)
  287. }
  288. if (skippedPackages.length) {
  289. console.log(
  290. pico.yellow(
  291. `The following packages are skipped and NOT published:\n- ${skippedPackages.join(
  292. '\n- ',
  293. )}`,
  294. ),
  295. )
  296. }
  297. console.log()
  298. }
  299. async function runTestsIfNeeded() {
  300. if (!skipTests) {
  301. step('Checking CI status for HEAD...')
  302. let isCIPassed = await getCIResult()
  303. skipTests ||= isCIPassed
  304. if (isCIPassed) {
  305. if (!skipPrompts) {
  306. /** @type {{ yes: boolean }} */
  307. const { yes: promptSkipTests } = await prompt({
  308. type: 'confirm',
  309. name: 'yes',
  310. message: `CI for this commit passed. Skip local tests?`,
  311. })
  312. skipTests = promptSkipTests
  313. } else {
  314. skipTests = true
  315. }
  316. } else if (skipPrompts) {
  317. throw new Error(
  318. 'CI for the latest commit has not passed yet. ' +
  319. 'Only run the release workflow after the CI has passed.',
  320. )
  321. }
  322. }
  323. if (!skipTests) {
  324. step('\nRunning tests...')
  325. if (!isDryRun) {
  326. await run('pnpm', ['run', 'test', '--run'])
  327. } else {
  328. console.log(`Skipped (dry run)`)
  329. }
  330. } else {
  331. step('Tests skipped.')
  332. }
  333. }
  334. async function getCIResult() {
  335. try {
  336. const sha = await getSha()
  337. const res = await fetch(
  338. `https://api.github.com/repos/vuejs/core/actions/runs?head_sha=${sha}` +
  339. `&status=success&exclude_pull_requests=true`,
  340. )
  341. /** @type {{ workflow_runs: ({ name: string, conclusion: string })[] }} */
  342. const data = await res.json()
  343. return data.workflow_runs.some(({ name, conclusion }) => {
  344. return name === 'ci' && conclusion === 'success'
  345. })
  346. } catch {
  347. console.error('Failed to get CI status for current commit.')
  348. return false
  349. }
  350. }
  351. async function isInSyncWithRemote() {
  352. try {
  353. const branch = await getBranch()
  354. const res = await fetch(
  355. `https://api.github.com/repos/vuejs/core/commits/${branch}?per_page=1`,
  356. )
  357. const data = await res.json()
  358. if (data.sha === (await getSha())) {
  359. return true
  360. } else {
  361. /** @type {{ yes: boolean }} */
  362. const { yes } = await prompt({
  363. type: 'confirm',
  364. name: 'yes',
  365. message: pico.red(
  366. `Local HEAD is not up-to-date with remote. Are you sure you want to continue?`,
  367. ),
  368. })
  369. return yes
  370. }
  371. } catch {
  372. console.error(
  373. pico.red('Failed to check whether local HEAD is up-to-date with remote.'),
  374. )
  375. return false
  376. }
  377. }
  378. async function getSha() {
  379. return (await exec('git', ['rev-parse', 'HEAD'])).stdout
  380. }
  381. async function getBranch() {
  382. return (await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout
  383. }
  384. /**
  385. * @param {string} version
  386. * @param {(pkgName: string) => string} getNewPackageName
  387. */
  388. function updateVersions(version, getNewPackageName = keepThePackageName) {
  389. // 1. update root package.json
  390. updatePackage(path.resolve(__dirname, '..'), version, getNewPackageName)
  391. // 2. update all packages
  392. packages.forEach(p =>
  393. updatePackage(getPkgRoot(p), version, getNewPackageName),
  394. )
  395. }
  396. /**
  397. * @param {string} pkgRoot
  398. * @param {string} version
  399. * @param {(pkgName: string) => string} getNewPackageName
  400. */
  401. function updatePackage(pkgRoot, version, getNewPackageName) {
  402. const pkgPath = path.resolve(pkgRoot, 'package.json')
  403. /** @type {Package} */
  404. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  405. pkg.name = getNewPackageName(pkg.name)
  406. pkg.version = version
  407. if (isCanary) {
  408. updateDeps(pkg, 'dependencies', version, getNewPackageName)
  409. updateDeps(pkg, 'peerDependencies', version, getNewPackageName)
  410. }
  411. fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
  412. }
  413. /**
  414. * @param {Package} pkg
  415. * @param {'dependencies' | 'peerDependencies'} depType
  416. * @param {string} version
  417. * @param {(pkgName: string) => string} getNewPackageName
  418. */
  419. function updateDeps(pkg, depType, version, getNewPackageName) {
  420. const deps = pkg[depType]
  421. if (!deps) return
  422. Object.keys(deps).forEach(dep => {
  423. if (isCorePackage(dep)) {
  424. const newName = getNewPackageName(dep)
  425. const newVersion = newName === dep ? version : `npm:${newName}@${version}`
  426. console.log(
  427. pico.yellow(`${pkg.name} -> ${depType} -> ${dep}@${newVersion}`),
  428. )
  429. deps[dep] = newVersion
  430. }
  431. })
  432. }
  433. async function buildPackages() {
  434. step('\nBuilding all packages...')
  435. if (!skipBuild) {
  436. await run('pnpm', ['run', 'build', '--withTypes'])
  437. } else {
  438. console.log(`(skipped)`)
  439. }
  440. }
  441. /**
  442. * @param {string} version
  443. */
  444. async function publishPackages(version) {
  445. // publish packages
  446. step('\nPublishing packages...')
  447. const additionalPublishFlags = []
  448. if (isDryRun) {
  449. additionalPublishFlags.push('--dry-run')
  450. }
  451. if (isDryRun || skipGit || process.env.CI) {
  452. additionalPublishFlags.push('--no-git-checks')
  453. }
  454. // add provenance metadata when releasing from CI
  455. // canary release commits are not pushed therefore we don't need to add provenance
  456. // also skip provenance if not publishing to actual npm
  457. if (process.env.CI && !isCanary && !args.registry) {
  458. additionalPublishFlags.push('--provenance')
  459. }
  460. for (const pkg of packages) {
  461. await publishPackage(pkg, version, additionalPublishFlags)
  462. }
  463. }
  464. /**
  465. * @param {string} pkgName
  466. * @param {string} version
  467. * @param {ReadonlyArray<string>} additionalFlags
  468. */
  469. async function publishPackage(pkgName, version, additionalFlags) {
  470. if (skippedPackages.includes(pkgName)) {
  471. return
  472. }
  473. let releaseTag = null
  474. if (args.tag) {
  475. releaseTag = args.tag
  476. } else if (version.includes('alpha')) {
  477. releaseTag = 'alpha'
  478. } else if (version.includes('beta')) {
  479. releaseTag = 'beta'
  480. } else if (version.includes('rc')) {
  481. releaseTag = 'rc'
  482. }
  483. step(`Publishing ${pkgName}...`)
  484. try {
  485. // Don't change the package manager here as we rely on pnpm to handle
  486. // workspace:* deps
  487. await run(
  488. 'pnpm',
  489. [
  490. 'publish',
  491. ...(releaseTag ? ['--tag', releaseTag] : []),
  492. '--access',
  493. 'public',
  494. ...(args.registry ? ['--registry', args.registry] : []),
  495. ...additionalFlags,
  496. ],
  497. {
  498. cwd: getPkgRoot(pkgName),
  499. stdio: 'pipe',
  500. },
  501. )
  502. console.log(pico.green(`Successfully published ${pkgName}@${version}`))
  503. } catch (/** @type {any} */ e) {
  504. if (e.message?.match(/previously published/)) {
  505. console.log(pico.red(`Skipping already published: ${pkgName}`))
  506. } else {
  507. throw e
  508. }
  509. }
  510. }
  511. async function publishOnly() {
  512. const targetVersion = positionals[0]
  513. if (targetVersion) {
  514. updateVersions(targetVersion)
  515. }
  516. await buildPackages()
  517. await publishPackages(currentVersion)
  518. }
  519. const fnToRun = args.publishOnly ? publishOnly : main
  520. fnToRun().catch(err => {
  521. if (versionUpdated) {
  522. // revert to current version on failed releases
  523. updateVersions(currentVersion)
  524. }
  525. console.error(err)
  526. process.exit(1)
  527. })