createCommand factory routine (#1191)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add factory method * Fix return doc * Can not use "this" for return type of createCommand * Use return type of createCommand for subcommand * Add mention of .command from .createCommand * Remove trailing space * Add examples for createCommand * Explain example and make a little more realistic * Add comments pointing from .addCommand to .command One of the downsides of extra ways of adding and creating commands is confusion with the more common way. * Add createCommand to README * Shift command/subcommand contrast * Use single quotes in ts like in js, and clean up whitespace in new code
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+168 added−3 removed
- tests:+36 added−0 removed
- other:+132 added−3 removed
Provenance
- Commit
8c3dd6f- Tree
5dbec43- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
3c9f33f
7 files changed+168 added−3 removed
added:examples/custom-command-class.js+36 added
123456789101112131415161718192021222324252627282930313233343536#!/usr/bin/env node
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repo
// Use a class override of createCommand to customise subcommands,// in this example by adding --debug option.
class MyCommand extends commander.Command { createCommand(name) { const cmd = new MyCommand(name); cmd.option('-d,--debug', 'output options'); return cmd; }};
const program = new MyCommand();program .command('serve') .option('--port <port-number>', 'specify port number', 80) .action((cmd) => { if (cmd.debug) { console.log('Options:'); console.log(cmd.opts()); console.log(); }
console.log(`Start serve on port ${cmd.port}`); });
program.parse();
// Try the following:// node custom-command-class.js help serve// node custom-command-class.js serve --debug// node custom-command-class.js serve --debug --port 8080added:examples/custom-command-function.js+36 added
123456789101112131415161718192021222324252627282930313233343536#!/usr/bin/env node
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repo
// Override createCommand directly to customise subcommands,// in this example by adding --debug option.
const program = commander.createCommand();
// Customise subcommand creationprogram.createCommand = (name) => { const cmd = commander.createCommand(name); cmd.option('-d,--debug', 'output options'); return cmd;};
program .command('serve') .option('--port <port-number>', 'specify port number', 80) .action((cmd) => { if (cmd.debug) { console.log('Options:'); console.log(cmd.opts()); console.log(); }
console.log(`Start serve on port ${cmd.port}`); });
program.parse();
// Try the following:// node custom-command-function.js help serve// node custom-command-function.js serve --debug// node custom-command-function.js serve --debug --port 8080added:tests/createCommand.test.js+36 added
123456789101112131415161718192021222324252627282930313233343536const commander = require('../');
test('when createCommand then unattached', () => { const program = new commander.Command(); const cmd = program.createCommand(); expect(program.commands.length).toBe(0); expect(cmd.parent).toBeFalsy(); // (actually null, but use weaker test for unattached)});
test('when subclass overrides createCommand then subcommand is subclass', () => { class MyClass extends commander.Command { constructor(name) { super(); this.myProperty = 'myClass'; };
createCommand(name) { return new MyClass(name); }; }; const program = new MyClass(); const sub = program.command('sub'); expect(sub.myProperty).toEqual('myClass');});
test('when override createCommand then subcommand is custom', () => { function createCustom(name) { const cmd = new commander.Command(); cmd.myProperty = 'custom'; return cmd; } const program = createCustom(); program.createCommand = createCustom; const sub = program.command('sub'); expect(sub.myProperty).toEqual('custom');});modified:typings/commander-tests.ts+16 added
183 unmodified lines184 const helpOptionThis3: commander.Command = program.helpOption(undefined, 'custom description');185 186 // on187 const onThis: commander.Command = program.on('--help', () => { })188+189+// createCommand190+191+const createInstance1: commander.Command = program.createCommand();192+const createInstance2: commander.Command = program.createCommand('name');193+194+class MyCommand extends commander.Command {195+ createCommand(name?: string) {196+ return new MyCommand(name);197+ }198+ myFunction() {}199+}200+const myProgram = new MyCommand();201+myProgram.myFunction();202+const mySub = myProgram.command('sub');203+mySub.myFunction();modified:typings/index.d.ts+12 added-2 removed
22 unmodified lines23 }24 type OptionConstructor = { new (flags: string, description?: string): Option };25 26 interface ParseOptions {27- from: "node" | "electron" | "user";27+ from: 'node' | 'electron' | 'user';28 }29 30 interface Command {31 [key: string]: any; // options as properties31 unmodified lines63 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`64 * @param opts - configuration options65 * @returns new command66 */67- command(nameAndArgs: string, opts?: CommandOptions): Command;67+ command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;68 /**69 * Define a command, implemented in a separate executable file.70 * 71 * @remarks13 unmodified lines85 */86 command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): this;87 88 /**89+ * Factory routine to create a new unattached command.90+ *91+ * See .command() for creating an attached subcommand, which uses this routine to92+ * create the command. You can override createCommand to customise subcommands.93+ */94+ createCommand(name?: string): Command;95+ 96+ /**97 * Add a prepared subcommand.98 * 99+ * See .command() for creating an attached subcommand which inherits settings from its parent.100+ * 101 * @returns parent command for chaining102 */103 addCommand(cmd: Command): this;104 264 unmodified linesmodified:index.js+18 added-1 removed
164 unmodified lines165 desc = null;166 }167 opts = opts || {};168 const args = nameAndArgs.split(/ +/);169- const cmd = new Command(args.shift());169+ const cmd = this.createCommand(args.shift());170 171 if (desc) {172 cmd.description(desc);173 cmd._executableHandler = true;21 unmodified lines195 return cmd;196 };197 198 /**199+ * Factory routine to create a new unattached command.200+ *201+ * See .command() for creating an attached subcommand, which uses this routine to202+ * create the command. You can override createCommand to customise subcommands.203+ *204+ * @param {string} [name]205+ * @return {Command} new command206+ * @api public207+ */208+209+ createCommand(name) {210+ return new Command(name);211+ };212+213+ /**214 * Add a prepared subcommand.215 *216+ * See .command() for creating an attached subcommand which inherits settings from its parent.217+ *218 * @param {Command} cmd - new subcommand219 * @return {Command} parent command for chaining220 * @api public221 */1491 unmodified linesmodified:Readme.md+14 added
34 unmodified lines35 - [Bits and pieces](#bits-and-pieces)36 - [.parse() and .parseAsync()](#parse-and-parseasync)37 - [Avoiding option name clashes](#avoiding-option-name-clashes)38 - [TypeScript](#typescript)39+ - [createCommand()](#createcommand)40 - [Node options such as `--harmony`](#node-options-such-as---harmony)41 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)42 - [Override exit handling](#override-exit-handling)43 - [Examples](#examples)586 unmodified lines630 ```bash631 node -r ts-node/register pm.ts632 ```633 634+### createCommand()635+636+This factory function creates a new command. It is exported and may be used instead of using `new`, like:637+638+```js639+const { createCommand } = require('commander');640+const program = createCommand();641+```642+643+`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally644+when creating subcommands using `.command()`, and you may override it to645+customise the new subcommand (examples using [subclass](./examples/custom-command-class.js) and [function](./examples/custom-command-function.js)).646+647 ### Node options such as `--harmony`648 649 You can enable `--harmony` option in two ways:650 87 unmodified lines