release.js 14 KB

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