release.js 14 KB

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