Skip to content
Myr

Add hooks for life cycle events: using .hook() (#1514)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* First cut at action hooks * First cut at promise support in hooks * Move static routines out of class * Add error for unexpport event type * Add typings * Add typings * Support multiple hooks on same command * Add some synchronous tests * Add async tests * Add tests that options and args are available from context in hooks * Expand test names * Spell life cycle as two words * Spell life cycle as two words * Fix typo in JSDoc * Add example for hooks * Make comment more accurate * First cut at README * Small README improvements * Add note about async and multiple hooks * Rename hooks and pass parameters rather than context hash * Make example scan better * Fix stale comment

authored by John Gee · committed by GitHub · parent 6c06528 · Browse files · 7 files+525 added−10 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+525 added−10 removed

  • tests:+329 added−0 removed
  • other:+196 added−10 removed

7 files+525 added−10 removed

added:examples/hook.js+56 added
modified:tests/command.chain.test.js+6 added
164 unmodified lines
165 const result = program.enablePositionalOptions();166 expect(result).toBe(program);167 });168169 test('when call .hook() then returns this', () => {170 const program = new Command();171 const result = program.hook('preAction', () => {});172 expect(result).toBe(program);173 });174175 test('when call .setOptionValue() then returns this', () => {176 const program = new Command();177 const result = program.setOptionValue();178 expect(result).toBe(program);
2 unmodified lines
added:tests/command.hook.test.js+323 added
1const commander = require('../');23test('when hook event wrong then throw', () => {4 const program = new commander.Command();5 expect(() => {6 program.hook('silly', () => {});7 }).toThrow();8});910test('when no action then action hooks not called', () => {11 const hook = jest.fn();12 const program = new commander.Command();13 program14 .hook('preAction', hook)15 .hook('postAction', hook);16 program.parse([], { from: 'user' });17 expect(hook).not.toHaveBeenCalled();18});1920describe('action hooks with synchronous hooks, order', () => {21 test('when hook preAction then hook called before action', () => {22 const calls = [];23 const program = new commander.Command();24 program25 .hook('preAction', () => calls.push('before'))26 .action(() => calls.push('action'));27 program.parse([], { from: 'user' });28 expect(calls).toEqual(['before', 'action']);29 });3031 test('when hook postAction then hook called after action', () => {32 const calls = [];33 const program = new commander.Command();34 program35 .hook('postAction', () => calls.push('after'))36 .action(() => calls.push('action'));37 program.parse([], { from: 'user' });38 expect(calls).toEqual(['action', 'after']);39 });4041 test('when hook preAction twice then hooks called FIFO', () => {42 const calls = [];43 const program = new commander.Command();44 program45 .hook('preAction', () => calls.push('1'))46 .hook('preAction', () => calls.push('2'))47 .action(() => calls.push('action'));48 program.parse([], { from: 'user' });49 expect(calls).toEqual(['1', '2', 'action']);50 });5152 test('when hook postAction twice then hooks called LIFO', () => {53 const calls = [];54 const program = new commander.Command();55 program56 .hook('postAction', () => calls.push('1'))57 .hook('postAction', () => calls.push('2'))58 .action(() => calls.push('action'));59 program.parse([], { from: 'user' });60 expect(calls).toEqual(['action', '2', '1']);61 });6263 test('when hook preAction at program and sub then hooks called program then sub', () => {64 const calls = [];65 const program = new commander.Command();66 program67 .hook('preAction', () => calls.push('program'));68 program.command('sub')69 .hook('preAction', () => calls.push('sub'))70 .action(() => calls.push('action'));71 program.parse(['sub'], { from: 'user' });72 expect(calls).toEqual(['program', 'sub', 'action']);73 });7475 test('when hook postAction at program and sub then hooks called sub then program', () => {76 const calls = [];77 const program = new commander.Command();78 program79 .hook('postAction', () => calls.push('program'));80 program.command('sub')81 .hook('postAction', () => calls.push('sub'))82 .action(() => calls.push('action'));83 program.parse(['sub'], { from: 'user' });84 expect(calls).toEqual(['action', 'sub', 'program']);85 });8687 test('when hook everything then hooks called nested', () => {88 const calls = [];89 const program = new commander.Command();90 program91 .hook('preAction', () => calls.push('pb1'))92 .hook('postAction', () => calls.push('pa1'));93 program94 .hook('preAction', () => calls.push('pb2'))95 .hook('postAction', () => calls.push('pa2'));96 program.command('sub')97 .hook('preAction', () => calls.push('sb'))98 .hook('postAction', () => calls.push('sa'))99 .action(() => calls.push('action'));100 program.parse(['sub'], { from: 'user' });101 expect(calls).toEqual(['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);102 });103});104105describe('action hooks context', () => {106 test('when hook on program then passed program/program', () => {107 const hook = jest.fn();108 const program = new commander.Command();109 program110 .hook('preAction', hook)111 .action(() => {});112 program.parse([], { from: 'user' });113 expect(hook).toHaveBeenCalledWith(program, program);114 });115116 test('when hook on program and call sub then passed program/sub', () => {117 const hook = jest.fn();118 const program = new commander.Command();119 program120 .hook('preAction', hook);121 const sub = program.command('sub')122 .action(() => {});123 program.parse(['sub'], { from: 'user' });124 expect(hook).toHaveBeenCalledWith(program, sub);125 });126127 test('when hook on sub and call sub then passed sub/sub', () => {128 const hook = jest.fn();129 const program = new commander.Command();130 const sub = program.command('sub')131 .hook('preAction', hook)132 .action(() => {});133 program.parse(['sub'], { from: 'user' });134 expect(hook).toHaveBeenCalledWith(sub, sub);135 });136137 test('when hook program on preAction then thisCommand has options set', () => {138 expect.assertions(1);139 const program = new commander.Command();140 program141 .option('--debug')142 .hook('preAction', (thisCommand) => {143 expect(thisCommand.opts().debug).toEqual(true);144 })145 .action(() => {});146 program.parse(['--debug'], { from: 'user' });147 });148149 test('when hook program on preAction and call sub then thisCommand has program options set', () => {150 expect.assertions(1);151 const program = new commander.Command();152 program153 .option('--debug')154 .hook('preAction', (thisCommand) => {155 expect(thisCommand.opts().debug).toEqual(true);156 });157 program.command('sub')158 .action(() => {});159 program.parse(['sub', '--debug'], { from: 'user' });160 });161162 test('when hook program on preAction and call sub then actionCommand has sub options set', () => {163 expect.assertions(1);164 const program = new commander.Command();165 program166 .hook('preAction', (thisCommand, actionCommand) => {167 expect(actionCommand.opts().debug).toEqual(true);168 });169 program.command('sub')170 .option('--debug')171 .action(() => {});172 program.parse(['sub', '--debug'], { from: 'user' });173 });174175 test('when hook program on preAction then actionCommand has args set', () => {176 expect.assertions(1);177 const program = new commander.Command();178 program179 .argument('[arg]')180 .hook('preAction', (thisCommand, actionCommand) => {181 expect(actionCommand.args).toEqual(['value']);182 })183 .action(() => {});184 program.parse(['value'], { from: 'user' });185 });186187 test('when hook program on preAction then actionCommand has args set with options removed', () => {188 expect.assertions(1);189 const program = new commander.Command();190 program191 .argument('[arg]')192 .option('--debug')193 .hook('preAction', (thisCommand, actionCommand) => {194 expect(actionCommand.args).toEqual(['value']);195 })196 .action(() => {});197 program.parse(['value', '--debug'], { from: 'user' });198 });199200 test('when hook program on preAction and call sub then thisCommand has program args set', () => {201 expect.assertions(1);202 const program = new commander.Command();203 program204 .argument('[arg]')205 .hook('preAction', (thisCommand) => {206 expect(thisCommand.args).toEqual(['sub', 'value']);207 });208 program.command('sub')209 .action(() => {});210 program.parse(['sub', 'value'], { from: 'user' });211 });212213 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {214 expect.assertions(1);215 const program = new commander.Command();216 program217 .hook('preAction', (thisCommand, actionCommand) => {218 expect(actionCommand.args).toEqual(['value']);219 });220 program.command('sub')221 .action(() => {});222 program.parse(['sub', 'value'], { from: 'user' });223 });224});225226describe('action hooks async', () => {227 test('when async preAction then async from preAction', async() => {228 const calls = [];229 const program = new commander.Command();230 program231 .hook('preAction', async() => {232 await 0;233 calls.push('before');234 })235 .action(() => calls.push('action'));236 const result = program.parseAsync([], { from: 'user' });237 expect(calls).toEqual([]);238 await result;239 expect(calls).toEqual(['before', 'action']);240 });241242 test('when async postAction then async from postAction', async() => {243 const calls = [];244 const program = new commander.Command();245 program246 .hook('postAction', async() => {247 await 0;248 calls.push('after');249 })250 .action(() => calls.push('action'));251 const result = program.parseAsync([], { from: 'user' });252 expect(calls).toEqual(['action']);253 await result;254 expect(calls).toEqual(['action', 'after']);255 });256257 test('when async action then async from action', async() => {258 const calls = [];259 const program = new commander.Command();260 program261 .hook('preAction', () => calls.push('before'))262 .hook('postAction', () => calls.push('after'))263 .action(async() => {264 await 0;265 calls.push('action');266 });267 const result = program.parseAsync([], { from: 'user' });268 expect(calls).toEqual(['before']);269 await result;270 expect(calls).toEqual(['before', 'action', 'after']);271 });272273 test('when async first preAction then async from first preAction', async() => {274 const calls = [];275 const program = new commander.Command();276 program277 .hook('preAction', async() => {278 await 0;279 calls.push('1');280 })281 .hook('preAction', () => calls.push('2'))282 .action(() => calls.push('action'));283 const result = program.parseAsync([], { from: 'user' });284 expect(calls).toEqual([]);285 await result;286 expect(calls).toEqual(['1', '2', 'action']);287 });288289 test('when async second preAction then async from second preAction', async() => {290 const calls = [];291 const program = new commander.Command();292 program293 .hook('preAction', () => calls.push('1'))294 .hook('preAction', async() => {295 await 0;296 calls.push('2');297 })298 .action(() => calls.push('action'));299 const result = program.parseAsync([], { from: 'user' });300 expect(calls).toEqual(['1']);301 await result;302 expect(calls).toEqual(['1', '2', 'action']);303 });304305 test('when async hook everything then hooks called nested', async() => {306 const calls = [];307 const program = new commander.Command();308 program309 .hook('preAction', async() => { await 0; calls.push('pb1'); })310 .hook('postAction', async() => { await 0; calls.push('pa1'); });311 program312 .hook('preAction', async() => { await 0; calls.push('pb2'); })313 .hook('postAction', async() => { await 0; calls.push('pa2'); });314 program.command('sub')315 .hook('preAction', async() => { await 0; calls.push('sb'); })316 .hook('postAction', async() => { await 0; calls.push('sa'); })317 .action(async() => { await 0; calls.push('action'); });318 const result = program.parseAsync(['sub'], { from: 'user' });319 expect(calls).toEqual([]);320 await result;321 expect(calls).toEqual(['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);322 });323});
modified:typings/index.d.ts+6 added
191 unmodified lines
192193}194195type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';196type HookEvent = 'preAction' | 'postAction';197198export interface OptionValues {199 [key: string]: any;200}
128 unmodified lines
329 */330 addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;331332 /**333 * Add hook for life cycle event.334 */335 hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;336337 /**338 * Register callback to use as replacement for calling process.exit.339 */340 exitOverride(callback?: (err: CommanderError) => never|void): this;341
369 unmodified lines
modified:typings/index.test-d.ts+15 added-9 removed
1 unmodified line
2import {expectType} from 'tsd';34// We are are not just checking return types here, we are also implicitly checking that the expected syntax is allowed.56/* eslint-disable @typescript-eslint/no-empty-function */78const program: commander.Command = new commander.Command();9// @ts-expect-error Check that Command is strongly typed and does not allow arbitrary properties10program.silly; // <-- Error, hurrah!11
59 unmodified lines
71 // Async callback from spawn events, not useful to throw.72 }73}));7473// action74expectType<commander.Command>(program.action(() => {75 // do nothing.75// hook76expectType<commander.Command>(program.hook('preAction', () => {}));77expectType<commander.Command>(program.hook('postAction', () => {}));78expectType<commander.Command>(program.hook('preAction', async() => {}));79expectType<commander.Command>(program.hook('preAction', (thisCommand, actionCommand) => {80 // implicit parameter types81 expectType<commander.Command>(thisCommand);82 expectType<commander.Command>(actionCommand);83}));77expectType<commander.Command>(program.action(async() => {78 // do nothing.79}));8485// action86expectType<commander.Command>(program.action(() => {}));87expectType<commander.Command>(program.action(async() => {}));8889// option90expectType<commander.Command>(program.option('-a,--alpha'));91expectType<commander.Command>(program.option('-p, --peppers', 'Add peppers'));92expectType<commander.Command>(program.option('-s, --string [value]', 'default string', 'value'));
154 unmodified lines
247 return '';248}));249250// on243expectType<commander.Command>(program.on('command:foo', () => {244 // do nothing.245}));251expectType<commander.Command>(program.on('command:foo', () => {}));252253// createCommand254expectType<commander.Command>(program.createCommand());255expectType<commander.Command>(program.createCommand('name'));
114 unmodified lines
modified:index.js+91 added-1 removed
676 unmodified lines
677 this._description = '';678 this._argsDescription = undefined; // legacy679 this._enablePositionalOptions = false;680 this._passThroughOptions = false;681 this._lifeCycleHooks = {}; // a hash of arrays682683 // see .configureOutput() for docs684 this._outputConfiguration = {685 writeOut: (str) => process.stdout.write(str),
303 unmodified lines
989 return this._addImplicitHelpCommand;990 };991992 /**993 * Add hook for life cycle event.994 *995 * @param {string} event996 * @param {Function} listener997 * @return {Command} `this` command for chaining998 */9991000 hook(event, listener) {1001 const allowedValues = ['preAction', 'postAction'];1002 if (!allowedValues.includes(event)) {1003 throw new Error(`Unexpected value for event passed to hook : '${event}'.1004Expecting one of '${allowedValues.join("', '")}'`);1005 }1006 if (this._lifeCycleHooks[event]) {1007 this._lifeCycleHooks[event].push(listener);1008 } else {1009 this._lifeCycleHooks[event] = [listener];1010 }1011 return this;1012 }10131014 /**1015 * Register callback to use as replacement for calling process.exit.1016 *1017 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing1018 * @return {Command} `this` command for chaining
644 unmodified lines
1663 return actionArgs;1664 }16651666 /**1667 * Once we have a promise we chain, but call synchronously until then.1668 *1669 * @param {Promise|undefined} promise1670 * @param {Function} fn1671 * @return {Promise|undefined}1672 */16731674 _chainOrCall(promise, fn) {1675 // thenable1676 if (promise && promise.then && typeof promise.then === 'function') {1677 // already have a promise, chain callback1678 return promise.then(() => fn());1679 }1680 // callback might return a promise1681 return fn();1682 }16831684 /**1685 *1686 * @param {Promise|undefined} promise1687 * @param {string} event1688 * @return {Promise|undefined}1689 * @api private1690 */16911692 _chainOrCallHooks(promise, event) {1693 let result = promise;1694 const hooks = [];1695 getCommandAndParents(this)1696 .reverse()1697 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1698 .forEach(hookedCommand => {1699 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1700 hooks.push({ hookedCommand, callback });1701 });1702 });1703 if (event === 'postAction') {1704 hooks.reverse();1705 }17061707 hooks.forEach((hookDetail) => {1708 result = this._chainOrCall(result, () => {1709 return hookDetail.callback(hookDetail.hookedCommand, this);1710 });1711 });1712 return result;1713 }17141715 /**1716 * Process arguments in context of this command.1717 * Returns action result, in case it is a promise.1718 *1719 * @api private
51 unmodified lines
1771 const commandEvent = `command:${this.name()}`;1772 if (this._actionHandler) {1773 checkForUnknownOptions();1774 checkNumberOfArguments();1703 const actionResult = this._actionHandler(this._getActionArguments());17751776 let actionResult;1777 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1778 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this._getActionArguments()));1779 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1780 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1781 return actionResult;1782 }1783 if (this.parent && this.parent.listenerCount(commandEvent)) {1784 checkForUnknownOptions();
714 unmodified lines
2499 }2500 return arg;2501 });2502}25032504/**2505 * @param {Command} startCommand2506 * @returns {Command[]}2507 * @api private2508 */25092510function getCommandAndParents(startCommand) {2511 const result = [];2512 for (let command = startCommand; command; command = command.parent) {2513 result.push(command);2514 }2515 return result;2516}
modified:Readme.md+28 added
24 unmodified lines
25 - [Specify the argument syntax](#specify-the-argument-syntax)26 - [Custom argument processing](#custom-argument-processing)27 - [Action handler](#action-handler)28 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)29 - [Life cycle hooks](#life-cycle-hooks)30 - [Automated help](#automated-help)31 - [Custom help](#custom-help)32 - [Display help from code](#display-help-from-code)33 - [.usage and .name](#usage-and-name)
523 unmodified lines
557```558559If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.560561### Life cycle hooks562563You can add callback hooks to a command for life cycle events.564565Example file: [hook.js](./examples/hook.js)566567```js568program569 .option('-t, --trace', 'display trace statements for commands')570 .hook('preAction', (thisCommand, actionCommand) => {571 if (thisCommand.opts().trace) {572 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);573 console.log('arguments: %O', actionCommand.args);574 console.log('options: %o', actionCommand.opts());575 }576 });577```578579The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.580581The supported events are:582583- `preAction`: called before action handler for this command and its subcommands584- `postAction`: called after action handler for this command and its subcommands585586The hook is passed the command it was added to, and the command running the action handler.587588## Automated help589590The help information is auto-generated based on the information commander already knows about your program. The default591help option is `-h,--help`.
386 unmodified lines