Skip to content
Myr

Add setOptionValueWithSource and getOptionValueSource (#1613)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Make setOptionValueWithSource public and add matching getOptionValueSource * Add mention in README

authored by John Gee · committed by GitHub · parent a546970 · Browse files · 7 files+114 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+114 added−15 removed

  • tests:+62 added−1 removed
  • other:+52 added−14 removed

7 files+114 added−15 removed

modified:lib/command.js+30 added-10 removed
34 unmodified lines
35 this.processedArgs = []; // like .args but after custom processing and collecting variadic36 this._scriptPath = null;37 this._name = name || '';38 this._optionValues = {};39 this._optionValueSources = {}; // default < env < cli39 this._optionValueSources = {}; // default < config < env < cli40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable
482 unmodified lines
526 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;527 }528 // preassign only if we have a default529 if (defaultValue !== undefined) {530 this._setOptionValueWithSource(name, defaultValue, 'default');530 this.setOptionValueWithSource(name, defaultValue, 'default');531 }532 }533534 // register the option
22 unmodified lines
557 // unassigned or boolean value558 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {559 // if no value, negate false, and we have a default, then use it!560 if (val == null) {561 this._setOptionValueWithSource(name, option.negate ? false : defaultValue || true, valueSource);561 this.setOptionValueWithSource(name, option.negate ? false : defaultValue || true, valueSource);562 } else {563 this._setOptionValueWithSource(name, val, valueSource);563 this.setOptionValueWithSource(name, val, valueSource);564 }565 } else if (val !== null) {566 // reassign567 this._setOptionValueWithSource(name, option.negate ? false : val, valueSource);567 this.setOptionValueWithSource(name, option.negate ? false : val, valueSource);568 }569 };570571 this.on('option:' + oname, (val) => {
220 unmodified lines
792 return this;793 };794795 /**796 * @api private797 */798 _setOptionValueWithSource(key, value, source) {796 * Store option value and where the value came from.797 *798 * @param {string} key799 * @param {Object} value800 * @param {string} source - expected values are default/config/env/cli801 * @return {Command} `this` command for chaining802 */803804 setOptionValueWithSource(key, value, source) {805 this.setOptionValue(key, value);806 this._optionValueSources[key] = source;807 return this;808 }809810 /**811 * Get source of option value.812 * Expected values are default | config | env | cli813 *814 * @param {string} key815 * @return {string}816 */817818 getOptionValueSource(key) {819 return this._optionValueSources[key];820 };821822 /**823 * Get user arguments implied or explicit arguments.824 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.825 *826 * @api private
303 unmodified lines
1130 *1131 * @param {Promise|undefined} promise1132 * @param {Function} fn1133 * @return {Promise|undefined}1134 * @api private1135 */11361137 _chainOrCall(promise, fn) {1138 // thenable
336 unmodified lines
1475 _parseOptionsEnv() {1476 this.options.forEach((option) => {1477 if (option.envVar && option.envVar in process.env) {1478 const optionKey = option.attributeName();1459 // env is second lowest priority source, above default1460 if (this.getOptionValue(optionKey) === undefined || this._optionValueSources[optionKey] === 'default') {1479 // Priority check. Do not overwrite cli or options from unknown source (client-code).1480 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1481 if (option.required || option.optional) { // option can take a value1482 // keep very simple, optional always takes value1483 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1484 } else { // boolean
460 unmodified lines
modified:tests/command.chain.test.js+7 added-1 removed
172 unmodified lines
173 });174175 test('when call .setOptionValue() then returns this', () => {176 const program = new Command();177 const result = program.setOptionValue();177 const result = program.setOptionValue('foo', 'bar');178 expect(result).toBe(program);179 });180181 test('when call .setOptionValueWithSource() then returns this', () => {182 const program = new Command();183 const result = program.setOptionValueWithSource('foo', 'bar', 'cli');184 expect(result).toBe(program);185 });186187 test('when call .showHelpAfterError() then returns this', () => {188 const program = new Command();189 const result = program.showHelpAfterError();190 expect(result).toBe(program);
15 unmodified lines
modified:tests/options.env.test.js+20 added
25 unmodified lines
26 expect(program.opts().foo).toBe('cli');27 delete process.env.BAR;28 });2930 test('when env defined and value source is config then option from env', () => {31 const program = new commander.Command();32 process.env.BAR = 'env';33 program.addOption(new commander.Option(fooFlags).env('BAR'));34 program.setOptionValueWithSource('foo', 'config', 'config');35 program.parse([], { from: 'user' });36 expect(program.opts().foo).toBe('env');37 delete process.env.BAR;38 });3940 test('when env defined and value source is unspecified then option unchanged', () => {41 const program = new commander.Command();42 process.env.BAR = 'env';43 program.addOption(new commander.Option(fooFlags).env('BAR'));44 program.setOptionValue('foo', 'client');45 program.parse([], { from: 'user' });46 expect(program.opts().foo).toBe('client');47 delete process.env.BAR;48 });4950 test('when default and env undefined and no cli then option from default', () => {51 const program = new commander.Command();52 program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));53 program.parse([], { from: 'user' });
275 unmodified lines
modified:tests/options.getset.test.js+35 added
modified:typings/index.d.ts+14 added-3 removed
212 unmodified lines
213 outputError?(str: string, write: (str: string) => void): void;214215}216217type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';218type HookEvent = 'preAction' | 'postAction';217export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';218export type HookEvent = 'preAction' | 'postAction';219export type OptionValueSource = 'default' | 'env' | 'config' | 'cli';220221export interface OptionValues {222 [key: string]: any;223}
302 unmodified lines
526 * Retrieve option value.527 */528 getOptionValue(key: string): any;529529 /**530 /**531 * Store option value.532 */533 setOptionValue(key: string, value: unknown): this;534535 /**536 * Store option value and where the value came from.537 */538 setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;539540 /**541 * Retrieve option value source.542 */543 getOptionValueSource(key: string): OptionValueSource;544545 /**546 * Alter parsing of short flags with optional values.547 *548 * @example549 * ```
225 unmodified lines
modified:typings/index.test-d.ts+6 added
153 unmodified lines
154// setOptionValue155expectType<commander.Command>(program.setOptionValue('example', 'value'));156expectType<commander.Command>(program.setOptionValue('example', true));157158// setOptionValueWithSource159expectType<commander.Command>(program.setOptionValueWithSource('example', [], 'cli'));160161// getOptionValueSource162expectType<commander.OptionValueSource>(program.getOptionValueSource('example'));163164// combineFlagAndOptionalValue165expectType<commander.Command>(program.combineFlagAndOptionalValue());166expectType<commander.Command>(program.combineFlagAndOptionalValue(false));167
249 unmodified lines
modified:Readme.md+2 added-1 removed
96 unmodified lines
9798Options 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 ('|').99100The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.101You can also use `.getOptionValue()` and `.setOptionValue()` to work with a single option value.101(You can also use `.getOptionValue()` and `.setOptionValue()` to work with a single option value,102and `.getOptionValueSource()` and `.setOptionValueWithSource()` when it matters where the option value came from.)103104Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.105106Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
909 unmodified lines