Rework docs to clarify action vs executable commands (#990)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* TSDoc: defined .command as an overload, with reworked documentstion * Add TSDoc remarks about command description * description is the key difference between the overloads, so be explicit about how it is suppliied. * Rework .command JSDoc to clarify two styles * Minor changes in comments * Rework (sub)command coverage in README * Update CHANGELOG with #938 * Minor improvements to command and argument coverage * Fix indentation in code blocks in README
authored by John Gee · committed by GitHub · parent 270cdf3 · Browse files · 5 files·+134 added−162 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+134 added−162 removed
- other:+134 added−162 removed
Provenance
- Commit
fe7850a- Tree
9800d91- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
270cdf3
5 files changed+134 added−162 removed
modified:typings/commander-tests.ts+6 added-1 removed
80 unmodified lines8182838485868788894 unmodified lines9495969798991001011021039910480 unmodified lines});
program .command('allow-unknown-option') .description("description") .allowUnknownOption() .action(() => { console.log('unknown option is allowed'); });4 unmodified lines .action((cmd, env) => { console.log(cmd, env); });
program .command("name1", "description") .command("name2", "description", { isDefault:true })
program.parse(process.argv);
console.log('stuff');No newline at end of fileconsole.log('stuff');modified:typings/index.d.ts+37 added-57 removed
47 unmodified lines48 */49 version(str: string, flags?: string, description?: string): Command;50 51 /**52- * Add command `name`.53- *54- * The `.action()` callback is invoked when the55- * command `name` is specified via __ARGV__,56- * and the remaining arguments are applied to the57- * function for access.58- *59- * When the `name` is "*" an un-matched command60- * will be passed as the first arg, followed by61- * the rest of __ARGV__ remaining.62- *52+ * Define a command, implemented using an action handler.53+ * 54+ * @remarks55+ * The command description is supplied using `.description`, not as a parameter to `.command`.56+ * 57 * @example64- * program65- * .version('0.0.1')66- * .option('-C, --chdir <path>', 'change the working directory')67- * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')68- * .option('-T, --no-tests', 'ignore test hook')69- *70- * program71- * .command('setup')72- * .description('run remote setup commands')73- * .action(function() {74- * console.log('setup');75- * });76- *77- * program78- * .command('exec <cmd>')79- * .description('run the given remote command')80- * .action(function(cmd) {81- * console.log('exec "%s"', cmd);82- * });83- *84- * program85- * .command('teardown <dir> [otherDirs...]')86- * .description('run teardown commands')87- * .action(function(dir, otherDirs) {88- * console.log('dir "%s"', dir);89- * if (otherDirs) {90- * otherDirs.forEach(function (oDir) {91- * console.log('dir "%s"', oDir);92- * });93- * }94- * });95- *96- * program97- * .command('*')98- * .description('deploy the given env')99- * .action(function(env) {100- * console.log('deploying "%s"', env);101- * });102- *103- * program.parse(process.argv);104- *105- * @param {string} name106- * @param {string} [desc] for git-style sub-commands107- * @param {CommandOptions} [opts] command options108- * @returns {Command} the new command58+ * ```ts59+ * program60+ * .command('clone <source> [destination]')61+ * .description('clone a repository into a newly created directory')62+ * .action((source, destination) => {63+ * console.log('clone command called');64+ * });65+ * ```66+ * 67+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`68+ * @param opts - configuration options69+ * @returns new command70 */110- command(name: string, desc?: string, opts?: commander.CommandOptions): Command;71+ command(nameAndArgs: string, opts?: commander.CommandOptions): Command;72+ /**73+ * Define a command, implemented in a separate executable file.74+ * 75+ * @remarks76+ * The command description is supplied as the second parameter to `.command`.77+ * 78+ * @example79+ * ```ts80+ * program81+ * .command('start <service>', 'start named service')82+ * .command('stop [service]', 'stop named serice, or all if no name supplied');83+ * ```84+ * 85+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`86+ * @param description - description of executable command87+ * @param opts - configuration options88+ * @returns top level command for chaining more command definitions89+ */90+ command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command;91 92 /**93 * Define argument syntax for the top-level command.94 *205 unmodified linesmodified:CHANGELOG.md+1 added
13 unmodified lines14 * Fix behavior of --no-* options (#795)15 * can now define both `--foo` and `--no-foo`16 * custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`)17 * default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false)18+ * Change docs for `.command` to contrast action handler vs git-style executable. TypeScript now uses overloaded function. (#938)19 20 2.20.0 / 2019-04-0221 ==================22 404 unmodified linesmodified:index.js+18 added-50 removed
107 unmodified lines108 this._helpLongFlag = '--help';109 }110 111 /**112- * Add command `name`.112+ * Define a command.113 *114- * The `.action()` callback is invoked when the115- * command `name` is specified via __ARGV__,116- * and the remaining arguments are applied to the117- * function for access.114+ * There are two styles of command: pay attention to where to put the description.115 *119- * When the `name` is "*" an un-matched command120- * will be passed as the first arg, followed by121- * the rest of __ARGV__ remaining.122- *116 * Examples:117 *118+ * // Command implemented using action handler (description is supplied separately to `.command`)119 * program126- * .version('0.0.1')127- * .option('-C, --chdir <path>', 'change the working directory')128- * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')129- * .option('-T, --no-tests', 'ignore test hook')130- *131- * program132- * .command('setup')133- * .description('run remote setup commands')134- * .action(function() {135- * console.log('setup');120+ * .command('clone <source> [destination]')121+ * .description('clone a repository into a newly created directory')122+ * .action((source, destination) => {123+ * console.log('clone command called');124 * });125 *126+ * // Command implemented using separate executable file (description is second parameter to `.command`)127 * program139- * .command('exec <cmd>')140- * .description('run the given remote command')141- * .action(function(cmd) {142- * console.log('exec "%s"', cmd);143- * });128+ * .command('start <service>', 'start named service')129+ * .command('stop [service]', 'stop named serice, or all if no name supplied');130 *145- * program146- * .command('teardown <dir> [otherDirs...]')147- * .description('run teardown commands')148- * .action(function(dir, otherDirs) {149- * console.log('dir "%s"', dir);150- * if (otherDirs) {151- * otherDirs.forEach(function (oDir) {152- * console.log('dir "%s"', oDir);153- * });154- * }155- * });156- *157- * program158- * .command('*')159- * .description('deploy the given env')160- * .action(function(env) {161- * console.log('deploying "%s"', env);162- * });163- *164- * program.parse(process.argv);165- *166- * @param {String} name167- * @param {String} [desc] for git-style sub-commands168- * @return {Command} the new command131+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`132+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)133+ * @param {Object} [execOpts] - configuration options (for executable)134+ * @return {Command} returns new command for action handler, or top-level command for executable command135 * @api public136 */137 172-Command.prototype.command = function(name, desc, opts) {138+Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) {139+ var desc = actionOptsOrExecDesc;140+ var opts = execOpts;141 if (typeof desc === 'object' && desc !== null) {142 opts = desc;143 desc = null;144 }145 opts = opts || {};178- var args = name.split(/ +/);146+ var args = nameAndArgs.split(/ +/);147 var cmd = new Command(args.shift());148 149 if (desc) {150 cmd.description(desc);1113 unmodified linesmodified:Readme.md+72 added-54 removed
214 unmodified lines215 216 The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.217 218 ```js219- program.version('0.0.1');219+program.version('0.0.1');220 ```221 222 ```bash223- $ ./examples/pizza -V224- 0.0.1223+$ ./examples/pizza -V224+0.0.1225 ```226 227 You may change the flags and description by passing additional parameters to the `version` method, using228 the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required.1 unmodified line230 ```js231 program.version('0.0.1', '-v, --vers', 'output the current version');232 ```233 234-## Command-specific options234+## Commands235 236-You can attach options to a command.236+You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.237 238-```js239-#!/usr/bin/env node238+For example:239 241-var program = require('commander');242-240+```js241+// Command implemented using action handler (description is supplied separately to `.command`)242+// Returns new command for configuring.243 program244- .command('rm <dir>')245- .option('-r, --recursive', 'Remove recursively')246- .action(function (dir, cmd) {247- console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))248- })244+ .command('clone <source> [destination]')245+ .description('clone a repository into a newly created directory')246+ .action((source, destination) => {247+ console.log('clone command called');248+ });249 250-program.parse(process.argv)250+// Command implemented using separate executable file (description is second parameter to `.command`)251+// Returns top-level command for adding more commands.252+program253+ .command('start <service>', 'start named service')254+ .command('stop [service]', 'stop named service, or all if no name supplied');255 ```256 253-A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.257+### Specify the argument syntax258 255-## Variadic arguments259+You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.260 257- The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to258- append `...` to the argument name. Here is an example:261 262 ```js261-#!/usr/bin/env node263+var program = require('commander');264 263-/**264- * Module dependencies.265- */265+program266+ .version('0.1.0')267+ .arguments('<cmd> [env]')268+ .action(function (cmd, env) {269+ cmdValue = cmd;270+ envValue = env;271+ });272 273+program.parse(process.argv);274+275+if (typeof cmdValue === 'undefined') {276+ console.error('no command given!');277+ process.exit(1);278+}279+console.log('command:', cmdValue);280+console.log('environment:', envValue || "no environment given");281+```282+283+ The last argument of a command can be variadic, and only the last argument. To make an argument variadic you284+ append `...` to the argument name. For example:285+286+```js287 var program = require('commander');288 289 program290 .version('0.1.0')9 unmodified lines300 301 program.parse(process.argv);302 ```303 284- An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed285- to your action as demonstrated above.304+The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.)305 287-## Specify the argument syntax306+### Action handler (sub)commands307 289-```js290-#!/usr/bin/env node308+You can add options to a command that uses an action handler.309+The action handler gets passed a parameter for each argument you declared, and one additional argument which is the310+command object itself. This command argument has the values for the command-specific options added as properties.311 312+```js313 var program = require('commander');314 315 program295- .version('0.1.0')296- .arguments('<cmd> [env]')297- .action(function (cmd, env) {298- cmdValue = cmd;299- envValue = env;300- });316+ .command('rm <dir>')317+ .option('-r, --recursive', 'Remove recursively')318+ .action(function (dir, cmdObj) {319+ console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))320+ })321 302-program.parse(process.argv);303-304-if (typeof cmdValue === 'undefined') {305- console.error('no command given!');306- process.exit(1);307-}308-console.log('command:', cmdValue);309-console.log('environment:', envValue || "no environment given");322+program.parse(process.argv)323 ```311-Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.324 313-## Git-style sub-commands325+A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.326 327+Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.328+329+### Git-style executable (sub)commands330+331+When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.332+Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.333+334+You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.335+336 ```js337 // file: ./examples/pm338 var program = require('commander');339 4 unmodified lines344 .command('list', 'list packages installed', {isDefault: true})345 .parse(process.argv);346 ```347 327-When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. 328-The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.348+Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.349 330-Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.331-350 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.351 334-### `--harmony`335-336-You can enable `--harmony` option in two ways:337-* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.338-* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.339-352 ## Automated --help353 354 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:355 140 unmodified lines496 ```bash497 node -r ts-node/register pm.ts498 ```499 500+### Node options such as `--harmony`501+502+You can enable `--harmony` option in two ways:503+* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. (Note Windows does not support this pattern.)504+* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.505+506 ## Examples507 508 ```js509 var program = require('commander');46 unmodified lines