Add .env method to Option for consulting environment variable for option value (#1587)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First cut at env support for options, including custom processing * Basic tests * Fill out special cases * Skip test that picked up a problem! * Add option source so can make decisions about priorities when processing env * Rework processing to preserve existing behaviour and handle cli and env same way * Remove _doParseOptionArg as no longer used, refactored in a more direct way * Update JSDoc/TSDoc/tsd * Add help test for env * Add env event tests * Add env to help for negated option * Make env error message more explicit * Add example file * Add env to README * name param for .env is not optional * Add test that env counts for mandatory options * Lint * Remove stale parameter * Minor lint
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+482 added−34 removed
- tests:+335 added−1 removed
- other:+147 added−33 removed
Provenance
- Commit
8571a75- Tree
0f9fdca- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
3a0ef21
12 files changed+482 added−34 removed
added:examples/options-env.js+38 added
1234567891011121314151617181920212223242526272829303132333435363738#!/usr/bin/env node// const { Command, Option } = require('commander'); // (normal include)const { Command, Option } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program.addOption(new Option('-p, --port <number>', 'specify port number') .default(80) .env('PORT'));program.addOption(new Option('-c, --colour', 'turn on colour output') .env('COLOUR'));program.addOption(new Option('-C, --no-colour', 'turn off colour output') .env('NO_COLOUR'));program.addOption(new Option('-s, --size <type>', 'specify size of drink') .choices(['small', 'medium', 'large']) .env('SIZE'));
program.parse();console.log(program.opts());
// Try the following:// node options-env.js --help//// node options-env.js// PORT=9001 node options-env.js// PORT=9001 node options-env.js --port 123//// COLOUR= node options-env.js// COLOUR= node options-env.js --no-colour// NO_COLOUR= node options-env.js// NO_COLOUR= node options-env.js --colour//// SIZE=small node options-env.js// SIZE=enormous node options-env.js// SIZE=enormous node options-env.js --size=largemodified:examples/options-extra.js+11 added-8 removed
12345567678910101112111213141516171819201920212223#!/usr/bin/env node
// This is used as an example in the README for extra option features.// See also options-env.js for more extensive env examples.
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();// const { Command, Option } = require('commander'); // (normal include)const { Command, Option } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program .addOption(new commander.Option('-s, --secret').hideHelp()) .addOption(new commander.Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')) .addOption(new commander.Option('-d, --drink <size>', 'drink cup size').choices(['small', 'medium', 'large'])); .addOption(new Option('-s, --secret').hideHelp()) .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')) .addOption(new Option('-d, --drink <size>', 'drink cup size').choices(['small', 'medium', 'large'])) .addOption(new Option('-p, --port <number>', 'port number').env('PORT'));
program.parse();
console.log('Options: ', program.opts());
// Try the following:// node options-extra.js --help// node options-extra.js --drink huge// node options-extra.js --help// node options-extra.js --drink huge// PORT=80 node options-extra.jsmodified:lib/command.js+54 added-10 removed
33 unmodified lines34 this.processedArgs = []; // like .args but after custom processing and collecting variadic35 this._scriptPath = null;36 this._name = name || '';37 this._optionValues = {};38+ this._optionValueSources = {}; // default < env < cli39 this._storeOptionsAsProperties = false;40 this._actionHandler = null;41 this._executableHandler = false;42 this._executableFile = null; // custom name for executable469 unmodified lines512 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;513 }514 // preassign only if we have a default515 if (defaultValue !== undefined) {515- this.setOptionValue(name, defaultValue);516+ this._setOptionValueWithSource(name, defaultValue, 'default');517 }518 }519 520 // register the option521 this.options.push(option);522 522- // when it's passed assign the value523- // and conditionally invoke the callback524- this.on('option:' + oname, (val) => {523+ // handler for cli and env supplied values524+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {525+ // Note: using closure to access lots of lexical scoped variables.526 const oldValue = this.getOptionValue(name);527 528 // custom processing529 if (val !== null && option.parseArg) {530 try {531 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);532 } catch (err) {533 if (err.code === 'commander.invalidArgument') {533- const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;534+ const message = `${invalidValueMessage} ${err.message}`;535 this._displayError(err.exitCode, err.code, message);536 }537 throw err;538 }4 unmodified lines543 // unassigned or boolean value544 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {545 // if no value, negate false, and we have a default, then use it!546 if (val == null) {546- this.setOptionValue(name, option.negate547- ? false548- : defaultValue || true);547+ this._setOptionValueWithSource(name, option.negate ? false : defaultValue || true, valueSource);548 } else {550- this.setOptionValue(name, val);549+ this._setOptionValueWithSource(name, val, valueSource);550 }551 } else if (val !== null) {552 // reassign554- this.setOptionValue(name, option.negate ? false : val);553+ this._setOptionValueWithSource(name, option.negate ? false : val, valueSource);554 }555+ };556+557+ this.on('option:' + oname, (val) => {558+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;559+ handleOptionValue(val, invalidValueMessage, 'cli');560 });561 562+ if (option.envVar) {563+ this.on('optionEnv:' + oname, (val) => {564+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;565+ handleOptionValue(val, invalidValueMessage, 'env');566+ });567+ }568+569 return this;570 }571 572 /**205 unmodified lines778 return this;779 };780 781 /**782+ * @api private783+ */784+ _setOptionValueWithSource(key, value, source) {785+ this.setOptionValue(key, value);786+ this._optionValueSources[key] = source;787+ }788+789+ /**790 * Get user arguments implied or explicit arguments.791 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.792 *793 * @api private355 unmodified lines1149 */1150 1151 _parseCommand(operands, unknown) {1152 const parsed = this.parseOptions(unknown);1153+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1154 operands = operands.concat(parsed.operands);1155 unknown = parsed.unknown;1156 this.args = operands.concat(unknown);1157 273 unmodified lines1431 this._exit(exitCode, code, message);1432 }1433 1434 /**1435+ * Apply any option related environment variables, if option does1436+ * not have a value from cli or client code.1437+ *1438+ * @api private1439+ */1440+ _parseOptionsEnv() {1441+ this.options.forEach((option) => {1442+ if (option.envVar && option.envVar in process.env) {1443+ const optionKey = option.attributeName();1444+ // env is second lowest priority source, above default1445+ if (this.getOptionValue(optionKey) === undefined || this._optionValueSources[optionKey] === 'default') {1446+ if (option.required || option.optional) { // option can take a value1447+ // keep very simple, optional always takes value1448+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1449+ } else { // boolean1450+ // keep very simple, only care that envVar defined and not the value1451+ this.emit(`optionEnv:${option.name()}`);1452+ }1453+ }1454+ }1455+ });1456+ }1457+1458+ /**1459 * Argument `name` is missing.1460 *1461 * @param {string} name1462 * @api private418 unmodified linesmodified:lib/help.js+8 added-5 removed
232 unmodified lines233 * @return {string}234 */235 236 optionDescription(option) {237- if (option.negate) {238- return option.description;239- }237 const extraInfo = [];238+ // Some of these do not make sense for negated boolean and suppress for backwards compatibility.239+241- if (option.argChoices) {240+ if (option.argChoices && !option.negate) {241 extraInfo.push(242 // use stringify to match the display of the default value243 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);244 }246- if (option.defaultValue !== undefined) {245+ if (option.defaultValue !== undefined && !option.negate) {246 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);247 }248+ if (option.envVar !== undefined) {249+ extraInfo.push(`env: ${option.envVar}`);250+ }251 if (extraInfo.length > 0) {252 return `${option.description} (${extraInfo.join(', ')})`;253 }254+255 return option.description;256 };257 258 /**138 unmodified linesmodified:lib/option.js+14 added
26 unmodified lines27 this.negate = this.long.startsWith('--no-');28 }29 this.defaultValue = undefined;30 this.defaultValueDescription = undefined;31+ this.envVar = undefined;32 this.parseArg = undefined;33 this.hidden = false;34 this.argChoices = undefined;35 }12 unmodified lines48 return this;49 };50 51 /**52+ * Set environment variable to check for option value.53+ * Priority order of option values is default < env < cli54+ *55+ * @param {string} name56+ * @return {Option}57+ */58+59+ env(name) {60+ this.envVar = name;61+ return this;62+ };63+64+ /**65 * Set the custom handler for processing CLI option arguments into option values.66 *67 * @param {Function} [fn]68 * @return {Option}140 unmodified linesmodified:tests/help.optionDescription.test.js+7 added
22 unmodified lines23242526272829303132333435363712 unmodified lines22 unmodified lines const helper = new commander.Help(); expect(helper.optionDescription(option)).toEqual('description (default: "default")'); });
test('when option has env then return description and env name', () => { const description = 'description'; const option = new commander.Option('-a', description).env('ENV'); const helper = new commander.Help(); expect(helper.optionDescription(option)).toEqual('description (env: ENV)'); });
test('when option has default value description then return description and custom default description', () => { const description = 'description'; const defaultValueDescription = 'custom'; const option = new commander.Option('-a', description).default('default value', defaultValueDescription);12 unmodified linesmodified:tests/option.chain.test.js+6 added
28 unmodified lines293031323334353637383928 unmodified lines const option = new Option('-e,--example <value>'); const result = option.choices(['a']); expect(result).toBe(option); });
test('when call .env() then returns this', () => { const option = new Option('-e,--example <value>'); const result = option.env('e'); expect(result).toBe(option); });});added:tests/options.env.test.js+308 added
1+const commander = require('../');2+3+// treating optional same as required, treat as option taking value rather than as boolean4+describe.each(['-f, --foo <required-arg>', '-f, --foo [optional-arg]'])('option declared as: %s', (fooFlags) => {5+ test('when env undefined and no cli then option undefined', () => {6+ const program = new commander.Command();7+ program.addOption(new commander.Option(fooFlags).env('BAR'));8+ program.parse([], { from: 'user' });9+ expect(program.opts().foo).toBeUndefined();10+ });11+12+ test('when env defined and no cli then option from env', () => {13+ const program = new commander.Command();14+ process.env.BAR = 'env';15+ program.addOption(new commander.Option(fooFlags).env('BAR'));16+ program.parse([], { from: 'user' });17+ expect(program.opts().foo).toBe('env');18+ delete process.env.BAR;19+ });20+21+ test('when env defined and cli then option from cli', () => {22+ const program = new commander.Command();23+ process.env.BAR = 'env';24+ program.addOption(new commander.Option(fooFlags).env('BAR'));25+ program.parse(['--foo', 'cli'], { from: 'user' });26+ expect(program.opts().foo).toBe('cli');27+ delete process.env.BAR;28+ });29+30+ test('when default and env undefined and no cli then option from default', () => {31+ const program = new commander.Command();32+ program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));33+ program.parse([], { from: 'user' });34+ expect(program.opts().foo).toBe('default');35+ });36+37+ test('when default and env defined and no cli then option from env', () => {38+ const program = new commander.Command();39+ process.env.BAR = 'env';40+ program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));41+ program.parse([], { from: 'user' });42+ expect(program.opts().foo).toBe('env');43+ delete process.env.BAR;44+ });45+46+ test('when default and env defined and cli then option from cli', () => {47+ const program = new commander.Command();48+ process.env.BAR = 'env';49+ program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));50+ program.parse(['--foo', 'cli'], { from: 'user' });51+ expect(program.opts().foo).toBe('cli');52+ delete process.env.BAR;53+ });54+});55+56+describe('boolean flag', () => {57+ test('when env undefined and no cli then option undefined', () => {58+ const program = new commander.Command();59+ program.addOption(new commander.Option('-f, --foo').env('BAR'));60+ program.parse([], { from: 'user' });61+ expect(program.opts().foo).toBeUndefined();62+ });63+64+ test('when env defined with value and no cli then option true', () => {65+ const program = new commander.Command();66+ process.env.BAR = 'env';67+ program.addOption(new commander.Option('-f, --foo').env('BAR'));68+ program.parse([], { from: 'user' });69+ expect(program.opts().foo).toBe(true);70+ delete process.env.BAR;71+ });72+73+ test('when env is "" and no cli then option true', () => {74+ // any string, including ""75+ const program = new commander.Command();76+ process.env.BAR = '';77+ program.addOption(new commander.Option('-f, --foo').env('BAR'));78+ program.parse([], { from: 'user' });79+ expect(program.opts().foo).toBe(true);80+ delete process.env.BAR;81+ });82+83+ test('when env is "0" and no cli then option true', () => {84+ // any string, including "0"85+ const program = new commander.Command();86+ process.env.BAR = '0';87+ program.addOption(new commander.Option('-f, --foo').env('BAR'));88+ program.parse([], { from: 'user' });89+ expect(program.opts().foo).toBe(true);90+ delete process.env.BAR;91+ });92+93+ test('when env is "false" and no cli then option true', () => {94+ // any string, including "false"95+ const program = new commander.Command();96+ process.env.BAR = 'false';97+ program.addOption(new commander.Option('-f, --foo').env('BAR'));98+ program.parse([], { from: 'user' });99+ expect(program.opts().foo).toBe(true);100+ delete process.env.BAR;101+ });102+});103+104+describe('boolean no-flag', () => {105+ test('when env undefined and no cli then option true', () => {106+ const program = new commander.Command();107+ program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));108+ program.parse([], { from: 'user' });109+ expect(program.opts().foo).toBe(true);110+ });111+112+ test('when env defined and no cli then option false', () => {113+ const program = new commander.Command();114+ process.env.NO_BAR = 'env';115+ program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));116+ program.parse([], { from: 'user' });117+ expect(program.opts().foo).toBe(false);118+ delete process.env.NO_BAR;119+ });120+});121+122+describe('boolean flag and negatable', () => {123+ test('when env undefined and no cli then option undefined', () => {124+ const program = new commander.Command();125+ program126+ .addOption(new commander.Option('-f, --foo').env('BAR'))127+ .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));128+ program.parse([], { from: 'user' });129+ expect(program.opts().foo).toBeUndefined();130+ });131+132+ test('when env defined and no cli then option true', () => {133+ const program = new commander.Command();134+ process.env.BAR = 'env';135+ program136+ .addOption(new commander.Option('-f, --foo').env('BAR'))137+ .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));138+ program.parse([], { from: 'user' });139+ expect(program.opts().foo).toBe(true);140+ delete process.env.BAR;141+ });142+143+ test('when env defined and cli --no-foo then option false', () => {144+ const program = new commander.Command();145+ process.env.BAR = 'env';146+ program147+ .addOption(new commander.Option('-f, --foo').env('BAR'))148+ .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));149+ program.parse(['--no-foo'], { from: 'user' });150+ expect(program.opts().foo).toBe(false);151+ delete process.env.BAR;152+ });153+154+ test('when no_env defined and no cli then option false', () => {155+ const program = new commander.Command();156+ process.env.NO_BAR = 'env';157+ program158+ .addOption(new commander.Option('-f, --foo').env('BAR'))159+ .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));160+ program.parse([], { from: 'user' });161+ expect(program.opts().foo).toBe(false);162+ delete process.env.NO_BAR;163+ });164+165+ test('when no_env defined and cli --foo then option true', () => {166+ const program = new commander.Command();167+ process.env.NO_BAR = 'env';168+ program169+ .addOption(new commander.Option('-f, --foo').env('BAR'))170+ .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));171+ program.parse(['--foo'], { from: 'user' });172+ expect(program.opts().foo).toBe(true);173+ delete process.env.NO_BAR;174+ });175+});176+177+describe('custom argParser', () => {178+ test('when env defined and no cli then custom parse from env', () => {179+ const program = new commander.Command();180+ process.env.BAR = 'env';181+ program.addOption(new commander.Option('-f, --foo <required>').env('BAR').argParser(str => str.toUpperCase()));182+ program.parse([], { from: 'user' });183+ expect(program.opts().foo).toBe('ENV');184+ delete process.env.BAR;185+ });186+});187+188+describe('variadic', () => {189+ test('when env defined and no cli then array from env', () => {190+ const program = new commander.Command();191+ process.env.BAR = 'env';192+ program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));193+ program.parse([], { from: 'user' });194+ expect(program.opts().foo).toEqual(['env']);195+ delete process.env.BAR;196+ });197+198+ test('when env defined and cli then array from cli', () => {199+ const program = new commander.Command();200+ process.env.BAR = 'env';201+ program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));202+ program.parse(['--foo', 'cli'], { from: 'user' });203+ expect(program.opts().foo).toEqual(['cli']);204+ delete process.env.BAR;205+ });206+});207+208+describe('env only processed when applies', () => {209+ test('when env defined on another subcommand then env not applied', () => {210+ // Doing selective processing. Not processing env at addOption time.211+ const program = new commander.Command();212+ process.env.BAR = 'env';213+ program.command('one')214+ .action(() => {});215+ const two = program.command('two')216+ .addOption(new commander.Option('-f, --foo <required...>').env('BAR').default('default'))217+ .action(() => {});218+ program.parse(['one'], { from: 'user' });219+ expect(two.opts().foo).toBe('default');220+ delete process.env.BAR;221+ });222+223+ test('when env and cli defined then only emit option event for cli', () => {224+ const program = new commander.Command();225+ const optionEventMock = jest.fn();226+ const optionEnvEventMock = jest.fn();227+ program.on('option:foo', optionEventMock);228+ program.on('optionEnv:foo', optionEnvEventMock);229+ process.env.BAR = 'env';230+ program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));231+ program.parse(['--foo', 'cli'], { from: 'user' });232+ expect(optionEventMock).toHaveBeenCalledWith('cli');233+ expect(optionEventMock).toHaveBeenCalledTimes(1);234+ expect(optionEnvEventMock).toHaveBeenCalledTimes(0);235+ delete process.env.BAR;236+ });237+238+ test('when env and cli defined then only parse value for cli', () => {239+ const program = new commander.Command();240+ const parseMock = jest.fn();241+ process.env.BAR = 'env';242+ program.addOption(new commander.Option('-f, --foo <required...>').env('BAR').argParser(parseMock));243+ program.parse(['--foo', 'cli'], { from: 'user' });244+ expect(parseMock).toHaveBeenCalledWith('cli', undefined);245+ expect(parseMock).toHaveBeenCalledTimes(1);246+ delete process.env.BAR;247+ });248+});249+250+describe('events dispatched for env', () => {251+ const optionEnvEventMock = jest.fn();252+253+ afterEach(() => {254+ optionEnvEventMock.mockClear();255+ delete process.env.BAR;256+ });257+258+ test('when env defined then emit "optionEnv" and not "option"', () => {259+ // Decided to do separate events, so test stays that way.260+ const program = new commander.Command();261+ const optionEventMock = jest.fn();262+ program.on('option:foo', optionEventMock);263+ program.on('optionEnv:foo', optionEnvEventMock);264+ process.env.BAR = 'env';265+ program.addOption(new commander.Option('-f, --foo <required>').env('BAR'));266+ program.parse([], { from: 'user' });267+ expect(optionEventMock).toHaveBeenCalledTimes(0);268+ expect(optionEnvEventMock).toHaveBeenCalledTimes(1);269+ });270+271+ test('when env defined for required then emit "optionEnv" with value', () => {272+ const program = new commander.Command();273+ program.on('optionEnv:foo', optionEnvEventMock);274+ process.env.BAR = 'env';275+ program.addOption(new commander.Option('-f, --foo <required>').env('BAR'));276+ program.parse([], { from: 'user' });277+ expect(optionEnvEventMock).toHaveBeenCalledWith('env');278+ });279+280+ test('when env defined for optional then emit "optionEnv" with value', () => {281+ const program = new commander.Command();282+ program.on('optionEnv:foo', optionEnvEventMock);283+ process.env.BAR = 'env';284+ program.addOption(new commander.Option('-f, --foo [optional]').env('BAR'));285+ program.parse([], { from: 'user' });286+ expect(optionEnvEventMock).toHaveBeenCalledWith('env');287+ });288+289+ test('when env defined for boolean then emit "optionEnv" with no param', () => {290+ // check matches historical boolean action event291+ const program = new commander.Command();292+ program.on('optionEnv:foo', optionEnvEventMock);293+ process.env.BAR = 'anything';294+ program.addOption(new commander.Option('-f, --foo').env('BAR'));295+ program.parse([], { from: 'user' });296+ expect(optionEnvEventMock).toHaveBeenCalledWith();297+ });298+299+ test('when env defined for negated boolean then emit "optionEnv" with no param', () => {300+ // check matches historical boolean action event301+ const program = new commander.Command();302+ program.on('optionEnv:no-foo', optionEnvEventMock);303+ process.env.BAR = 'anything';304+ program.addOption(new commander.Option('-F, --no-foo').env('BAR'));305+ program.parse([], { from: 'user' });306+ expect(optionEnvEventMock).toHaveBeenCalledWith();307+ });308+});modified:tests/options.mandatory.test.js+14 added-1 removed
164 unmodified lines165 });166 });167 168 describe('required command option with mandatory value specified', () => {169- test('when command has required value specified then specified value', () => {169+ test('when command has required value specified then no error and option has specified value', () => {170 const program = new commander.Command();171 let cmdOptions;172 program173 .exitOverride()6 unmodified lines180 program.parse(['node', 'test', 'sub', '--subby', 'blue']);181 182 expect(cmdOptions.subby).toBe('blue');183 });184+185+ test('when command has required value specified using env then no error and option has specified value', () => {186+ const program = new commander.Command();187+ program188+ .exitOverride()189+ .addOption(new commander.Option('-p, --port <number>', 'port number').makeOptionMandatory().env('FOO'));190+191+ process.env.FOO = 'bar';192+ program.parse([], { from: 'user' });193+ delete process.env.FOO;194+195+ expect(program.opts().port).toBe('bar');196+ });197 });198 199 describe('required command option with mandatory value not specified', () => {200 // Optional. Use internal knowledge to suppress output to keep test output clean.93 unmodified linesmodified:typings/index.d.ts+12 added-6 removed
42 unmodified lines43 */44 constructor(arg: string, description?: string);45 46 /**47- * Return argument name.48- */47+ * Return argument name.48+ */49 name(): string;50 51 /**52 * Set the default value, and optionally supply the description to be displayed in the help.53 */54- default(value: unknown, description?: string): this;54+ default(value: unknown, description?: string): this;55 56 /**57 * Set the custom handler for processing CLI command arguments into argument values.58 */59- argParser<T>(fn: (value: string, previous: T) => T): this;59+ argParser<T>(fn: (value: string, previous: T) => T): this;60 61 /**62 * Only allow argument value to be one of choices.63 */64- choices(values: string[]): this;64+ choices(values: string[]): this;65 66 /**67 * Make option-argument required.68 */69- argRequired(): this;69+ argRequired(): this;70 71 /**72 * Make option-argument optional.73 */25 unmodified lines99 */100 default(value: unknown, description?: string): this;101 102 /**103+ * Set environment variable to check for option value.104+ * Priority order of option values is default < env < cli105+ */106+ env(name: string): this;107+108+ /**109 * Calculate the full description, including defaultValue etc.110 */111 fullDescription(): string;112 652 unmodified linesmodified:typings/index.test-d.ts+3 added
343 unmodified lines344 // default345 expectType<commander.Option>(baseOption.default(3));346 expectType<commander.Option>(baseOption.default(60, 'one minute'));347 348+// env349+expectType<commander.Option>(baseOption.env('PORT'));350+351 // fullDescription352 expectType<string>(baseOption.fullDescription());353 354 // argParser55 unmodified linesmodified:Readme.md+7 added-4 removed
91 unmodified lines92 import { Command } from 'commander';93 const program = new Command();94 ```95 96-96 ## Options97 98 Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').99 206 unmodified lines306 307 You can add most options using the `.option()` method, but there are some additional features available308 by constructing an `Option` explicitly for less common cases.309 311-Example file: [options-extra.js](./examples/options-extra.js)310+Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js)311 312 ```js313 program314 .addOption(new Option('-s, --secret').hideHelp())315 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))317- .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']));316+ .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))317+ .addOption(new Option('-p, --port <number>', 'port number').env('PORT'));318 ```319 320 ```bash321 $ extra --help1 unmodified line323 324 Options:325 -t, --timeout <delay> timeout in seconds (default: one minute)326 -d, --drink <size> drink cup size (choices: "small", "medium", "large")327+ -p, --port <number> port number (env: PORT)328 -h, --help display help for command329 330 $ extra --drink huge331 error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.332+333+$ PORT=80 extra 334+Options: { timeout: 60, port: '80' }335 ```336 337 ### Custom option processing338 567 unmodified lines906 You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.907 908 Example file: [configure-output.js](./examples/configure-output.js)909 906-910 ```js911 function errorColor(str) {912 // Add ANSI escape codes to display text in red.913 return `\x1b[31m${str}\x1b[0m`;96 unmodified lines