Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(write): accept multiple integrity algorithms #200

Merged
merged 1 commit into from May 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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