release.js 12 KB

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