From c3a8e5d12253d867b6b9def1943617a8ad6bb04d Mon Sep 17 00:00:00 2001 From: Paul Rumkin Date: Tue, 1 Dec 2020 11:21:45 +0300 Subject: [PATCH] [pkg,util] Add digest generation util --- bin/digest.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100755 bin/digest.js diff --git a/bin/digest.js b/bin/digest.js new file mode 100755 index 0000000..3676684 --- /dev/null +++ b/bin/digest.js @@ -0,0 +1,51 @@ +#!/usr/bin/env node + +const fs = require('fs') +const path = require('path') +const {createHash} = require('crypto') + +const fsp = fs.promises + +function calcHash(alg, filepath) { + const hash = createHash(alg) + + const stream = fs.createReadStream(filepath) + + return new Promise((resolve, reject) => { + stream.on('data', (chunk) => hash.update(chunk)) + stream.on('error', reject) + stream.on('end', () => { + resolve(hash.digest()) + }) + }) +} + +async function calcHashes(alg, dir, files) { + dir = path.resolve(dir) + const result = await Promise.all(files.map(async (relPath) => { + const filepath = path.resolve(relPath) + const digest = await calcHash(alg, filepath) + + const content = { + manifest: 'digest-json/v1', + alg, + digest: `${alg}-${digest.toString('base64')}`, + } + + await fsp.writeFile(`${relPath}.digest.json`, JSON.stringify(content, null, 2)) + + return [relPath, content] + })) + + for (const [file, {digest}] of result) { + console.log('%s %s', file, digest) + } +} + +calcHashes(process.argv[2], process.cwd(), process.argv.slice(3)) +.catch((error) => { + console.error(error) + + return 1 +}) +.then((code = 0) => process.exit(code)) diff --git a/package.json b/package.json index 4c63ad8..45ecc75 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "build:iife": "rollup --format iife --name pill -o dist/pill.js src/pill.js", "build:cjs": "rollup --format cjs --name pill -o dist/node/pill.js src/pill.js", "build:minify": "babel-minify -o dist/pill.min.js dist/pill.js", - "build:checksum": "node bin/checksum.js dist dist/*.js > dist/checksum.txt", + "build:digest": "node bin/digest.js sha512 dist/*.js", "prepublishOnly": "npm run committed && npm run clean && npm run build", "lint": "eslint src", "lint:staged": "bin/lint-staged.js",