Skip to content

Instantly share code, notes, and snippets.

@trulysinclair
Last active June 30, 2020 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trulysinclair/eec58d7eec81ebc87d4ff292f89c926f to your computer and use it in GitHub Desktop.
Save trulysinclair/eec58d7eec81ebc87d4ff292f89c926f to your computer and use it in GitHub Desktop.
import { Cli } from 'clipanion';
import { Readable, Writable } from 'stream';
import { readdirSync } from 'fs';
import { join } from 'path';
export type CommandContext = {
cwd: string;
quiet: boolean;
stdin: Readable;
stdout: Writable;
stderr: Writable;
};
/**
* Recursively register commands in `commands/`
* @param cli the Clipanion instance.
*/
async function registerCommands(cli: Cli<CommandContext>) {
const root = `${__dirname}/commands`;
const commands = readdirSync(root);
for (const command of commands) {
const index = require(join(root, command));
cli.register(index.default);
}
}
async function main() {
async function run(): Promise<void> {
const cli = new Cli<CommandContext>({
binaryLabel: 'Yarnberry Toolkit',
binaryName: 'toolkit',
binaryVersion: '0.1.0',
});
registerCommands(cli);
try {
await exec(cli);
} catch (error) {
process.stdout.write(cli.error(error));
process.exitCode = 1;
}
}
async function exec(cli: Cli<CommandContext>): Promise<void> {
const command = cli.process(process.argv.slice(2));
cli.runExit(command, {
cwd: process.cwd(),
quiet: false,
stdin: process.stdin,
stdout: process.stdout,
stderr: process.stderr,
});
}
return run().catch((error) => {
process.stdout.write(error.stack || error.message);
process.exitCode = 1;
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment