release.js 15 KB

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