@@ -4,8 +4,8 @@ const events = require('events')
44
55const contentPath = require ( './path' )
66const fs = require ( 'fs/promises' )
7- const moveFile = require ( '../util/move-file ' )
8- const Minipass = require ( 'minipass' )
7+ const { moveFile } = require ( '@npmcli/fs ' )
8+ const { Minipass } = require ( 'minipass' )
99const Pipeline = require ( 'minipass-pipeline' )
1010const Flush = require ( 'minipass-flush' )
1111const path = require ( 'path' )
@@ -17,9 +17,6 @@ module.exports = write
1717
1818async function write ( cache , data , opts = { } ) {
1919 const { algorithms, size, integrity } = opts
20- if ( algorithms && algorithms . length > 1 ) {
21- throw new Error ( 'opts.algorithms only supports a single algorithm for now' )
22- }
2320
2421 if ( typeof size === 'number' && data . length !== size ) {
2522 throw sizeError ( size , data . length )
@@ -30,16 +27,19 @@ async function write (cache, data, opts = {}) {
3027 throw checksumError ( integrity , sri )
3128 }
3229
33- const tmp = await makeTmp ( cache , opts )
34- try {
35- await fs . writeFile ( tmp . target , data , { flag : 'wx' } )
36- await moveToDestination ( tmp , cache , sri , opts )
37- return { integrity : sri , size : data . length }
38- } finally {
39- if ( ! tmp . moved ) {
40- await fs . rm ( tmp . target , { recursive : true , force : true } )
30+ for ( const algo in sri ) {
31+ const tmp = await makeTmp ( cache , opts )
32+ const hash = sri [ algo ] . toString ( )
33+ try {
34+ await fs . writeFile ( tmp . target , data , { flag : 'wx' } )
35+ await moveToDestination ( tmp , cache , hash , opts )
36+ } finally {
37+ if ( ! tmp . moved ) {
38+ await fs . rm ( tmp . target , { recursive : true , force : true } )
39+ }
4140 }
4241 }
42+ return { integrity : sri , size : data . length }
4343}
4444
4545module . exports . stream = writeStream
@@ -161,8 +161,14 @@ async function moveToDestination (tmp, cache, sri, opts) {
161161 const destDir = path . dirname ( destination )
162162
163163 await fs . mkdir ( destDir , { recursive : true } )
164- await moveFile ( tmp . target , destination )
165- tmp . moved = true
164+ try {
165+ await moveFile ( tmp . target , destination , { overwrite : false } )
166+ tmp . moved = true
167+ } catch ( err ) {
168+ if ( ! err . message . startsWith ( 'The destination file exists' ) ) {
169+ throw Object . assign ( err , { code : 'EEXIST' } )
170+ }
171+ }
166172}
167173
168174function sizeError ( expected , found ) {
0 commit comments