From fb48d643347e11272b0e6f38ee6133b8f51d525f Mon Sep 17 00:00:00 2001 From: Gar Date: Tue, 2 May 2023 13:07:04 -0700 Subject: [PATCH] feat(write): accept multiple integrity algorithms --- lib/content/write.js | 22 +++++++++++----------- test/content/write.js | 15 +++++++++++---- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/lib/content/write.js b/lib/content/write.js index 74b87fb..b6f5c56 100644 --- a/lib/content/write.js +++ b/lib/content/write.js @@ -17,9 +17,6 @@ module.exports = write async function write (cache, data, opts = {}) { const { algorithms, size, integrity } = opts - if (algorithms && algorithms.length > 1) { - throw new Error('opts.algorithms only supports a single algorithm for now') - } if (typeof size === 'number' && data.length !== size) { throw sizeError(size, data.length) @@ -30,16 +27,19 @@ async function write (cache, data, opts = {}) { throw checksumError(integrity, sri) } - const tmp = await makeTmp(cache, opts) - try { - await fs.writeFile(tmp.target, data, { flag: 'wx' }) - await moveToDestination(tmp, cache, sri, opts) - return { integrity: sri, size: data.length } - } finally { - if (!tmp.moved) { - await fs.rm(tmp.target, { recursive: true, force: true }) + for (const algo in sri) { + const tmp = await makeTmp(cache, opts) + const hash = sri[algo].toString() + try { + await fs.writeFile(tmp.target, data, { flag: 'wx' }) + await moveToDestination(tmp, cache, hash, opts) + } finally { + if (!tmp.moved) { + await fs.rm(tmp.target, { recursive: true, force: true }) + } } } + return { integrity: sri, size: data.length } } module.exports.stream = writeStream diff --git a/test/content/write.js b/test/content/write.js index fae3cd9..3b43aa5 100644 --- a/test/content/write.js +++ b/test/content/write.js @@ -329,11 +329,18 @@ t.test('checks the size of stream data if opts.size provided', (t) => { }) }) -t.test('only one algorithm for now', async t => { +t.test('accepts multiple algorithms', async t => { const CACHE = t.testdir() - await t.rejects(() => write(CACHE, 'foo', { algorithms: [1, 2] }), { - message: 'opts.algorithms only supports a single algorithm for now', - }) + const CONTENT = 'multiple algorithms!' + const { integrity } = await write(CACHE, CONTENT, { algorithms: ['sha512', 'sha1'] }) + const cpath512 = contentPath(CACHE, integrity.sha512.toString()) + t.ok(fs.lstatSync(cpath512).isFile(), 'sha512 content written') + const cpath1 = contentPath(CACHE, integrity.sha1.toString()) + t.ok(fs.lstatSync(cpath1).isFile(), 'sha1 content written') + t.equal(fs.readFileSync(cpath512, 'utf8'), + CONTENT, 'sha512 contents are identical to inserted content') + t.equal(fs.readFileSync(cpath1, 'utf8'), + CONTENT, 'sha1 contents are identical to inserted content') }) t.test('writes to cache with default options', t => {