release.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // @ts-check
  2. import minimist from 'minimist'
  3. import fs from 'node:fs'
  4. import path from 'node:path'
  5. import chalk from 'chalk'
  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. const { prompt } = enquirer
  12. const currentVersion = createRequire(import.meta.url)('../package.json').version
  13. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  14. const args = minimist(process.argv.slice(2))
  15. const preId = args.preid || semver.prerelease(currentVersion)?.[0]
  16. const isDryRun = args.dry
  17. let skipTests = args.skipTests
  18. const skipBuild = args.skipBuild
  19. const isCanary = args.canary
  20. const skipPrompts = args.skipPrompts || args.canary
  21. const skipGit = args.skipGit || args.canary
  22. const packages = fs
  23. .readdirSync(path.resolve(__dirname, '../packages'))
  24. .filter(p => !p.endsWith('.ts') && !p.startsWith('.'))
  25. const isCorePackage = pkgName => {
  26. if (!pkgName) return
  27. if (pkgName === 'vue' || pkgName === '@vue/compat') {
  28. return true
  29. }
  30. return (
  31. pkgName.startsWith('@vue') &&
  32. packages.includes(pkgName.replace(/^@vue\//, ''))
  33. )
  34. }
  35. const renamePackageToCanary = pkgName => {
  36. if (pkgName === 'vue') {
  37. return '@vue/canary'
  38. }
  39. if (isCorePackage(pkgName)) {
  40. return `${pkgName}-canary`
  41. }
  42. return pkgName
  43. }
  44. const keepThePackageName = pkgName => pkgName
  45. const skippedPackages = []
  46. const versionIncrements = [
  47. 'patch',
  48. 'minor',
  49. 'major',
  50. ...(preId ? ['prepatch', 'preminor', 'premajor', 'prerelease'] : [])
  51. ]
  52. const inc = i => semver.inc(currentVersion, i, preId)
  53. const run = (bin, args, opts = {}) =>
  54. execa(bin, args, { stdio: 'inherit', ...opts })
  55. const dryRun = (bin, args, opts = {}) =>
  56. console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts)
  57. const runIfNotDry = isDryRun ? dryRun : run
  58. const getPkgRoot = pkg => path.resolve(__dirname, '../packages/' + pkg)
  59. const step = msg => console.log(chalk.cyan(msg))
  60. async function main() {
  61. let targetVersion = args._[0]
  62. if (isCanary) {
  63. // The canary version string format is `3.yyyyMMdd.0`.
  64. // Use UTC date so that it's consistent across CI and maintainers' machines
  65. const date = new Date()
  66. const yyyy = date.getUTCFullYear()
  67. const MM = (date.getUTCMonth() + 1).toString().padStart(2, '0')
  68. const dd = date.getUTCDate().toString().padStart(2, '0')
  69. const major = semver.major(currentVersion)
  70. const minor = `${yyyy}${MM}${dd}`
  71. const patch = 0
  72. let canaryVersion = `${major}.${minor}.${patch}`
  73. // check the registry to avoid version collision
  74. // in case we need to publish more than one canary versions in a day
  75. try {
  76. const pkgName = renamePackageToCanary('vue')
  77. const { stdout } = await run(
  78. 'pnpm',
  79. ['view', `${pkgName}@~${canaryVersion}`, 'version', '--json'],
  80. { stdio: 'pipe' }
  81. )
  82. let versions = JSON.parse(stdout)
  83. versions = Array.isArray(versions) ? versions : [versions]
  84. const latestSameDayPatch = /** @type {string} */ (
  85. semver.maxSatisfying(versions, `~${canaryVersion}`)
  86. )
  87. canaryVersion = /** @type {string} */ (
  88. semver.inc(latestSameDayPatch, 'patch')
  89. )
  90. } catch (e) {
  91. if (/E404/.test(e.message)) {
  92. // the first patch version on that day
  93. } else {
  94. throw e
  95. }
  96. }
  97. targetVersion = canaryVersion
  98. }
  99. if (!targetVersion) {
  100. // no explicit version, offer suggestions
  101. // @ts-ignore
  102. const { release } = await prompt({
  103. type: 'select',
  104. name: 'release',
  105. message: 'Select release type',
  106. choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom'])
  107. })
  108. if (release === 'custom') {
  109. const result = await prompt({
  110. type: 'input',
  111. name: 'version',
  112. message: 'Input custom version',
  113. initial: currentVersion
  114. })
  115. // @ts-ignore
  116. targetVersion = result.version
  117. } else {
  118. targetVersion = release.match(/\((.*)\)/)[1]
  119. }
  120. }
  121. if (!semver.valid(targetVersion)) {
  122. throw new Error(`invalid target version: ${targetVersion}`)
  123. }
  124. if (skipPrompts) {
  125. step(
  126. isCanary
  127. ? `Releasing canary version v${targetVersion}...`
  128. : `Releasing v${targetVersion}...`
  129. )
  130. } else {
  131. // @ts-ignore
  132. const { yes: confirmRelease } = await prompt({
  133. type: 'confirm',
  134. name: 'yes',
  135. message: `Releasing v${targetVersion}. Confirm?`
  136. })
  137. if (!confirmRelease) {
  138. return
  139. }
  140. }
  141. if (!skipTests) {
  142. step('Checking CI status for HEAD...')
  143. let isCIPassed = await getCIResult()
  144. skipTests ||= isCIPassed
  145. if (isCIPassed && !skipPrompts) {
  146. // @ts-ignore
  147. const { yes: promptSkipTests } = await prompt({
  148. type: 'confirm',
  149. name: 'yes',
  150. message: `CI for this commit passed. Skip local tests?`
  151. })
  152. skipTests = promptSkipTests
  153. }
  154. }
  155. if (!skipTests) {
  156. step('\nRunning tests...')
  157. if (!isDryRun) {
  158. await run('pnpm', ['test', 'run'])
  159. } else {
  160. console.log(`Skipped (dry run)`)
  161. }
  162. } else {
  163. step('Tests skipped.')
  164. }
  165. // update all package versions and inter-dependencies
  166. step('\nUpdating cross dependencies...')
  167. updateVersions(
  168. targetVersion,
  169. isCanary ? renamePackageToCanary : keepThePackageName
  170. )
  171. // build all packages with types
  172. step('\nBuilding all packages...')
  173. if (!skipBuild && !isDryRun) {
  174. await run('pnpm', ['run', 'build'])
  175. step('\nBuilding and testing types...')
  176. await run('pnpm', ['test-dts'])
  177. } else {
  178. console.log(`(skipped)`)
  179. }
  180. // generate changelog
  181. step('\nGenerating changelog...')
  182. await run(`pnpm`, ['run', 'changelog'])
  183. if (!skipPrompts) {
  184. // @ts-ignore
  185. const { yes: changelogOk } = await prompt({
  186. type: 'confirm',
  187. name: 'yes',
  188. message: `Changelog generated. Does it look good?`
  189. })
  190. if (!changelogOk) {
  191. return
  192. }
  193. }
  194. // update pnpm-lock.yaml
  195. // skipped during canary release because the package names changed and installing with `workspace:*` would fail
  196. if (!isCanary) {
  197. step('\nUpdating lockfile...')
  198. await run(`pnpm`, ['install', '--prefer-offline'])
  199. }
  200. if (!skipGit) {
  201. const { stdout } = await run('git', ['diff'], { stdio: 'pipe' })
  202. if (stdout) {
  203. step('\nCommitting changes...')
  204. await runIfNotDry('git', ['add', '-A'])
  205. await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`])
  206. } else {
  207. console.log('No changes to commit.')
  208. }
  209. }
  210. // publish packages
  211. step('\nPublishing packages...')
  212. for (const pkg of packages) {
  213. await publishPackage(pkg, targetVersion)
  214. }
  215. // push to GitHub
  216. if (!skipGit) {
  217. step('\nPushing to GitHub...')
  218. await runIfNotDry('git', ['tag', `v${targetVersion}`])
  219. await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
  220. await runIfNotDry('git', ['push'])
  221. }
  222. if (isDryRun) {
  223. console.log(`\nDry run finished - run git diff to see package changes.`)
  224. }
  225. if (skippedPackages.length) {
  226. console.log(
  227. chalk.yellow(
  228. `The following packages are skipped and NOT published:\n- ${skippedPackages.join(
  229. '\n- '
  230. )}`
  231. )
  232. )
  233. }
  234. console.log()
  235. }
  236. async function getCIResult() {
  237. try {
  238. const { stdout: sha } = await execa('git', ['rev-parse', 'HEAD'])
  239. const res = await fetch(
  240. `https://api.github.com/repos/vuejs/core/actions/runs?head_sha=${sha}` +
  241. `&status=success&exclude_pull_requests=true`
  242. )
  243. const data = await res.json()
  244. return data.workflow_runs.length > 0
  245. } catch (e) {
  246. return false
  247. }
  248. }
  249. function updateVersions(version, getNewPackageName = keepThePackageName) {
  250. // 1. update root package.json
  251. updatePackage(path.resolve(__dirname, '..'), version, getNewPackageName)
  252. // 2. update all packages
  253. packages.forEach(p =>
  254. updatePackage(getPkgRoot(p), version, getNewPackageName)
  255. )
  256. }
  257. function updatePackage(pkgRoot, version, getNewPackageName) {
  258. const pkgPath = path.resolve(pkgRoot, 'package.json')
  259. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  260. pkg.name = getNewPackageName(pkg.name)
  261. pkg.version = version
  262. updateDeps(pkg, 'dependencies', version, getNewPackageName)
  263. updateDeps(pkg, 'peerDependencies', version, getNewPackageName)
  264. fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
  265. }
  266. function updateDeps(pkg, depType, version, getNewPackageName) {
  267. const deps = pkg[depType]
  268. if (!deps) return
  269. Object.keys(deps).forEach(dep => {
  270. if (deps[dep] === 'workspace:*') {
  271. return
  272. }
  273. if (isCorePackage(dep)) {
  274. const newName = getNewPackageName(dep)
  275. const newVersion = newName === dep ? version : `npm:${newName}@${version}`
  276. console.log(
  277. chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${newVersion}`)
  278. )
  279. deps[dep] = newVersion
  280. }
  281. })
  282. }
  283. async function publishPackage(pkgName, version) {
  284. if (skippedPackages.includes(pkgName)) {
  285. return
  286. }
  287. const pkgRoot = getPkgRoot(pkgName)
  288. const pkgPath = path.resolve(pkgRoot, 'package.json')
  289. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  290. if (pkg.private) {
  291. return
  292. }
  293. let releaseTag = null
  294. if (args.tag) {
  295. releaseTag = args.tag
  296. } else if (version.includes('alpha')) {
  297. releaseTag = 'alpha'
  298. } else if (version.includes('beta')) {
  299. releaseTag = 'beta'
  300. } else if (version.includes('rc')) {
  301. releaseTag = 'rc'
  302. }
  303. step(`Publishing ${pkgName}...`)
  304. try {
  305. await runIfNotDry(
  306. // note: use of yarn is intentional here as we rely on its publishing
  307. // behavior.
  308. 'yarn',
  309. [
  310. 'publish',
  311. '--new-version',
  312. version,
  313. ...(releaseTag ? ['--tag', releaseTag] : []),
  314. '--access',
  315. 'public',
  316. ...(skipGit ? ['--no-commit-hooks', '--no-git-tag-version'] : [])
  317. ],
  318. {
  319. cwd: pkgRoot,
  320. stdio: 'pipe'
  321. }
  322. )
  323. console.log(chalk.green(`Successfully published ${pkgName}@${version}`))
  324. } catch (e) {
  325. if (e.stderr.match(/previously published/)) {
  326. console.log(chalk.red(`Skipping already published: ${pkgName}`))
  327. } else {
  328. throw e
  329. }
  330. }
  331. }
  332. main().catch(err => {
  333. updateVersions(currentVersion)
  334. console.error(err)
  335. process.exit(1)
  336. })