Skip to content

Instantly share code, notes, and snippets.

@kcwinner
Created October 14, 2020 15:44
Show Gist options
  • Save kcwinner/5962df02a43e4f46955038d9a60f67a8 to your computer and use it in GitHub Desktop.
Save kcwinner/5962df02a43e4f46955038d9a60f67a8 to your computer and use it in GitHub Desktop.
import { execSync } from 'child_process';
import * as path from 'path';
import { Readable } from 'stream';
import * as zlib from 'zlib';
import * as fs from 'fs-extra';
import * as tar from 'tar-fs';
import * as yargs from 'yargs';
import { JsiiType } from '../../inventory';
class Command implements yargs.CommandModule {
public readonly command = 'discover NPM-MODULE';
public readonly describe = 'Discovers project types from remote npm packages';
public builder(args: yargs.Argv) {
return args;
}
async handler(opts: any) {
const module = opts.npmModule;
const packageDir = await downloadExtractRemoteModule(module);
const jsii: { [name: string]: JsiiType } = fs.readJsonSync(path.join(packageDir, '.jsii')).types;
// TODO: implement the rest...
}
}
async function downloadExtractRemoteModule(module: string): Promise<string> {
const output = execSync(`npm pack ${module}`, { stdio: ['inherit', 'pipe', 'ignore'] });
const baseDir = process.cwd();
const packageZip = path.join(baseDir, output.toString('utf-8').trim());
const target = './tmp';
const fileData = fs.readFileSync(packageZip);
const tarData = zlib.gunzipSync(fileData);
// Readable.from() doesn't work in TS?
// const stream = Readable.from(tarData);
// stream.pipe(tar.extract(target),); // consume the stream
const readable = new Readable();
readable._read = () => { }; // _read is required but you can noop it
readable.push(tarData);
readable.push(null);
await new Promise((resolve, reject) => {
// consume the stream
readable.pipe(
tar.extract(target)
.on('finish', resolve)
.on('error', reject)
);
});
return path.join(baseDir, target, 'package');
}
module.exports = new Command();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment