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
Provenance
- Commit
6e00f44- Tree
17cd705- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
a546970
7 files changed+114 added−15 removed
modified:lib/command.js+30 added-10 removed
34 unmodified lines35 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 executable482 unmodified lines526 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 }533 534 // register the option22 unmodified lines557 // 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 };570 571 this.on('option:' + oname, (val) => {220 unmodified lines792 return this;793 };794 795 /**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+ */803+804+ setOptionValueWithSource(key, value, source) {805 this.setOptionValue(key, value);806 this._optionValueSources[key] = source;807+ return this;808 }809 810 /**811+ * Get source of option value.812+ * Expected values are default | config | env | cli813+ *814+ * @param {string} key815+ * @return {string}816+ */817+818+ getOptionValueSource(key) {819+ return this._optionValueSources[key];820+ };821+822+ /**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 private303 unmodified lines1130 *1131 * @param {Promise|undefined} promise1132 * @param {Function} fn1133 * @return {Promise|undefined}1134+ * @api private1135 */1136 1137 _chainOrCall(promise, fn) {1138 // thenable336 unmodified lines1475 _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 { // boolean460 unmodified linesmodified:tests/command.chain.test.js+7 added-1 removed
172 unmodified lines173 });174 175 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 });180 181+ 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+ });186+187 test('when call .showHelpAfterError() then returns this', () => {188 const program = new Command();189 const result = program.showHelpAfterError();190 expect(result).toBe(program);15 unmodified linesmodified:tests/options.env.test.js+20 added
25 unmodified lines26 expect(program.opts().foo).toBe('cli');27 delete process.env.BAR;28 });29 30+ 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+ });39+40+ 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+ });49+50 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 linesmodified:tests/options.getset.test.js+35 added
20 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585920 unmodified lines .setOptionValue('cheese', cheeseType); expect(program.opts().cheese).toBe(cheeseType); });});
test('when setOptionValueWithSource then value returned by opts', () => { const program = new commander.Command(); const cheeseValue = 'blue'; program .option('--cheese [type]', 'cheese type') .setOptionValue('cheese', cheeseValue); expect(program.opts().cheese).toBe(cheeseValue);});
test('when setOptionValueWithSource then source returned by getOptionValueSource', () => { const program = new commander.Command(); program .option('--cheese [type]', 'cheese type') .setOptionValueWithSource('cheese', 'blue', 'config'); expect(program.getOptionValueSource('cheese')).toBe('config');});
test('when option value parsed from env then option source is env', () => { const program = new commander.Command(); process.env.BAR = 'env'; program .addOption(new commander.Option('-f, --foo').env('BAR')); program.parse([], { from: 'user' }); expect(program.getOptionValueSource('foo')).toBe('env'); delete process.env.BAR;});
test('when option value parsed from cli then option source is cli', () => { const program = new commander.Command(); program .addOption(new commander.Option('-f, --foo').env('BAR')); program.parse(['--foo'], { from: 'user' }); expect(program.getOptionValueSource('foo')).toBe('cli');});modified:typings/index.d.ts+14 added-3 removed
212 unmodified lines213 outputError?(str: string, write: (str: string) => void): void;214 215 }216 217-type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';218-type HookEvent = 'preAction' | 'postAction';217+export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';218+export type HookEvent = 'preAction' | 'postAction';219+export type OptionValueSource = 'default' | 'env' | 'config' | 'cli';220 221 export interface OptionValues {222 [key: string]: any;223 }302 unmodified lines526 * Retrieve option value.527 */528 getOptionValue(key: string): any;529 529- /**530+ /**531 * Store option value.532 */533 setOptionValue(key: string, value: unknown): this;534 535 /**536+ * Store option value and where the value came from.537+ */538+ setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;539+540+ /**541+ * Retrieve option value source.542+ */543+ getOptionValueSource(key: string): OptionValueSource;544+545+ /**546 * Alter parsing of short flags with optional values.547 *548 * @example549 * ```225 unmodified linesmodified:typings/index.test-d.ts+6 added
153 unmodified lines154 // setOptionValue155 expectType<commander.Command>(program.setOptionValue('example', 'value'));156 expectType<commander.Command>(program.setOptionValue('example', true));157 158+// setOptionValueWithSource159+expectType<commander.Command>(program.setOptionValueWithSource('example', [], 'cli'));160+161+// getOptionValueSource162+expectType<commander.OptionValueSource>(program.getOptionValueSource('example'));163+164 // combineFlagAndOptionalValue165 expectType<commander.Command>(program.combineFlagAndOptionalValue());166 expectType<commander.Command>(program.combineFlagAndOptionalValue(false));167 249 unmodified linesmodified:Readme.md+2 added-1 removed
96 unmodified lines97 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 100 The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.101-You 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,102+and `.getOptionValueSource()` and `.setOptionValueWithSource()` when it matters where the option value came from.)103 104 Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.105 106 Multiple 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