vue3-core/scripts/release.js

382 lines
10 KiB
JavaScript
Raw Normal View History

2023-01-26 14:24:49 +08:00
// @ts-check
import minimist from 'minimist'
import fs from 'node:fs'
import path from 'node:path'
import chalk from 'chalk'
import semver from 'semver'
import enquirer from 'enquirer'
import execa from 'execa'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
2019-12-11 10:29:52 +08:00
2023-01-26 14:24:49 +08:00
const { prompt } = enquirer
const currentVersion = createRequire(import.meta.url)('../package.json').version
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const args = minimist(process.argv.slice(2))
const preId = args.preid || semver.prerelease(currentVersion)?.[0]
2019-12-11 10:29:52 +08:00
const isDryRun = args.dry
let skipTests = args.skipTests
2019-12-11 10:29:52 +08:00
const skipBuild = args.skipBuild
const isCanary = args.canary
const skipPrompts = args.skipPrompts || args.canary
const skipGit = args.skipGit || args.canary
2019-12-11 10:29:52 +08:00
const packages = fs
.readdirSync(path.resolve(__dirname, '../packages'))
.filter(p => !p.endsWith('.ts') && !p.startsWith('.'))
const isCorePackage = pkgName => {
if (!pkgName) return
if (pkgName === 'vue' || pkgName === '@vue/compat') {
return true
}
return (
pkgName.startsWith('@vue') &&
packages.includes(pkgName.replace(/^@vue\//, ''))
)
}
const renamePackageToCanary = pkgName => {
if (pkgName === 'vue') {
return '@vue/canary'
}
if (isCorePackage(pkgName)) {
return `${pkgName}-canary`
}
return pkgName
}
const keepThePackageName = pkgName => pkgName
const skippedPackages = []
2019-12-21 02:43:48 +08:00
2019-12-11 10:29:52 +08:00
const versionIncrements = [
'patch',
'minor',
'major',
...(preId ? ['prepatch', 'preminor', 'premajor', 'prerelease'] : [])
2019-12-11 10:29:52 +08:00
]
const inc = i => semver.inc(currentVersion, i, preId)
const run = (bin, args, opts = {}) =>
execa(bin, args, { stdio: 'inherit', ...opts })
2019-12-21 02:43:48 +08:00
const dryRun = (bin, args, opts = {}) =>
console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts)
const runIfNotDry = isDryRun ? dryRun : run
2019-12-11 10:29:52 +08:00
const getPkgRoot = pkg => path.resolve(__dirname, '../packages/' + pkg)
2019-12-21 02:43:48 +08:00
const step = msg => console.log(chalk.cyan(msg))
2019-12-11 10:29:52 +08:00
async function main() {
let targetVersion = args._[0]
if (isCanary) {
// The canary version string format is `3.yyyyMMdd.0`.
// Use UTC date so that it's consistent across CI and maintainers' machines
const date = new Date()
const yyyy = date.getUTCFullYear()
const MM = (date.getUTCMonth() + 1).toString().padStart(2, '0')
const dd = date.getUTCDate().toString().padStart(2, '0')
const major = semver.major(currentVersion)
const minor = `${yyyy}${MM}${dd}`
const patch = 0
let canaryVersion = `${major}.${minor}.${patch}`
// check the registry to avoid version collision
// in case we need to publish more than one canary versions in a day
try {
const pkgName = renamePackageToCanary('vue')
const { stdout } = await run(
'pnpm',
['view', `${pkgName}@~${canaryVersion}`, 'version', '--json'],
{ stdio: 'pipe' }
)
let versions = JSON.parse(stdout)
versions = Array.isArray(versions) ? versions : [versions]
const latestSameDayPatch = /** @type {string} */ (
semver.maxSatisfying(versions, `~${canaryVersion}`)
)
canaryVersion = /** @type {string} */ (
semver.inc(latestSameDayPatch, 'patch')
)
} catch (e) {
if (/E404/.test(e.message)) {
// the first patch version on that day
} else {
throw e
}
}
targetVersion = canaryVersion
}
2019-12-11 10:29:52 +08:00
if (!targetVersion) {
// no explicit version, offer suggestions
2023-01-26 14:24:49 +08:00
// @ts-ignore
2019-12-11 10:29:52 +08:00
const { release } = await prompt({
type: 'select',
name: 'release',
message: 'Select release type',
choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom'])
})
if (release === 'custom') {
2023-01-26 14:24:49 +08:00
const result = await prompt({
type: 'input',
name: 'version',
message: 'Input custom version',
initial: currentVersion
})
// @ts-ignore
targetVersion = result.version
2019-12-11 10:29:52 +08:00
} else {
targetVersion = release.match(/\((.*)\)/)[1]
}
}
if (!semver.valid(targetVersion)) {
throw new Error(`invalid target version: ${targetVersion}`)
}
if (skipPrompts) {
step(
isCanary
? `Releasing canary version v${targetVersion}...`
: `Releasing v${targetVersion}...`
)
} else {
// @ts-ignore
const { yes: confirmRelease } = await prompt({
type: 'confirm',
name: 'yes',
message: `Releasing v${targetVersion}. Confirm?`
})
if (!confirmRelease) {
return
}
}
if (!skipTests) {
step('Checking CI status for HEAD...')
let isCIPassed = await getCIResult()
skipTests ||= isCIPassed
if (isCIPassed && !skipPrompts) {
// @ts-ignore
const { yes: promptSkipTests } = await prompt({
type: 'confirm',
name: 'yes',
message: `CI for this commit passed. Skip local tests?`
})
skipTests = promptSkipTests
}
}
if (!skipTests) {
step('\nRunning tests...')
if (!isDryRun) {
await run('pnpm', ['test', 'run'])
} else {
console.log(`Skipped (dry run)`)
}
2019-12-21 02:43:48 +08:00
} else {
step('Tests skipped.')
2019-12-11 10:29:52 +08:00
}
// update all package versions and inter-dependencies
2019-12-21 02:43:48 +08:00
step('\nUpdating cross dependencies...')
updateVersions(
targetVersion,
isCanary ? renamePackageToCanary : keepThePackageName
)
2019-12-11 10:29:52 +08:00
// build all packages with types
2019-12-21 02:43:48 +08:00
step('\nBuilding all packages...')
if (!skipBuild && !isDryRun) {
await run('pnpm', ['run', 'build'])
step('\nBuilding and testing types...')
await run('pnpm', ['test-dts'])
2019-12-21 02:43:48 +08:00
} else {
console.log(`(skipped)`)
2019-12-11 10:29:52 +08:00
}
// generate changelog
step('\nGenerating changelog...')
2021-11-02 14:31:38 +08:00
await run(`pnpm`, ['run', 'changelog'])
if (!skipPrompts) {
// @ts-ignore
const { yes: changelogOk } = await prompt({
type: 'confirm',
name: 'yes',
message: `Changelog generated. Does it look good?`
})
if (!changelogOk) {
return
}
}
// update pnpm-lock.yaml
// skipped during canary release because the package names changed and installing with `workspace:*` would fail
if (!isCanary) {
step('\nUpdating lockfile...')
await run(`pnpm`, ['install', '--prefer-offline'])
}
if (!skipGit) {
const { stdout } = await run('git', ['diff'], { stdio: 'pipe' })
if (stdout) {
step('\nCommitting changes...')
await runIfNotDry('git', ['add', '-A'])
await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`])
} else {
console.log('No changes to commit.')
}
2019-12-21 02:43:48 +08:00
}
// publish packages
step('\nPublishing packages...')
for (const pkg of packages) {
await publishPackage(pkg, targetVersion)
2019-12-21 02:43:48 +08:00
}
// push to GitHub
if (!skipGit) {
step('\nPushing to GitHub...')
await runIfNotDry('git', ['tag', `v${targetVersion}`])
await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
await runIfNotDry('git', ['push'])
}
2019-12-21 02:43:48 +08:00
if (isDryRun) {
console.log(`\nDry run finished - run git diff to see package changes.`)
}
2019-12-11 10:29:52 +08:00
2019-12-21 02:43:48 +08:00
if (skippedPackages.length) {
console.log(
chalk.yellow(
`The following packages are skipped and NOT published:\n- ${skippedPackages.join(
'\n- '
)}`
)
)
2019-12-11 10:29:52 +08:00
}
2019-12-21 02:43:48 +08:00
console.log()
2019-12-11 10:29:52 +08:00
}
async function getCIResult() {
try {
const { stdout: sha } = await execa('git', ['rev-parse', 'HEAD'])
const res = await fetch(
`https://api.github.com/repos/vuejs/core/actions/runs?head_sha=${sha}` +
`&status=success&exclude_pull_requests=true`
)
const data = await res.json()
return data.workflow_runs.length > 0
} catch (e) {
return false
}
}
function updateVersions(version, getNewPackageName = keepThePackageName) {
2019-12-11 10:29:52 +08:00
// 1. update root package.json
updatePackage(path.resolve(__dirname, '..'), version, getNewPackageName)
2019-12-11 10:29:52 +08:00
// 2. update all packages
packages.forEach(p =>
updatePackage(getPkgRoot(p), version, getNewPackageName)
)
2019-12-11 10:29:52 +08:00
}
function updatePackage(pkgRoot, version, getNewPackageName) {
2019-12-21 02:43:48 +08:00
const pkgPath = path.resolve(pkgRoot, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
pkg.name = getNewPackageName(pkg.name)
2019-12-11 10:29:52 +08:00
pkg.version = version
updateDeps(pkg, 'dependencies', version, getNewPackageName)
updateDeps(pkg, 'peerDependencies', version, getNewPackageName)
2019-12-11 10:29:52 +08:00
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
}
function updateDeps(pkg, depType, version, getNewPackageName) {
2019-12-21 02:43:48 +08:00
const deps = pkg[depType]
2019-12-18 10:51:41 +08:00
if (!deps) return
Object.keys(deps).forEach(dep => {
if (deps[dep] === 'workspace:*') {
return
}
if (isCorePackage(dep)) {
const newName = getNewPackageName(dep)
const newVersion = newName === dep ? version : `npm:${newName}@${version}`
2019-12-21 02:43:48 +08:00
console.log(
chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${newVersion}`)
2019-12-21 02:43:48 +08:00
)
deps[dep] = newVersion
2019-12-18 10:51:41 +08:00
}
})
}
async function publishPackage(pkgName, version) {
2020-01-03 07:08:42 +08:00
if (skippedPackages.includes(pkgName)) {
2019-12-21 02:43:48 +08:00
return
}
2019-12-11 10:29:52 +08:00
const pkgRoot = getPkgRoot(pkgName)
2019-12-21 02:43:48 +08:00
const pkgPath = path.resolve(pkgRoot, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
if (pkg.private) {
return
}
let releaseTag = null
if (args.tag) {
releaseTag = args.tag
} else if (version.includes('alpha')) {
releaseTag = 'alpha'
} else if (version.includes('beta')) {
releaseTag = 'beta'
} else if (version.includes('rc')) {
releaseTag = 'rc'
}
2020-01-14 06:53:54 +08:00
step(`Publishing ${pkgName}...`)
2019-12-21 02:43:48 +08:00
try {
await runIfNotDry(
2021-10-09 02:23:30 +08:00
// note: use of yarn is intentional here as we rely on its publishing
// behavior.
2019-12-21 02:43:48 +08:00
'yarn',
[
'publish',
'--new-version',
version,
2020-01-22 23:51:17 +08:00
...(releaseTag ? ['--tag', releaseTag] : []),
2019-12-21 02:43:48 +08:00
'--access',
'public',
...(skipGit ? ['--no-commit-hooks', '--no-git-tag-version'] : [])
2019-12-21 02:43:48 +08:00
],
{
cwd: pkgRoot,
stdio: 'pipe'
}
)
console.log(chalk.green(`Successfully published ${pkgName}@${version}`))
} catch (e) {
2019-12-21 02:43:48 +08:00
if (e.stderr.match(/previously published/)) {
console.log(chalk.red(`Skipping already published: ${pkgName}`))
} else {
throw e
}
2019-12-11 10:29:52 +08:00
}
}
main().catch(err => {
updateVersions(currentVersion)
2019-12-11 10:29:52 +08:00
console.error(err)
process.exit(1)
2019-12-11 10:29:52 +08:00
})