Skip to content

Commit

Permalink
Add Command.awaitHook() (tj#1900)
Browse files Browse the repository at this point in the history
  • Loading branch information
aweebit committed Jul 6, 2023
1 parent 7fe7831 commit 4061bff
Show file tree
Hide file tree
Showing 6 changed files with 165 additions and 1 deletion.
21 changes: 21 additions & 0 deletions lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,27 @@ Expecting one of '${allowedValues.join("', '")}'`);
return this;
}

/**
* Add hook to await argument and option values before calling action handlers for this command and its nested subcommands.
* Useful for asynchronous custom processing (parseArg) of arguments and option-arguments.
*/

awaitHook() {
this.hook('preAction', async function awaitHook(thisCommand, actionCommand) {
actionCommand.processedArgs = await Promise.all(
actionCommand.processedArgs
);

for (const [key, value] of Object.entries(actionCommand.opts())) {
actionCommand.setOptionValueWithSource(
key, await value, actionCommand._optionValueSources[key]
);
}
});

return this;
}

/**
* Register callback to use as replacement for calling process.exit.
*
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

128 changes: 128 additions & 0 deletions tests/command.awaitHook.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
const commander = require('../');

describe('awaitHook with arguments', () => {
test('when awaitHook and arguments with custom processing then .processedArgs and actioon arguments resolved from callback', async() => {
const resolvedValues = [3, 4];
const awaited = [
{ then: (fn) => fn(resolvedValues[0]) },
resolvedValues[1]
];
const mockCoercions = awaited.map(
value => jest.fn().mockImplementation(() => value)
);

let actionValues;
const program = new commander.Command();
program
.argument('<arg>', 'desc', mockCoercions[0])
.argument('[arg]', 'desc', mockCoercions[1])
.awaitHook()
.action((...args) => {
actionValues = args.slice(0, resolvedValues.length);
});

const result = program.parseAsync(['1', '2'], { from: 'user' });
expect(program.processedArgs).toEqual(awaited);
await result;
expect(program.processedArgs).toEqual(resolvedValues);
expect(actionValues).toEqual(resolvedValues);
});

test('when awaitHook and arguments not specified with default values then .processedArgs and actioon arguments resolved from default values', async() => {
const resolvedValues = [1, 2];
const awaited = [
{ then: (fn) => fn(resolvedValues[0]) },
resolvedValues[1]
];

let actionValues;
const program = new commander.Command();
program
.argument('[arg]', 'desc', awaited[0])
.argument('[arg]', 'desc', awaited[1])
.awaitHook()
.action((...args) => {
actionValues = args.slice(0, resolvedValues.length);
});

const result = program.parseAsync([], { from: 'user' });
expect(program.processedArgs).toEqual(awaited);
await result;
expect(program.processedArgs).toEqual(resolvedValues);
expect(actionValues).toEqual(resolvedValues);
});
});

describe('awaitHook with options', () => {
test('when awaitHook and options with custom processing then .opts() resolved from callback', async() => {
const resolvedValues = { a: 3, b: 4 };
const awaited = {
a: { then: (fn) => fn(resolvedValues.a) },
b: resolvedValues.b
};
const mockCoercions = Object.entries(awaited).reduce((acc, [key, value]) => {
acc[key] = jest.fn().mockImplementation(() => value);
return acc;
}, {});

const program = new commander.Command();
program
.option('-a <arg>', 'desc', mockCoercions.a)
.option('-b [arg]', 'desc', mockCoercions.b)
.awaitHook()
.action(() => {});

const result = program.parseAsync(['-a', '1', '-b', '2'], { from: 'user' });
expect(program.opts()).toEqual(awaited);
await result;
expect(program.opts()).toEqual(resolvedValues);
expect(program.getOptionValueSource('a')).toEqual('cli');
expect(program.getOptionValueSource('b')).toEqual('cli');
});

test('when awaitHook and options not specified with default values then .opts() resolved from default values', async() => {
const resolvedValues = { a: 1, b: 2 };
const awaited = {
a: { then: (fn) => fn(resolvedValues.a) },
b: resolvedValues.b
};

const program = new commander.Command();
program
.option('-a <arg>', 'desc', awaited.a)
.option('-b [arg]', 'desc', awaited.b)
.awaitHook()
.action(() => {});

const result = program.parseAsync([], { from: 'user' });
expect(program.opts()).toEqual(awaited);
await result;
expect(program.opts()).toEqual(resolvedValues);
expect(program.getOptionValueSource('a')).toEqual('default');
expect(program.getOptionValueSource('b')).toEqual('default');
});

test('when awaitHook and implied option values then .opts() resolved from implied values', async() => {
const resolvedValues = { a: 1, b: 2 };
const awaited = {
a: { then: (fn) => fn(resolvedValues.a) },
b: resolvedValues.b
};

const option = new commander.Option('-c').implies(awaited);
const program = new commander.Command();
program
.option('-a <arg>')
.option('-b [arg]')
.addOption(option)
.awaitHook()
.action(() => {});

const result = program.parseAsync(['-c'], { from: 'user' });
expect(program.opts()).toEqual({ ...awaited, c: true });
await result;
expect(program.opts()).toEqual({ ...resolvedValues, c: true });
expect(program.getOptionValueSource('a')).toEqual('implied');
expect(program.getOptionValueSource('b')).toEqual('implied');
});
});
6 changes: 6 additions & 0 deletions tests/command.chain.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ describe('Command methods that should return this for chaining', () => {
expect(result).toBe(program);
});

test('when call .awaitHook() then returns this', () => {
const program = new Command();
const result = program.awaitHook();
expect(result).toBe(program);
});

test('when call .setOptionValue() then returns this', () => {
const program = new Command();
const result = program.setOptionValue('foo', 'bar');
Expand Down
6 changes: 6 additions & 0 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,12 @@ export class Command {
*/
hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;

/**
* Add hook to await argument and option values before calling action handlers for this command and its nested subcommands.
* Useful for asynchronous custom processing (parseArg) of arguments and option-arguments.
*/
awaitHook(): this;

/**
* Register callback to use as replacement for calling process.exit.
*/
Expand Down
3 changes: 3 additions & 0 deletions typings/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ expectType<commander.Command>(program.hook('preSubcommand', (thisCommand, subcom
expectType<commander.Command>(subcommand);
}));

// awaitHook
expectType<commander.Command>(program.awaitHook());

// action
expectType<commander.Command>(program.action(() => {}));
expectType<commander.Command>(program.action(async() => {}));
Expand Down

0 comments on commit 4061bff

Please sign in to comment.