Skip to content
Myr

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

5 files+134 added−162 removed

modified:typings/commander-tests.ts+6 added-1 removed
modified:typings/index.d.ts+37 added-57 removed
47 unmodified lines
48 */49 version(str: string, flags?: string, description?: string): Command;5051 /**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;9192 /**93 * Define argument syntax for the top-level command.94 *
205 unmodified lines
modified:CHANGELOG.md+1 added
13 unmodified lines
14 * 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)19202.20.0 / 2019-04-0221==================22
404 unmodified lines
modified:index.js+18 added-50 removed
107 unmodified lines
108 this._helpLongFlag = '--help';109}110111/**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 */137172Command.prototype.command = function(name, desc, opts) {138Command.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());148149 if (desc) {150 cmd.description(desc);
1113 unmodified lines
modified:Readme.md+72 added-54 removed
214 unmodified lines
215216The 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.217218```js219 program.version('0.0.1');219program.version('0.0.1');220```221222```bash223 $ ./examples/pizza -V224 0.0.1223$ ./examples/pizza -V2240.0.1225```226227You may change the flags and description by passing additional parameters to the `version` method, using228the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required.
1 unmodified line
230```js231program.version('0.0.1', '-v, --vers', 'output the current version');232```233234## Command-specific options234## Commands235236You can attach options to a command.236You 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...`.237238```js239#!/usr/bin/env node238For example:239241var program = require('commander');242240```js241// Command implemented using action handler (description is supplied separately to `.command`)242// Returns new command for configuring.243program244 .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 });249250program.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.252program253 .command('start <service>', 'start named service')254 .command('stop [service]', 'stop named service, or all if no name supplied');255```256253A 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 syntax258255## Variadic arguments259You 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.260257 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:261262```js261#!/usr/bin/env node263var program = require('commander');264263/**264 * Module dependencies.265 */265program266 .version('0.1.0')267 .arguments('<cmd> [env]')268 .action(function (cmd, env) {269 cmdValue = cmd;270 envValue = env;271 });272273program.parse(process.argv);274275if (typeof cmdValue === 'undefined') {276 console.error('no command given!');277 process.exit(1);278}279console.log('command:', cmdValue);280console.log('environment:', envValue || "no environment given");281```282283 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:285286```js287var program = require('commander');288289program290 .version('0.1.0')
9 unmodified lines
300301program.parse(process.argv);302```303284 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.304The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.)305287## Specify the argument syntax306### Action handler (sub)commands307289```js290#!/usr/bin/env node308You can add options to a command that uses an action handler.309The action handler gets passed a parameter for each argument you declared, and one additional argument which is the310command object itself. This command argument has the values for the command-specific options added as properties.311312```js313var program = require('commander');314315program295 .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 })321302program.parse(process.argv);303304if (typeof cmdValue === 'undefined') {305 console.error('no command given!');306 process.exit(1);307}308console.log('command:', cmdValue);309console.log('environment:', envValue || "no environment given");322program.parse(process.argv)323```311Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.324313## Git-style sub-commands325A 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.326327Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.328329### Git-style executable (sub)commands330331When `.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.332Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.333334You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.335336```js337// file: ./examples/pm338var program = require('commander');339
4 unmodified lines
344 .command('list', 'list packages installed', {isDefault: true})345 .parse(process.argv);346```347327When `.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. 328The 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`.348Configuration 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.349330Options 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.331350If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.351334### `--harmony`335336You 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.339352## Automated --help353354 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 lines
496```bash497node -r ts-node/register pm.ts498```499500### Node options such as `--harmony`501502You 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.505506## Examples507508```js509var program = require('commander');
46 unmodified lines