Add getOptionValue and setOptionValue (#1521)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Simplify typings by removing default export of program * Switch any to unknown per lint suggestion * Add typings change to deprecated.md * Make getOptionValue and setOptionValue public * Fix comment change lost in merge * Tweak wording
authored by John Gee · committed by GitHub · parent ad3f947 · Browse files · 6 files·+71 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+71 added−21 removed
- tests:+30 added−0 removed
- other:+41 added−21 removed
Provenance
- Commit
6c06528- Tree
7a41888- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
ad3f947
6 files changed+71 added−21 removed
modified:tests/command.chain.test.js+6 added
163 unmodified linesExpand all164165166167168169170171172173174163 unmodified linesExpand all const program = new Command(); const result = program.enablePositionalOptions(); expect(result).toBe(program); });
test('when call .setOptionValue() then returns this', () => { const program = new Command(); const result = program.setOptionValue(); expect(result).toBe(program); });});added:tests/options.getset.test.js+24 added
123456789101112131415161718192021222324const commander = require('../');
describe.each([true, false])('storeOptionsAsProperties is %s', (storeOptionsAsProperties) => { test('when option specified on CLI then value returned by getOptionValue', () => { const program = new commander.Command(); program .storeOptionsAsProperties(storeOptionsAsProperties) .option('--cheese [type]', 'cheese type'); const cheeseType = 'blue'; program.parse(['node', 'test', '--cheese', cheeseType]); expect(program.getOptionValue('cheese')).toBe(cheeseType); });
test('when setOptionValue then value returned by opts', () => { const program = new commander.Command(); const cheeseType = 'blue'; // Note: opts() only returns declared options when options stored as properties program .storeOptionsAsProperties(storeOptionsAsProperties) .option('--cheese [type]', 'cheese type') .setOptionValue('cheese', cheeseType); expect(program.opts().cheese).toBe(cheeseType); });});modified:typings/index.d.ts+10 added
464 unmodified lines465 storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;466 storeOptionsAsProperties(storeAsProperties?: boolean): this;467 468 /**469+ * Retrieve option value.470+ */471+ getOptionValue(key: string): any;472+473+ /**474+ * Store option value.475+ */476+ setOptionValue(key: string, value: unknown): this;477+478+ /**479 * Alter parsing of short flags with optional values.480 *481 * @example482 * // for `.option('-f,--flag [value]'):222 unmodified linesmodified:typings/index.test-d.ts+7 added
136 unmodified lines137 expectType<commander.Command & commander.OptionValues>(program.storeOptionsAsProperties());138 expectType<commander.Command & commander.OptionValues>(program.storeOptionsAsProperties(true));139 expectType<commander.Command>(program.storeOptionsAsProperties(false));140 141+// getOptionValue142+void program.getOptionValue('example');143+144+// setOptionValue145+expectType<commander.Command>(program.setOptionValue('example', 'value'));146+expectType<commander.Command>(program.setOptionValue('example', true));147+148 // combineFlagAndOptionalValue149 expectType<commander.Command>(program.combineFlagAndOptionalValue());150 expectType<commander.Command>(program.combineFlagAndOptionalValue(false));151 212 unmodified linesmodified:index.js+20 added-20 removed
1092 unmodified lines1093 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {1094 // when --no-foo we make sure default is true, unless a --foo option is already defined1095 if (option.negate) {1096 const positiveLongFlag = option.long.replace(/^--no-/, '--');1097- defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;1097+ defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;1098 }1099 // preassign only if we have a default1100 if (defaultValue !== undefined) {1101- this._setOptionValue(name, defaultValue);1101+ this.setOptionValue(name, defaultValue);1102 }1103 }1104 1105 // register the option1 unmodified line1107 1108 // when it's passed assign the value1109 // and conditionally invoke the callback1110 this.on('option:' + oname, (val) => {1111- const oldValue = this._getOptionValue(name);1111+ const oldValue = this.getOptionValue(name);1112 1113 // custom processing1114 if (val !== null && option.parseArg) {1115 try {12 unmodified lines1128 // unassigned or boolean value1129 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {1130 // if no value, negate false, and we have a default, then use it!1131 if (val == null) {1132- this._setOptionValue(name, option.negate1132+ this.setOptionValue(name, option.negate1133 ? false1134 : defaultValue || true);1135 } else {1136- this._setOptionValue(name, val);1136+ this.setOptionValue(name, val);1137 }1138 } else if (val !== null) {1139 // reassign1140- this._setOptionValue(name, option.negate ? false : val);1140+ this.setOptionValue(name, option.negate ? false : val);1141 }1142 });1143 1144 return this;179 unmodified lines1324 return this;1325 };1326 1327 /**1328- * Store option value1328+ * Retrieve option value.1329 *1330 * @param {string} key1331- * @param {Object} value1332- * @api private1331+ * @return {Object} value1332 */1333 1335- _setOptionValue(key, value) {1334+ getOptionValue(key) {1335 if (this._storeOptionsAsProperties) {1337- this[key] = value;1338- } else {1339- this._optionValues[key] = value;1336+ return this[key];1337 }1338+ return this._optionValues[key];1339 };1340 1341 /**1344- * Retrieve option value1342+ * Store option value.1343 *1344 * @param {string} key1347- * @return {Object} value1348- * @api private1345+ * @param {Object} value1346+ * @return {Command} `this` command for chaining1347 */1348 1351- _getOptionValue(key) {1349+ setOptionValue(key, value) {1350 if (this._storeOptionsAsProperties) {1353- return this[key];1351+ this[key] = value;1352+ } else {1353+ this._optionValues[key] = value;1354 }1355- return this._optionValues[key];1355+ return this;1356 };1357 1358 /**1359 * Get user arguments implied or explicit arguments.403 unmodified lines1763 _checkForMissingMandatoryOptions() {1764 // Walk up hierarchy so can call in subcommand after checking for displaying help.1765 for (let cmd = this; cmd; cmd = cmd.parent) {1766 cmd.options.forEach((anOption) => {1767- if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {1767+ if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1768 cmd.missingMandatoryOptionValue(anOption);1769 }1770 });1771 }655 unmodified linesmodified:Readme.md+4 added-1 removed
93 unmodified lines94 ## Options95 96 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 ('|').97 98-The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.98+The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.99+You can also use `.getOptionValue()` and `.setOptionValue()` to work with a single option value.100 101+Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.102+103 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).104 For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.105 106 You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.843 unmodified lines