2
0

release.js 14 KB

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