Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@trulysinclair
Last active June 30, 2020 17:20
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/93fe9b189f70ca4517640fe129babb24 to your computer and use it in GitHub Desktop.
Save trulysinclair/93fe9b189f70ca4517640fe129babb24 to your computer and use it in GitHub Desktop.
// src/tools/BaseCommand.ts
import { Command } from 'clipanion';
import { CommandContext } from '..';
/**
* The BaseCommand allows us to add behind-the-scenes functionality,
* while also allowing us to now have to add Command<CommandContext>
* to every command manually.
*/
export abstract class BaseCommand extends Command<CommandContext> {
abstract execute(): Promise<number | void>;
}
export default BaseCommand;
// src/cli.ts
import { Cli } from 'clipanion';
/** Here we setup our custom context object. */
export type CommandContext = {
quiet: boolean;
stdin: Readable;
stdout: Writable;
stderr: Writable;
};
/** Create the Clipanion instance and name it. */
const cli = new Cli<CommandContext>({
binaryLabel: 'An example program',
binaryName: 'toolkit',
binaryVersion: '1.0.0',
});
/** Register our WelcomeCommand. */
cli.register(WelcomeCommand);
/** Pass in our terminal arguments. */
const command = cli.process(process.argv.slice(2));
/** Run the program. */
cli.runExit(command, {
quiet: false,
stdin: process.stdin,
stdout: process.stdout,
stderr: process.stderr,
})
// src/commands/WelcomeCommand.ts
import { BaseCommand } from '../tools/BaseCommand';
import { Command } from 'clipanion';
const message = () => `
Welcome to the Yarnberry Toolkit! The powerhouse of the ce-- the Yarnberry Cookbook!
I won't lie, the Yarnberry Toolkit uses "arcanis/Clipanion" which is new and not
overly documented so I stripped some logic from Yarn 2 😅.
`;
/** Although simple, this quickly shows what makes Clipanion unique. */
export class WelcomeCommand extends BaseCommand {
/** We tell Clipanion to listen for `--welcome` to run this command. */
@Command.Path('--welcome')
/** This tells Clipanion that this is also the default command. */
@Command.Path()
async execute(): Promise<void> {
/** We don't use console, instead Clipanion uses an internal context/state. */
this.context.stdout.write(`${message().trim()}\n`);
}
}
export default WelcomeCommand;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment