Skip to content

Commit

Permalink
feat(write): accept multiple integrity algorithms (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
wraithgar committed May 2, 2023
1 parent 1b3774e commit 2e83cfc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
22 changes: 11 additions & 11 deletions lib/content/write.js
Expand Up @@ -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)
Expand All @@ -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
Expand Down
15 changes: 11 additions & 4 deletions test/content/write.js
Expand Up @@ -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 => {
Expand Down

0 comments on commit 2e83cfc

Please sign in to comment.