feat: add preSubcommand hook (#1763)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by 鸿则 · committed by GitHub · parent 3ae30a2 · Browse files · 7 files·+111 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+111 added−34 removed
- tests:+36 added−0 removed
- other:+75 added−34 removed
Provenance
- Commit
2c7f687- Tree
335062d- Author
鸿则 <hungtcs@outlook.com>- Committer
GitHub <noreply@github.com>- Parent
3ae30a2
7 files changed+111 added−34 removed
modified:examples/hook.js+28 added-19 removed
12345456789101111121314154 unmodified lines202122232424252627282 unmodified lines3132333435363738394035363738394041424344454643444547484950515253545556575859606151525354555662636465#!/usr/bin/env node
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();const { Command, Option } = require('../'); // include commander in git clone of commander repoconst program = new Command();
// This example shows using some hooks for life cycle events.
const timeLabel = 'command duration';program .option('-p, --profile', 'show how long command takes') .option('--profile', 'show how long command takes') .hook('preAction', (thisCommand) => { if (thisCommand.opts().profile) { console.time(timeLabel); }4 unmodified lines } });
program .option('-t, --trace', 'display trace statements for commands') .option('--trace', 'display trace statements for commands') .hook('preAction', (thisCommand, actionCommand) => { if (thisCommand.opts().trace) { console.log('>>>>'); console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);2 unmodified lines console.log('<<<<'); } });
program.command('delay') .option('--message <value>', 'custom message to display', 'Thanks for waiting') .argument('[seconds]', 'how long to delay', '1') .action(async(waitSeconds, options) => { await new Promise(resolve => setTimeout(resolve, parseInt(waitSeconds) * 1000)); console.log(options.message);program .option('--env <filename>', 'specify environment file') .hook('preSubcommand', (thisCommand, subcommand) => { if (thisCommand.opts().env) { // One use case for this hook is modifying environment variables before // parsing the subcommand, say by reading .env file. console.log(`Reading ${thisCommand.opts().env}...`); process.env.PORT = 80; console.log(`About to call subcommand: ${subcommand.name()}`); } });
program.command('hello') .option('-e, --example') .action(() => console.log('Hello, world'));program.command('start') .argument('[script]', 'script name', 'server.js') .option('-d, --delay <seconds>', 'how long to delay before starting') .addOption(new Option('-p, --port <number>', 'port number').default(8080).env('PORT')) .action(async(script, options) => { if (options.delay) { await new Promise(resolve => setTimeout(resolve, parseInt(options.delay) * 1000)); } console.log(`Starting ${script} on port ${options.port}`); });
// Some of the hooks or actions are async, so call parseAsync rather than parse.program.parseAsync().then(() => {});
// Try the following:// node hook.js hello// node hook.js --profile hello// node hook.js --trace hello --example// node hook.js delay// node hook.js --trace delay 5 --message bye// node hook.js --profile delay// node hook.js start// node hook.js --trace start --port 9000 test.js// node hook.js --profile start --delay 5// node hook.js --env=production.env startmodified:lib/command.js+32 added-6 removed
397 unmodified lines398 * @return {Command} `this` command for chaining399 */400 401 hook(event, listener) {402- const allowedValues = ['preAction', 'postAction'];402+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];403 if (!allowedValues.includes(event)) {404 throw new Error(`Unexpected value for event passed to hook : '${event}'.405 Expecting one of '${allowedValues.join("', '")}'`);406 }646 unmodified lines1053 _dispatchSubcommand(commandName, operands, unknown) {1054 const subCommand = this._findCommand(commandName);1055 if (!subCommand) this.help({ error: true });1056 1057+ let hookResult;1058+ hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand');1059+ hookResult = this._chainOrCall(hookResult, () => {1057- if (subCommand._executableHandler) {1058- this._executeSubCommand(subCommand, operands.concat(unknown));1059- } else {1060- return subCommand._parseCommand(operands, unknown);1061- }1060+ if (subCommand._executableHandler) {1061+ this._executeSubCommand(subCommand, operands.concat(unknown));1062+ } else {1063+ return subCommand._parseCommand(operands, unknown);1064+ }1065+ });1066+ return hookResult;1067 }1068 1069 /**1070 * Check this.args against expected this._args.119 unmodified lines1190 return result;1191 }1192 1193 /**1194+ *1195+ * @param {Promise|undefined} promise1196+ * @param {Command} subCommand1197+ * @param {string} event1198+ * @return {Promise|undefined}1199+ * @api private1200+ */1201+1202+ _chainOrCallSubCommandHook(promise, subCommand, event) {1203+ let result = promise;1204+ if (this._lifeCycleHooks[event] !== undefined) {1205+ this._lifeCycleHooks[event].forEach((hook) => {1206+ result = this._chainOrCall(result, () => {1207+ return hook(this, subCommand);1208+ });1209+ });1210+ }1211+ return result;1212+ }1213+1214+ /**1215 * Process arguments in context of this command.1216 * Returns action result, in case it is a promise.1217 *1218 * @api private943 unmodified linesmodified:tests/command.hook.test.js+36 added
318 unmodified lines319 expect(calls).toEqual([]);320 await result;321 expect(calls).toEqual(['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);322 });323+324+ test('preSubcommand hook should work', async() => {325+ const calls = [];326+ const program = new commander.Command();327+ program328+ .hook('preSubcommand', async() => { await 0; calls.push(0); });329+ program.command('sub')330+ .action(async() => { await 1; calls.push(1); });331+ program.action(async() => { await 2; calls.push(2); });332+ const result = program.parseAsync(['sub'], { from: 'user' });333+ expect(calls).toEqual([]);334+ await result;335+ expect(calls).toEqual([0, 1]);336+ });337+ test('preSubcommand hook should effective for direct subcommands', async() => {338+ const calls = [];339+ const program = new commander.Command();340+ program341+ .hook('preSubcommand', async(thisCommand, subCommand) => {342+ await 'preSubcommand';343+ calls.push('preSubcommand');344+ calls.push(subCommand.name());345+ });346+ program347+ .command('first')348+ .action(async() => { await 'first'; calls.push('first'); })349+ .command('second')350+ .action(async() => { await 'second'; calls.push('second'); })351+ .command('third')352+ .action(async() => { await 'third'; calls.push('third'); });353+ program.action(async() => { await 2; calls.push(2); });354+ const result = program.parseAsync(['first', 'second', 'third'], { from: 'user' });355+ expect(calls).toEqual([]);356+ await result;357+ expect(calls).toEqual(['preSubcommand', 'first', 'third']);358+ });359 });modified:typings/index.d.ts+1 added-1 removed
263 unmodified lines264 265 }266 267 export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';268-export type HookEvent = 'preAction' | 'postAction';268+export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';269 export type OptionValueSource = 'default' | 'env' | 'config' | 'cli';270 271 export interface OptionValues {272 [key: string]: any;607 unmodified linesmodified:typings/index.test-d.ts+6 added
88 unmodified lines89 // implicit parameter types90 expectType<commander.Command>(thisCommand);91 expectType<commander.Command>(actionCommand);92 }));93+expectType<commander.Command>(program.hook('preSubcommand', () => {}));94+expectType<commander.Command>(program.hook('preSubcommand', (thisCommand, subcommand) => {95+ // implicit parameter types96+ expectType<commander.Command>(thisCommand);97+ expectType<commander.Command>(subcommand);98+}));99 100 // action101 expectType<commander.Command>(program.action(() => {}));102 expectType<commander.Command>(program.action(async() => {}));372 unmodified linesmodified:Readme_zh-CN.md+4 added-4 removed
694 unmodified lines695 钩子函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。一个事件上可以添加多个钩子。696 697 支持的事件有:698 699-- `preAction`:在本命令或其子命令的处理函数执行前700-- `postAction`:在本命令或其子命令的处理函数执行后699+| 事件名称 | 触发时机 | 参数列表 |700+| :-- | :-- | :-- |701+| `preAction`, `postAction` | 本命令或其子命令的处理函数执行前/后 | `(thisCommand, actionCommand)` |702+| `preSubcommand` | 在其直接子命令解析之前调用 | `(thisCommand, subcommand)` |703 702-钩子函数的参数为添加上钩子的命令,及实际执行的命令。703-704 ## 自动化帮助信息705 706 帮助信息是 Commander 基于你的程序自动生成的,默认的帮助选项是`-h,--help`。707 364 unmodified linesmodified:Readme.md+4 added-4 removed
717 unmodified lines718 The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.719 720 The supported events are:721 722-- `preAction`: called before action handler for this command and its subcommands723-- `postAction`: called after action handler for this command and its subcommands722+| event name | when hook called | callback parameters |723+| :-- | :-- | :-- |724+| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |725+| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |726 725-The hook is passed the command it was added to, and the command running the action handler.726-727 ## Automated help728 729 The help information is auto-generated based on the information commander already knows about your program. The default730 help option is `-h,--help`.384 unmodified lines