From 253c0cc1edc5806d2e7ebacae955b8ea5d9461cd Mon Sep 17 00:00:00 2001 From: Superchupu <53496941+SuperchupuDev@users.noreply.github.com> Date: Thu, 17 Oct 2024 08:56:51 +0200 Subject: [PATCH] refactor: replace `chalk` and `fs-extra` (#53) --- lib/build.ts | 51 +++++++++++++++++++++++++------------------ lib/index.ts | 9 ++++---- lib/log.ts | 13 +++++++---- lib/utils.ts | 17 ++++++++------- package.json | 6 ++--- scripts/test_patch.sh | 2 +- yarn.lock | 51 +++++++++---------------------------------- 7 files changed, 66 insertions(+), 83 deletions(-) diff --git a/lib/build.ts b/lib/build.ts index e6d6124c..62b36847 100644 --- a/lib/build.ts +++ b/lib/build.ts @@ -1,6 +1,7 @@ import { createGunzip } from 'zlib'; import crypto from 'crypto'; -import fs from 'fs-extra'; +import { createReadStream, existsSync } from 'fs'; +import { cp, mkdir, readFile, rm, writeFile } from 'fs/promises'; import os from 'os'; import path from 'path'; import { pipeline } from 'stream'; @@ -88,18 +89,20 @@ async function tarFetch(nodeVersion: string) { const archivePath = path.join(nodeArchivePath, tarName); const hashPath = path.join(nodeArchivePath, `${tarName}.sha256sum`); - if (fs.existsSync(hashPath) && fs.existsSync(archivePath)) { + if (existsSync(hashPath) && existsSync(archivePath)) { return; } - await fs.remove(hashPath).catch(() => undefined); - await fs.remove(archivePath).catch(() => undefined); + await rm(hashPath, { recursive: true, force: true }).catch(() => undefined); + await rm(archivePath, { recursive: true, force: true }).catch( + () => undefined + ); await downloadUrl(`${distUrl}/SHASUMS256.txt`, hashPath); - await fs.writeFile( + await writeFile( hashPath, - (await fs.readFile(hashPath, 'utf8')) + (await readFile(hashPath, 'utf8')) .split('\n') .filter((l) => l.includes(tarName))[0] ); @@ -113,22 +116,25 @@ async function tarExtract(nodeVersion: string, suppressTarOutput: boolean) { const tarName = `node-${nodeVersion}.tar.gz`; const expectedHash = ( - await fs.readFile( - path.join(nodeArchivePath, `${tarName}.sha256sum`), - 'utf8' - ) + await readFile(path.join(nodeArchivePath, `${tarName}.sha256sum`), 'utf8') ).split(' ')[0]; const actualHash = await hash(path.join(nodeArchivePath, tarName)); if (expectedHash !== actualHash) { - await fs.remove(path.join(nodeArchivePath, tarName)); - await fs.remove(path.join(nodeArchivePath, `${tarName}.sha256sum`)); + await rm(path.join(nodeArchivePath, tarName), { + recursive: true, + force: true, + }); + await rm(path.join(nodeArchivePath, `${tarName}.sha256sum`), { + recursive: true, + force: true, + }); throw wasReported(`Hash mismatch for ${tarName}`); } const pipe = promisify(pipeline); - const source = fs.createReadStream(path.join(nodeArchivePath, tarName)); + const source = createReadStream(path.join(nodeArchivePath, tarName)); const gunzip = createGunzip(); const extract = tar.extract(nodePath, { strip: 1, @@ -164,7 +170,10 @@ async function applyPatches(nodeVersion: string) { } } -export async function fetchExtractApply(nodeVersion: string, quietExtraction: boolean) { +export async function fetchExtractApply( + nodeVersion: string, + quietExtraction: boolean +) { await tarFetch(nodeVersion); await tarExtract(nodeVersion, quietExtraction); await applyPatches(nodeVersion); @@ -308,9 +317,9 @@ async function compile( } export async function prepBuildPath() { - await fs.remove(buildPath); - await fs.mkdirp(nodePath); - await fs.mkdirp(nodeArchivePath); + await rm(buildPath, { recursive: true, force: true }); + await mkdir(nodePath, { recursive: true }); + await mkdir(nodeArchivePath, { recursive: true }); } export default async function build( @@ -325,12 +334,12 @@ export default async function build( const output = await compile(nodeVersion, targetArch, targetPlatform); const outputHash = await hash(output); - await fs.mkdirp(path.dirname(local)); - await fs.copy(output, local); - await fs.promises.writeFile( + await mkdir(path.dirname(local), { recursive: true }); + await cp(output, local); + await writeFile( `${local}.sha256sum`, `${outputHash} ${path.basename(local)} ` ); - await fs.remove(buildPath); + await rm(buildPath, { recursive: true, force: true }); } diff --git a/lib/index.ts b/lib/index.ts index 65e9f139..43212f74 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -1,4 +1,5 @@ -import fs from 'fs-extra'; +import { unlinkSync } from 'fs'; +import { stat } from 'fs/promises'; import path from 'path'; import semver from 'semver'; @@ -37,7 +38,7 @@ async function download( async function exists(file: string) { try { - await fs.stat(file); + await stat(file); return true; } catch (error) { return false; @@ -132,7 +133,7 @@ export async function need(opts: NeedOptions) { } log.info('Binary hash does NOT match. Re-fetching...'); - fs.unlinkSync(fetched); + unlinkSync(fetched); } } @@ -153,7 +154,7 @@ export async function need(opts: NeedOptions) { return fetched; } - fs.unlinkSync(fetched); + unlinkSync(fetched); throw wasReported('Binary hash does NOT match.'); } diff --git a/lib/log.ts b/lib/log.ts index 693062c2..96003166 100644 --- a/lib/log.ts +++ b/lib/log.ts @@ -2,7 +2,12 @@ import Progress from 'progress'; import assert from 'assert'; -import chalk from 'chalk'; +import picocolors from 'picocolors'; +import { WriteStream } from 'tty'; + +// workaround until picocolors improves its color detection +// https://github.com/alexeyraspopov/picocolors/issues/85 +const pc = picocolors.createColors(WriteStream.prototype.hasColors()); class Log { debugMode = false; @@ -29,7 +34,7 @@ class Log { return; } - console.log(`> ${chalk.green('[debug]')} ${text}`); + console.log(`> ${pc.green('[debug]')} ${text}`); this.lines(lines); } @@ -39,13 +44,13 @@ class Log { } warn(text: string, lines?: string[] | string) { - console.log(`> ${chalk.blue('Warning')} ${text}`); + console.log(`> ${pc.blue('Warning')} ${text}`); this.lines(lines); } error(text: Error | string, lines?: string[] | string) { const message = text instanceof Error ? text.stack : text; - console.log(`> ${chalk.red('Error!')} ${message}`); + console.log(`> ${pc.red('Error!')} ${message}`); this.lines(lines); } diff --git a/lib/utils.ts b/lib/utils.ts index 0f0bd03f..9856fdc6 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -1,6 +1,7 @@ import fetch from 'node-fetch'; import crypto from 'crypto'; -import fs from 'fs-extra'; +import { createReadStream, createWriteStream, mkdirSync, renameSync, rmSync } from 'fs'; +import { chmod, stat } from 'fs/promises'; import httpsProxyAgent from 'https-proxy-agent'; import path from 'path'; import { spawnSync, SpawnSyncOptions } from 'child_process'; @@ -30,8 +31,8 @@ export async function downloadUrl(url: string, file: string): Promise { } const tempFile = `${file}.downloading`; - fs.mkdirpSync(path.dirname(tempFile)); - const ws = fs.createWriteStream(tempFile); + mkdirSync(path.dirname(tempFile), { recursive: true }); + const ws = createWriteStream(tempFile); const totalSize = Number(res.headers.get('content-length')); let currentSize = 0; @@ -48,12 +49,12 @@ export async function downloadUrl(url: string, file: string): Promise { stream.finished(ws, (err) => { if (err) { log.disableProgress(); - fs.rmSync(tempFile); + rmSync(tempFile); reject(wasReported(`${err.name}: ${err.message}`)); } else { log.showProgress(100); log.disableProgress(); - fs.moveSync(tempFile, file); + renameSync(tempFile, file); resolve(); } }); @@ -63,7 +64,7 @@ export async function downloadUrl(url: string, file: string): Promise { export async function hash(filePath: string): Promise { return new Promise((resolve, reject) => { const resultHash = crypto.createHash('sha256'); - const input = fs.createReadStream(filePath); + const input = createReadStream(filePath); input.on('error', (e) => { reject(e); @@ -81,11 +82,11 @@ export async function hash(filePath: string): Promise { } export async function plusx(file: string) { - const s = await fs.stat(file); + const s = await stat(file); const newMode = s.mode | 64 | 8 | 1; if (s.mode === newMode) return; const base8 = newMode.toString(8).slice(-3); - await fs.chmod(file, base8); + await chmod(file, base8); } export async function spawn( diff --git a/package.json b/package.json index 6cea8133..24594db0 100644 --- a/package.json +++ b/package.json @@ -18,10 +18,9 @@ "patches/*" ], "dependencies": { - "chalk": "^4.1.2", - "fs-extra": "^9.1.0", "https-proxy-agent": "^5.0.0", "node-fetch": "^2.6.6", + "picocolors": "^1.1.0", "progress": "^2.0.3", "semver": "^7.3.5", "tar-fs": "^2.1.1", @@ -29,8 +28,7 @@ }, "devDependencies": { "@release-it/conventional-changelog": "^7.0.2", - "@types/fs-extra": "^9.0.13", - "@types/node": "^14.17.32", + "@types/node": "^16.18.113", "@types/node-fetch": "^2.5.12", "@types/progress": "^2.0.5", "@types/semver": "^7.3.9", diff --git a/scripts/test_patch.sh b/scripts/test_patch.sh index 77c8f92f..b78e87d3 100755 --- a/scripts/test_patch.sh +++ b/scripts/test_patch.sh @@ -11,7 +11,7 @@ fi echo "Applying patches for $node_range" command="npm run applyPatches -- --node-range $node_range --quiet-extraction" -output=$($command) +output=$(NO_COLOR=1 $command) status=$? if [ $status -ne 0 ]; then diff --git a/yarn.lock b/yarn.lock index e8a0cc13..b4053855 100644 --- a/yarn.lock +++ b/yarn.lock @@ -260,13 +260,6 @@ resolved "https://registry.yarnpkg.com/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz#db4ecfd499a9765ab24002c3b696d02e6d32a12c" integrity sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA== -"@types/fs-extra@^9.0.13": - version "9.0.13" - resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.13.tgz#7594fbae04fe7f1918ce8b3d213f74ff44ac1f45" - integrity sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA== - dependencies: - "@types/node" "*" - "@types/http-cache-semantics@^4.0.1": version "4.0.2" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.2.tgz#abe102d06ccda1efdf0ed98c10ccf7f36a785a41" @@ -295,10 +288,10 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-20.8.2.tgz#d76fb80d87d0d8abfe334fc6d292e83e5524efc4" integrity sha512-Vvycsc9FQdwhxE3y3DzeIxuEJbWGDsnrxvMADzTDF/lcdR9/K+AQIeAghTQsHtotg/q0j3WEOYS/jQgSdWue3w== -"@types/node@^14.17.32": - version "14.18.63" - resolved "https://registry.yarnpkg.com/@types/node/-/node-14.18.63.tgz#1788fa8da838dbb5f9ea994b834278205db6ca2b" - integrity sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ== +"@types/node@^16.18.113": + version "16.18.113" + resolved "https://registry.yarnpkg.com/@types/node/-/node-16.18.113.tgz#fbe99013933c4997db5838d20497494a7e01f4ab" + integrity sha512-4jHxcEzSXpF1cBNxogs5FVbVSFSKo50sFCn7Xg7vmjJTbWFWgeuHW3QnoINlfmfG++MFR/q97RZE5RQXKeT+jg== "@types/normalize-package-data@^2.4.1": version "2.4.2" @@ -652,11 +645,6 @@ asynckit@^0.4.0: resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q== -at-least-node@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" - integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== - available-typed-arrays@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7" @@ -819,7 +807,7 @@ chalk@^2.4.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" -chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.2: +chalk@^4.0.0, chalk@^4.1.0: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== @@ -1844,16 +1832,6 @@ fs-extra@^8.1.0: jsonfile "^4.0.0" universalify "^0.1.0" -fs-extra@^9.1.0: - version "9.1.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" - integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== - dependencies: - at-least-node "^1.0.0" - graceful-fs "^4.2.0" - jsonfile "^6.0.1" - universalify "^2.0.0" - fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" @@ -2690,15 +2668,6 @@ jsonfile@^4.0.0: optionalDependencies: graceful-fs "^4.1.6" -jsonfile@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" - integrity sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ== - dependencies: - universalify "^2.0.0" - optionalDependencies: - graceful-fs "^4.1.6" - jsonparse@^1.2.0: version "1.3.1" resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280" @@ -3309,6 +3278,11 @@ path-type@^4.0.0: resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== +picocolors@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.0.tgz#5358b76a78cde483ba5cef6a9dc9671440b27d59" + integrity sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw== + picomatch@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" @@ -4176,11 +4150,6 @@ universalify@^0.1.0: resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== -universalify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" - integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== - untildify@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/untildify/-/untildify-4.0.0.tgz#2bc947b953652487e4600949fb091e3ae8cd919b"