import * as fs from "fs-extra" ; import * as os from "os" ; import * as path from "path" ; import { onExit } from "./exit" ; export interface MkdtmpPromise extends Promise < string > { remove ( ) : Promise < void > ; } export function mkdtmp ( prefix , basedir = os . tmpdir ( ) ) { let newDir ; let removeOnExit ; const retP = fs . mkdtemp ( path . join ( basedir , prefix + "-" ) ) . then ( ( dir ) => { newDir = dir ; removeOnExit = onExit ( remove ) ; return newDir ; } ) ; return Object . assign ( retP , { remove } ) ; async function remove ( ) { if ( newDir ) await fs . remove ( newDir ) ; if ( removeOnExit ) removeOnExit ( ) ; } } export interface WithTmpDirOpts { prefix ? : string ; basedir ? : string ; } const withTmpDirDefaults = { prefix : "tmp" , basedir : os . tmpdir ( ) , } ; export async function withTmpDir < T > ( f , options = { } ) { const { basedir , prefix } = { ... withTmpDirDefaults , ... options } ; const tmpDirP = mkdtmp ( prefix , basedir ) ; try { const tmpDir = await tmpDirP ; return await f ( tmpDir ) ; } finally { await tmpDirP . remove ( ) ; } }