11import debug from 'debug'
22import { createWriteStream , promises } from 'fs'
33import { platform , arch } from 'os'
4+ import { join } from 'path'
45import { clean , satisfies , valid } from 'semver'
56import { Readable } from 'stream'
67import { open as openArchive } from 'yauzl'
@@ -63,7 +64,7 @@ async function download(url, archive) {
6364 } )
6465}
6566
66- function unpack ( archive ) {
67+ function unpack ( archive , targetDirectory ) {
6768 log ( 'unpack "%s"' , archive )
6869 return new Promise ( ( resolve , reject ) =>
6970 openArchive ( archive , { lazyEntries : true } , ( err , zip ) => {
@@ -74,14 +75,15 @@ function unpack(archive) {
7475 const { fileName } = entry
7576 /* c8 ignore next */
7677 if ( fileName . endsWith ( '/' ) ) return new Error ( 'directory in archive' )
77- log ( 'write "%s"' , fileName )
78+ const filePath = targetDirectory ? join ( targetDirectory , fileName ) : fileName
79+ log ( 'write "%s"' , filePath )
7880 zip . openReadStream ( entry , ( err , stream ) => {
7981 /* c8 ignore next */
8082 if ( err ) return reject ( err )
8183 stream
8284 . on ( 'error' , reject )
83- . pipe ( createWriteStream ( fileName ) )
84- . on ( 'finish' , ( ) => resolve ( fileName ) )
85+ . pipe ( createWriteStream ( filePath ) )
86+ . on ( 'finish' , ( ) => resolve ( filePath ) )
8587 . on ( 'error' , reject )
8688 } )
8789 } )
@@ -99,7 +101,7 @@ async function makeExecutable(executable) {
99101 }
100102}
101103
102- export default async function grab ( { name, repository, version, platformSuffixes, unpackExecutable, verbose } ) {
104+ export default async function grab ( { name, repository, version, platformSuffixes, targetDirectory , unpackExecutable, verbose } ) {
103105 if ( verbose ) log = console . log . bind ( console )
104106 if ( ! version ) version = 'latest'
105107 const verspec = clean ( version ) || version
@@ -111,9 +113,10 @@ export default async function grab({ name, repository, version, platformSuffixes
111113 } else {
112114 ( { name, version, archive, url } = await getRelease ( name , repository , verspec , platformSuffixes ) )
113115 }
116+ if ( targetDirectory ) archive = join ( targetDirectory , archive )
114117 await download ( url , archive )
115118 if ( unpackExecutable ) {
116- const executable = await unpack ( archive )
119+ const executable = await unpack ( archive , targetDirectory )
117120 await makeExecutable ( executable )
118121 log ( 'remove "%s"' , archive )
119122 await unlink ( archive )
0 commit comments