Skip to content
Myr

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

7 files+111 added−34 removed

modified:examples/hook.js+28 added-19 removed
modified:lib/command.js+32 added-6 removed
397 unmodified lines
398 * @return {Command} `this` command for chaining399 */400401 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}'.405Expecting one of '${allowedValues.join("', '")}'`);406 }
646 unmodified lines
1053 _dispatchSubcommand(commandName, operands, unknown) {1054 const subCommand = this._findCommand(commandName);1055 if (!subCommand) this.help({ error: true });10561057 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 }10681069 /**1070 * Check this.args against expected this._args.
119 unmodified lines
1190 return result;1191 }11921193 /**1194 *1195 * @param {Promise|undefined} promise1196 * @param {Command} subCommand1197 * @param {string} event1198 * @return {Promise|undefined}1199 * @api private1200 */12011202 _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 }12131214 /**1215 * Process arguments in context of this command.1216 * Returns action result, in case it is a promise.1217 *1218 * @api private
943 unmodified lines
modified:tests/command.hook.test.js+36 added
318 unmodified lines
319 expect(calls).toEqual([]);320 await result;321 expect(calls).toEqual(['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);322 });323324 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 lines
264265}266267export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';268export type HookEvent = 'preAction' | 'postAction';268export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';269export type OptionValueSource = 'default' | 'env' | 'config' | 'cli';270271export interface OptionValues {272 [key: string]: any;
607 unmodified lines
modified:typings/index.test-d.ts+6 added
88 unmodified lines
89 // implicit parameter types90 expectType<commander.Command>(thisCommand);91 expectType<commander.Command>(actionCommand);92}));93expectType<commander.Command>(program.hook('preSubcommand', () => {}));94expectType<commander.Command>(program.hook('preSubcommand', (thisCommand, subcommand) => {95 // implicit parameter types96 expectType<commander.Command>(thisCommand);97 expectType<commander.Command>(subcommand);98}));99100// action101expectType<commander.Command>(program.action(() => {}));102expectType<commander.Command>(program.action(async() => {}));
372 unmodified lines
modified:Readme_zh-CN.md+4 added-4 removed
694 unmodified lines
695钩子函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。一个事件上可以添加多个钩子。696697支持的事件有:698699- `preAction`:在本命令或其子命令的处理函数执行前700- `postAction`:在本命令或其子命令的处理函数执行后699| 事件名称 | 触发时机 | 参数列表 |700| :-- | :-- | :-- |701| `preAction`, `postAction` | 本命令或其子命令的处理函数执行前/后 | `(thisCommand, actionCommand)` |702| `preSubcommand` | 在其直接子命令解析之前调用 | `(thisCommand, subcommand)` |703702钩子函数的参数为添加上钩子的命令,及实际执行的命令。703704## 自动化帮助信息705706帮助信息是 Commander 基于你的程序自动生成的,默认的帮助选项是`-h,--help`。707
364 unmodified lines
modified:Readme.md+4 added-4 removed
717 unmodified lines
718The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.719720The supported events are:721722- `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)` |726725The hook is passed the command it was added to, and the command running the action handler.726727## Automated help728729The help information is auto-generated based on the information commander already knows about your program. The default730help option is `-h,--help`.
384 unmodified lines