import copy from '@timsuchanek/copy' ; import execa from 'execa' ; import fs from 'fs' ; import makeDir from 'make-dir' ; import path from 'path' ; import readPkgUp from 'read-pkg-up' ; import { resolvePkg } from './utils/resolve' ; import rimraf from 'rimraf' ; import { quote } from 'shell-quote' ; import tar from 'tar' ; import tempy from 'tempy' ; import { promisify } from 'util' ; import { hasYarn } from './utils/hasYarn' ; const del = promisify ( rimraf ) ; const readdir = promisify ( fs . readdir ) ; const rename = promisify ( fs . rename ) ; export async function getPackedPackage ( name , target ? , packageDir ? ) { packageDir = packageDir || ( await resolvePkg ( name , { basedir : process . cwd ( ) } ) ) || ( await resolvePkg ( name , { basedir : target } ) ) ; if ( ! packageDir ) { const pkg = await readPkgUp ( { cwd : target , } ) ; if ( pkg && pkg . packageJson . name === name ) { packageDir = path . dirname ( pkg . path ) ; } } if ( ! packageDir && fs . existsSync ( path . join ( process . cwd ( ) , 'package.json' ) ) ) { packageDir = process . cwd ( ) ; } if ( ! packageDir ) { throw new Error ( `Error in getPackage: Could not resolve package ${ name } from ${ __dirname }` ) ; } const tmpDir = tempy . directory ( ) ; const archivePath = path . join ( tmpDir , `package.tgz` ) ; const isYarn = await hasYarn ( packageDir ) ; const packCmd = isYarn ? [ 'yarn' , 'pack' , '-f' , archivePath ] : [ 'npm' , 'pack' , packageDir ] ; const escapedCmd = quote ( packCmd ) ; await execa . command ( escapedCmd , { shell : true , cwd : isYarn ? packageDir : tmpDir , } ) ; if ( ! isYarn ) { const filename = ( await readdir ( tmpDir ) ) [ 0 ] ; await rename ( path . join ( tmpDir , filename ) , archivePath ) ; } await tar . extract ( { cwd : tmpDir , file : archivePath , } ) ; await del ( archivePath ) ; /**
     * Only if a target is provided, perform the copy
     */ if ( target ) { await makeDir ( target ) ; await copy ( { from : path . join ( tmpDir , 'package' ) , to : target , recursive : true , parallelJobs : 20 , overwrite : true , } ) ; await del ( tmpDir ) ; } return path . join ( tmpDir , 'package' ) ; }