From 23a29a24f4047e81b12e0f622a7d7d3dba5e9345 Mon Sep 17 00:00:00 2001 From: Saeed M Rad Date: Sun, 1 May 2022 13:11:52 +0430 Subject: [PATCH] Improve error handling in prepack script (#209) --- scripts/prepack.js | 59 ++++++++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 20 deletions(-) diff --git a/scripts/prepack.js b/scripts/prepack.js index 5983a3c..1baa88f 100755 --- a/scripts/prepack.js +++ b/scripts/prepack.js @@ -1,34 +1,36 @@ #!/usr/bin/env node import fs from 'node:fs/promises'; +import process from 'node:process'; import { execaCommand } from 'execa'; -async function getMetadata () { - const metadata = JSON.parse(await fs.readFile('package.json', 'utf8')); - +/** + * @param {Record} packageMeta + */ +function processPackageJson (packageMeta) { // Cleanup package.json - delete metadata.scripts; - delete metadata.devDependencies; - delete metadata.engines.pnpm; - delete metadata.imports['#test/*']; - delete metadata.packageManager; - delete metadata.pnpm; - - for (const subpath of Object.keys(metadata.exports ?? {})) { - delete metadata.exports[subpath].docs; + delete packageMeta.scripts; + delete packageMeta.devDependencies; + delete packageMeta.engines.pnpm; + delete packageMeta.imports['#test/*']; + delete packageMeta.packageManager; + delete packageMeta.pnpm; + + const exports = packageMeta.exports ?? {}; + + for (const subpath of Object.keys(exports)) { + delete exports[subpath].docs; } - return metadata; + return packageMeta; } -const metadata = await getMetadata(); - /** @type {import('execa').Options} */ const options = { stdio: 'inherit', }; console.log('pnpm install'); -await execaCommand('pnpm install', options); +await execaCommand('pnpm install --prod=false', options); console.log('pnpm run build'); await execaCommand('pnpm run build', options); @@ -39,8 +41,25 @@ await execaCommand('pnpm run lint', options); console.log('pnpm run test'); await execaCommand('pnpm run test', options); -console.log('mv package.json …'); -await fs.rename('package.json', '.package.dev.json'); +const packageJson = await fs.readFile('package.json', 'utf8'); +const newPackageJson = JSON.stringify(processPackageJson(JSON.parse(packageJson))); + +try { + console.log('mv package.json …'); + await fs.rename('package.json', '.package.dev.json'); -console.log('new package.json'); -await fs.writeFile('package.json', JSON.stringify(metadata)); + console.log('new package.json'); + await fs.writeFile('package.json', newPackageJson); +} catch (error) { + console.error(error); + + console.error('# Reverting changes to package.json'); + await fs.writeFile('package.json', packageJson); + + console.error('rm …'); + await fs.rm('.package.dev.json', { + force: true, + }); + + process.exit(1); +}