/* oxlint-disable no-console */ import { spawn } from 'node:child_process' import { access, readFile, stat, writeFile } from 'node:fs/promises' import path from 'node:path' import { getPackageManager, getUpdateCommand } from './packageManager.js' import { checkTaobaoRegistry } from './registry.js' import { updatePackages } from './updatePackage.js' const runCommand = (command: string, cwd: string): Promise => new Promise((resolve, reject) => { const child = spawn(command, { shell: true, stdio: 'inherit', cwd }) child.on('close', (code) => { if (code === 0) resolve() else reject(new Error(`"${command}" exited with code ${code}`)) }) }) /** * Ensure the target is an existing directory * * @param dir - The resolved target directory / 解析后的目标目录 */ const ensureDirectory = async (dir: string): Promise => { const stats = await stat(dir).catch(() => null) if (!stats) throw new Error(`Target directory "${dir}" does not exist`) if (!stats.isDirectory()) throw new Error(`Target path "${dir}" is not a directory`) } /** * Update the dependencies of the VuePress project at `targetDir` * * The package.json is modified, and the install / update commands as well as * the package manager and registry probes all run inside the target directory. * * 更新 `targetDir` 下 VuePress 项目的依赖。package.json 会被修改,安装 / 升级命令以及包管理器、registry * 探测都在目标目录内执行。 * * @param targetDir - Directory of the VuePress project, relative to `cwd` / * VuePress 项目目录,相对于 `cwd` */ export const updateProject = async (targetDir = ''): Promise => { console.log('Bumping deps...') const dir = path.resolve(process.cwd(), targetDir) const packageJSON = path.resolve(dir, 'package.json') await ensureDirectory(dir) try { await access(packageJSON) } catch { throw new Error(`No package.json found in "${dir}"`) } const packageManager = getPackageManager(dir) checkTaobaoRegistry(packageManager, dir) const content = await readFile(packageJSON, 'utf-8') const packageJSONContent = JSON.parse(content) as Record & { dependencies?: Record devDependencies?: Record } await Promise.all([ packageJSONContent.dependencies ? updatePackages(packageManager, packageJSONContent.dependencies, dir) : Promise.resolve(), packageJSONContent.devDependencies ? updatePackages(packageManager, packageJSONContent.devDependencies, dir) : Promise.resolve(), ]) await writeFile( packageJSON, `${JSON.stringify(packageJSONContent, null, 2)}\n`, ) console.info('Installing deps...') await runCommand(`${packageManager} install`, dir) console.info('Upgrading deps...') await runCommand(getUpdateCommand(packageManager), dir) }