release.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. const versions = JSON.parse(stdout)
  83. const latestSameDayPatch = /** @type {string} */ (
  84. semver.maxSatisfying(versions, `~${canaryVersion}`)
  85. )
  86. canaryVersion = /** @type {string} */ (
  87. semver.inc(latestSameDayPatch, 'patch')
  88. )
  89. } catch (e) {}
  90. targetVersion = canaryVersion
  91. }
  92. if (!targetVersion) {
  93. // no explicit version, offer suggestions
  94. // @ts-ignore
  95. const { release } = await prompt({
  96. type: 'select',
  97. name: 'release',
  98. message: 'Select release type',
  99. choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom'])
  100. })
  101. if (release === 'custom') {
  102. const result = await prompt({
  103. type: 'input',
  104. name: 'version',
  105. message: 'Input custom version',
  106. initial: currentVersion
  107. })
  108. // @ts-ignore
  109. targetVersion = result.version
  110. } else {
  111. targetVersion = release.match(/\((.*)\)/)[1]
  112. }
  113. }
  114. if (!semver.valid(targetVersion)) {
  115. throw new Error(`invalid target version: ${targetVersion}`)
  116. }
  117. if (skipPrompts) {
  118. step(
  119. isCanary
  120. ? `Releasing canary version v${targetVersion}...`
  121. : `Releasing v${targetVersion}...`
  122. )
  123. } else {
  124. // @ts-ignore
  125. const { yes: confirmRelease } = await prompt({
  126. type: 'confirm',
  127. name: 'yes',
  128. message: `Releasing v${targetVersion}. Confirm?`
  129. })
  130. if (!confirmRelease) {
  131. return
  132. }
  133. }
  134. if (!skipTests) {
  135. step('Checking CI status for HEAD...')
  136. let isCIPassed = await getCIResult()
  137. skipTests ||= isCIPassed
  138. if (isCIPassed && !skipPrompts) {
  139. // @ts-ignore
  140. const { yes: promptSkipTests } = await prompt({
  141. type: 'confirm',
  142. name: 'yes',
  143. message: `CI for this commit passed. Skip local tests?`
  144. })
  145. skipTests = promptSkipTests
  146. }
  147. }
  148. if (!skipTests) {
  149. step('\nRunning tests...')
  150. if (!isDryRun) {
  151. await run('pnpm', ['test', 'run'])
  152. } else {
  153. console.log(`Skipped (dry run)`)
  154. }
  155. } else {
  156. step('Tests skipped.')
  157. }
  158. // update all package versions and inter-dependencies
  159. step('\nUpdating cross dependencies...')
  160. updateVersions(
  161. targetVersion,
  162. isCanary ? renamePackageToCanary : keepThePackageName
  163. )
  164. // build all packages with types
  165. step('\nBuilding all packages...')
  166. if (!skipBuild && !isDryRun) {
  167. await run('pnpm', ['run', 'build'])
  168. step('\nBuilding and testing types...')
  169. await run('pnpm', ['test-dts'])
  170. } else {
  171. console.log(`(skipped)`)
  172. }
  173. // generate changelog
  174. step('\nGenerating changelog...')
  175. await run(`pnpm`, ['run', 'changelog'])
  176. // update pnpm-lock.yaml
  177. // skipped during canary release because the package names changed and installing with `workspace:*` would fail
  178. if (!isCanary) {
  179. step('\nUpdating lockfile...')
  180. await run(`pnpm`, ['install', '--prefer-offline'])
  181. }
  182. if (!skipGit) {
  183. const { stdout } = await run('git', ['diff'], { stdio: 'pipe' })
  184. if (stdout) {
  185. step('\nCommitting changes...')
  186. await runIfNotDry('git', ['add', '-A'])
  187. await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`])
  188. } else {
  189. console.log('No changes to commit.')
  190. }
  191. }
  192. // publish packages
  193. step('\nPublishing packages...')
  194. for (const pkg of packages) {
  195. await publishPackage(pkg, targetVersion)
  196. }
  197. // push to GitHub
  198. if (!skipGit) {
  199. step('\nPushing to GitHub...')
  200. await runIfNotDry('git', ['tag', `v${targetVersion}`])
  201. await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
  202. await runIfNotDry('git', ['push'])
  203. }
  204. if (isDryRun) {
  205. console.log(`\nDry run finished - run git diff to see package changes.`)
  206. }
  207. if (skippedPackages.length) {
  208. console.log(
  209. chalk.yellow(
  210. `The following packages are skipped and NOT published:\n- ${skippedPackages.join(
  211. '\n- '
  212. )}`
  213. )
  214. )
  215. }
  216. console.log()
  217. }
  218. async function getCIResult() {
  219. try {
  220. const { stdout: sha } = await execa('git', ['rev-parse', 'HEAD'])
  221. const res = await fetch(
  222. `https://api.github.com/repos/vuejs/core/actions/runs?head_sha=${sha}` +
  223. `&status=success&exclude_pull_requests=true`
  224. )
  225. const data = await res.json()
  226. return data.workflow_runs.length > 0
  227. } catch (e) {
  228. return false
  229. }
  230. }
  231. function updateVersions(version, getNewPackageName = keepThePackageName) {
  232. // 1. update root package.json
  233. updatePackage(path.resolve(__dirname, '..'), version, getNewPackageName)
  234. // 2. update all packages
  235. packages.forEach(p =>
  236. updatePackage(getPkgRoot(p), version, getNewPackageName)
  237. )
  238. }
  239. function updatePackage(pkgRoot, version, getNewPackageName) {
  240. const pkgPath = path.resolve(pkgRoot, 'package.json')
  241. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  242. pkg.name = getNewPackageName(pkg.name)
  243. pkg.version = version
  244. updateDeps(pkg, 'dependencies', version, getNewPackageName)
  245. updateDeps(pkg, 'peerDependencies', version, getNewPackageName)
  246. fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
  247. }
  248. function updateDeps(pkg, depType, version, getNewPackageName) {
  249. const deps = pkg[depType]
  250. if (!deps) return
  251. Object.keys(deps).forEach(dep => {
  252. if (deps[dep] === 'workspace:*') {
  253. return
  254. }
  255. if (isCorePackage(dep)) {
  256. const newName = getNewPackageName(dep)
  257. const newVersion = newName === dep ? version : `npm:${newName}@${version}`
  258. console.log(
  259. chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${newVersion}`)
  260. )
  261. deps[dep] = newVersion
  262. }
  263. })
  264. }
  265. async function publishPackage(pkgName, version) {
  266. if (skippedPackages.includes(pkgName)) {
  267. return
  268. }
  269. const pkgRoot = getPkgRoot(pkgName)
  270. const pkgPath = path.resolve(pkgRoot, 'package.json')
  271. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
  272. if (pkg.private) {
  273. return
  274. }
  275. let releaseTag = null
  276. if (args.tag) {
  277. releaseTag = args.tag
  278. } else if (version.includes('alpha')) {
  279. releaseTag = 'alpha'
  280. } else if (version.includes('beta')) {
  281. releaseTag = 'beta'
  282. } else if (version.includes('rc')) {
  283. releaseTag = 'rc'
  284. }
  285. step(`Publishing ${pkgName}...`)
  286. try {
  287. await runIfNotDry(
  288. // note: use of yarn is intentional here as we rely on its publishing
  289. // behavior.
  290. 'yarn',
  291. [
  292. 'publish',
  293. '--new-version',
  294. version,
  295. ...(releaseTag ? ['--tag', releaseTag] : []),
  296. '--access',
  297. 'public',
  298. ...(skipGit ? ['--no-commit-hooks', '--no-git-tag-version'] : [])
  299. ],
  300. {
  301. cwd: pkgRoot,
  302. stdio: 'pipe'
  303. }
  304. )
  305. console.log(chalk.green(`Successfully published ${pkgName}@${version}`))
  306. } catch (e) {
  307. if (e.stderr.match(/previously published/)) {
  308. console.log(chalk.red(`Skipping already published: ${pkgName}`))
  309. } else {
  310. throw e
  311. }
  312. }
  313. }
  314. main().catch(err => {
  315. updateVersions(currentVersion)
  316. console.error(err)
  317. })