Skip to content
Myr

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

authored by John Gee · committed by GitHub · parent 3a0ef21 · Browse files · 12 files+482 added−34 removed
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

12 files+482 added−34 removed

added:examples/options-env.js+38 added
modified:examples/options-extra.js+11 added-8 removed
modified:lib/command.js+54 added-10 removed
33 unmodified lines
34 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 executable
469 unmodified lines
512 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 }519520 // register the option521 this.options.push(option);522522 // 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);527528 // 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 lines
543 // 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 };556557 this.on('option:' + oname, (val) => {558 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;559 handleOptionValue(val, invalidValueMessage, 'cli');560 });561562 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 }568569 return this;570 }571572 /**
205 unmodified lines
778 return this;779 };780781 /**782 * @api private783 */784 _setOptionValueWithSource(key, value, source) {785 this.setOptionValue(key, value);786 this._optionValueSources[key] = source;787 }788789 /**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 private
355 unmodified lines
1149 */11501151 _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 lines
1431 this._exit(exitCode, code, message);1432 }14331434 /**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 }14571458 /**1459 * Argument `name` is missing.1460 *1461 * @param {string} name1462 * @api private
418 unmodified lines
modified:lib/help.js+8 added-5 removed
232 unmodified lines
233 * @return {string}234 */235236 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.239241 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 }254255 return option.description;256 };257258 /**
138 unmodified lines
modified:lib/option.js+14 added
26 unmodified lines
27 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 lines
48 return this;49 };5051 /**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 */5859 env(name) {60 this.envVar = name;61 return this;62 };6364 /**65 * Set the custom handler for processing CLI option arguments into option values.66 *67 * @param {Function} [fn]68 * @return {Option}
140 unmodified lines
modified:tests/help.optionDescription.test.js+7 added
modified:tests/option.chain.test.js+6 added
added:tests/options.env.test.js+308 added
1const commander = require('../');23// treating optional same as required, treat as option taking value rather than as boolean4describe.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 });1112 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 });2021 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 });2930 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 });3637 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 });4546 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});5556describe('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 });6364 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 });7273 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 });8283 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 });9293 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});103104describe('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 });111112 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});121122describe('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 });131132 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 });142143 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 });153154 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 });164165 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});176177describe('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});187188describe('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 });197198 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});207208describe('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 });222223 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 });237238 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});249250describe('events dispatched for env', () => {251 const optionEnvEventMock = jest.fn();252253 afterEach(() => {254 optionEnvEventMock.mockClear();255 delete process.env.BAR;256 });257258 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 });270271 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 });279280 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 });288289 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 });298299 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 lines
165 });166});167168describe('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 lines
180 program.parse(['node', 'test', 'sub', '--subby', 'blue']);181182 expect(cmdOptions.subby).toBe('blue');183 });184185 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'));190191 process.env.FOO = 'bar';192 program.parse([], { from: 'user' });193 delete process.env.FOO;194195 expect(program.opts().port).toBe('bar');196 });197});198199describe('required command option with mandatory value not specified', () => {200 // Optional. Use internal knowledge to suppress output to keep test output clean.
93 unmodified lines
modified:typings/index.d.ts+12 added-6 removed
42 unmodified lines
43 */44 constructor(arg: string, description?: string);4546 /**47 * Return argument name.48 */47 * Return argument name.48 */49 name(): string;5051 /**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;5556 /**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;6061 /**62 * Only allow argument value to be one of choices.63 */64 choices(values: string[]): this;64 choices(values: string[]): this;6566 /**67 * Make option-argument required.68 */69 argRequired(): this;69 argRequired(): this;7071 /**72 * Make option-argument optional.73 */
25 unmodified lines
99 */100 default(value: unknown, description?: string): this;101102 /**103 * Set environment variable to check for option value.104 * Priority order of option values is default < env < cli105 */106 env(name: string): this;107108 /**109 * Calculate the full description, including defaultValue etc.110 */111 fullDescription(): string;112
652 unmodified lines
modified:typings/index.test-d.ts+3 added
343 unmodified lines
344// default345expectType<commander.Option>(baseOption.default(3));346expectType<commander.Option>(baseOption.default(60, 'one minute'));347348// env349expectType<commander.Option>(baseOption.env('PORT'));350351// fullDescription352expectType<string>(baseOption.fullDescription());353354// argParser
55 unmodified lines
modified:Readme.md+7 added-4 removed
91 unmodified lines
92import { Command } from 'commander';93const program = new Command();94```959696## Options9798Options 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 lines
306307You can add most options using the `.option()` method, but there are some additional features available308by constructing an `Option` explicitly for less common cases.309311Example file: [options-extra.js](./examples/options-extra.js)310Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js)311312```js313program314 .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```319320```bash321$ extra --help
1 unmodified line
323324Options: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 command329330$ extra --drink huge331error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.332333$ PORT=80 extra 334Options: { timeout: 60, port: '80' }335```336337### Custom option processing338
567 unmodified lines
906You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.907908Example file: [configure-output.js](./examples/configure-output.js)909906910```js911function errorColor(str) {912 // Add ANSI escape codes to display text in red.913 return `\x1b[31m${str}\x1b[0m`;
96 unmodified lines