|
| 1 | +import * as fs from 'fs-extra'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as os from 'os'; |
| 4 | +import { spawn, SpawnOptions } from 'child_process'; |
| 5 | + |
| 6 | +export async function withTempDir(dirname: string, closure: (dir: string) => Promise<void>) { |
| 7 | + const prevdir = process.cwd(); |
| 8 | + const parent = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk8s.')); |
| 9 | + const workdir = path.join(parent, dirname); |
| 10 | + await fs.mkdirp(workdir); |
| 11 | + try { |
| 12 | + process.chdir(workdir); |
| 13 | + await closure(workdir); |
| 14 | + |
| 15 | + if (!process.env.WITH_TEMP_DIR_RETAIN) { |
| 16 | + await fs.remove(parent); |
| 17 | + } else { |
| 18 | + console.error(`retained temp dir: ${parent}`); |
| 19 | + } |
| 20 | + } catch(e) { |
| 21 | + console.error(`retained temp dir due to an error: ${parent}`); |
| 22 | + throw e; |
| 23 | + } finally { |
| 24 | + process.chdir(prevdir); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +export async function exec(moduleName: string, args: string[] = [], options: SpawnOptions = { }) { |
| 29 | + return new Promise((ok, fail) => { |
| 30 | + |
| 31 | + const opts: SpawnOptions = { |
| 32 | + ...options, |
| 33 | + stdio: [ 'inherit', 'pipe', 'pipe' ], |
| 34 | + }; |
| 35 | + const child = spawn(process.execPath, [ moduleName, ...args ], opts); |
| 36 | + |
| 37 | + const data = new Array<Buffer>(); |
| 38 | + child.stdout?.on('data', chunk => data.push(chunk)); |
| 39 | + child.stderr?.on('data', chunk => data.push(chunk)); |
| 40 | + |
| 41 | + const newError = (message: string) => new Error([ |
| 42 | + message, |
| 43 | + `COMMAND: ${moduleName} ${args.join(' ')}`, |
| 44 | + `WORKDIR: ${path.resolve(options.cwd ?? '.')}`, |
| 45 | + '------------------------------------------------------------------------------------', |
| 46 | + Buffer.concat(data).toString('utf-8'), |
| 47 | + '------------------------------------------------------------------------------------', |
| 48 | + ].join('\n')); |
| 49 | + |
| 50 | + child.once('error', err => { |
| 51 | + throw newError(`jsii compilation failed. error: ${err.message}`); |
| 52 | + }); |
| 53 | + |
| 54 | + child.once('exit', code => { |
| 55 | + if (code === 0) { |
| 56 | + return ok(); |
| 57 | + } |
| 58 | + else { |
| 59 | + return fail(newError(`jsii compilation failed with non-zero exit code: ${code}`)); |
| 60 | + } |
| 61 | + }); |
| 62 | + }); |
| 63 | +} |
0 commit comments