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
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
Provenance
- Commit
c20284d- Tree
feed535- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
6c06528
7 files changed+525 added−10 removed
added:examples/hook.js+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#!/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();
// This example shows using some hooks for life cycle events.
const timeLabel = 'command duration';program .option('-p, --profile', 'show how long command takes') .hook('preAction', (thisCommand) => { if (thisCommand.opts().profile) { console.time(timeLabel); } }) .hook('postAction', (thisCommand) => { if (thisCommand.opts().profile) { console.timeEnd(timeLabel); } });
program .option('-t, --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()}`); console.log('arguments: %O', actionCommand.args); console.log('options: %o', actionCommand.opts()); 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.command('hello') .option('-e, --example') .action(() => console.log('Hello, world'));
// 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 delaymodified:tests/command.chain.test.js+6 added
164 unmodified lines165 const result = program.enablePositionalOptions();166 expect(result).toBe(program);167 });168 169+ test('when call .hook() then returns this', () => {170+ const program = new Command();171+ const result = program.hook('preAction', () => {});172+ expect(result).toBe(program);173+ });174+175 test('when call .setOptionValue() then returns this', () => {176 const program = new Command();177 const result = program.setOptionValue();178 expect(result).toBe(program);2 unmodified linesadded:tests/command.hook.test.js+323 added
1+const commander = require('../');2+3+test('when hook event wrong then throw', () => {4+ const program = new commander.Command();5+ expect(() => {6+ program.hook('silly', () => {});7+ }).toThrow();8+});9+10+test('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+});19+20+describe('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+ });30+31+ 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+ });40+41+ 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+ });51+52+ 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+ });62+63+ 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+ });74+75+ 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+ });86+87+ 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+});104+105+describe('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+ });115+116+ 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+ });126+127+ 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+ });136+137+ 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+ });148+149+ 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+ });161+162+ 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+ });174+175+ 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+ });186+187+ 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+ });199+200+ 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+ });212+213+ 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+});225+226+describe('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+ });241+242+ 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+ });256+257+ 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+ });272+273+ 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+ });288+289+ 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+ });304+305+ 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 lines192 193 }194 195 type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';196+type HookEvent = 'preAction' | 'postAction';197 198 export interface OptionValues {199 [key: string]: any;200 }128 unmodified lines329 */330 addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;331 332 /**333+ * Add hook for life cycle event.334+ */335+ hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;336+337+ /**338 * Register callback to use as replacement for calling process.exit.339 */340 exitOverride(callback?: (err: CommanderError) => never|void): this;341 369 unmodified linesmodified:typings/index.test-d.ts+15 added-9 removed
1 unmodified line2 import {expectType} from 'tsd';3 4 // We are are not just checking return types here, we are also implicitly checking that the expected syntax is allowed.5 6+/* eslint-disable @typescript-eslint/no-empty-function */7+8 const program: commander.Command = new commander.Command();9 // @ts-expect-error Check that Command is strongly typed and does not allow arbitrary properties10 program.silly; // <-- Error, hurrah!11 59 unmodified lines71 // Async callback from spawn events, not useful to throw.72 }73 }));74 73-// action74-expectType<commander.Command>(program.action(() => {75- // do nothing.75+// hook76+expectType<commander.Command>(program.hook('preAction', () => {}));77+expectType<commander.Command>(program.hook('postAction', () => {}));78+expectType<commander.Command>(program.hook('preAction', async() => {}));79+expectType<commander.Command>(program.hook('preAction', (thisCommand, actionCommand) => {80+ // implicit parameter types81+ expectType<commander.Command>(thisCommand);82+ expectType<commander.Command>(actionCommand);83 }));77-expectType<commander.Command>(program.action(async() => {78- // do nothing.79-}));84 85+// action86+expectType<commander.Command>(program.action(() => {}));87+expectType<commander.Command>(program.action(async() => {}));88+89 // option90 expectType<commander.Command>(program.option('-a,--alpha'));91 expectType<commander.Command>(program.option('-p, --peppers', 'Add peppers'));92 expectType<commander.Command>(program.option('-s, --string [value]', 'default string', 'value'));154 unmodified lines247 return '';248 }));249 250 // on243-expectType<commander.Command>(program.on('command:foo', () => {244- // do nothing.245-}));251+expectType<commander.Command>(program.on('command:foo', () => {}));252 253 // createCommand254 expectType<commander.Command>(program.createCommand());255 expectType<commander.Command>(program.createCommand('name'));114 unmodified linesmodified:index.js+91 added-1 removed
676 unmodified lines677 this._description = '';678 this._argsDescription = undefined; // legacy679 this._enablePositionalOptions = false;680 this._passThroughOptions = false;681+ this._lifeCycleHooks = {}; // a hash of arrays682 683 // see .configureOutput() for docs684 this._outputConfiguration = {685 writeOut: (str) => process.stdout.write(str),303 unmodified lines989 return this._addImplicitHelpCommand;990 };991 992 /**993+ * Add hook for life cycle event.994+ *995+ * @param {string} event996+ * @param {Function} listener997+ * @return {Command} `this` command for chaining998+ */999+1000+ 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}'.1004+Expecting 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+ }1013+1014+ /**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 chaining644 unmodified lines1663 return actionArgs;1664 }1665 1666 /**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+ */1673+1674+ _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+ }1683+1684+ /**1685+ *1686+ * @param {Promise|undefined} promise1687+ * @param {string} event1688+ * @return {Promise|undefined}1689+ * @api private1690+ */1691+1692+ _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+ }1706+1707+ hooks.forEach((hookDetail) => {1708+ result = this._chainOrCall(result, () => {1709+ return hookDetail.callback(hookDetail.hookedCommand, this);1710+ });1711+ });1712+ return result;1713+ }1714+1715+ /**1716 * Process arguments in context of this command.1717 * Returns action result, in case it is a promise.1718 *1719 * @api private51 unmodified lines1771 const commandEvent = `command:${this.name()}`;1772 if (this._actionHandler) {1773 checkForUnknownOptions();1774 checkNumberOfArguments();1703- const actionResult = this._actionHandler(this._getActionArguments());1775+1776+ 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 lines2499 }2500 return arg;2501 });2502 }2503+2504+/**2505+ * @param {Command} startCommand2506+ * @returns {Command[]}2507+ * @api private2508+ */2509+2510+function 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 lines25 - [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 lines557 ```558 559 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.560 561+### Life cycle hooks562+563+You can add callback hooks to a command for life cycle events.564+565+Example file: [hook.js](./examples/hook.js)566+567+```js568+program569+ .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+```578+579+The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.580+581+The supported events are:582+583+- `preAction`: called before action handler for this command and its subcommands584+- `postAction`: called after action handler for this command and its subcommands585+586+The hook is passed the command it was added to, and the command running the action handler.587+588 ## Automated help589 590 The help information is auto-generated based on the information commander already knows about your program. The default591 help option is `-h,--help`.386 unmodified lines