From b4fbe678efcf3c51fec2b7710fe529eaa0b7e0ec Mon Sep 17 00:00:00 2001 From: John Gee Date: Sun, 27 Sep 2020 09:12:32 +1300 Subject: [PATCH] Back to shared implementation method for .option and .requiredOption (#1363) --- index.js | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/index.js b/index.js index aa4f49d5e..7129b2126 100644 --- a/index.js +++ b/index.js @@ -666,6 +666,31 @@ Read more on https://git.io/JJc0W`); return this; } + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @api private + */ + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + option.makeOptionMandatory(!!config.mandatory); + if (typeof fn === 'function') { + option.default(defaultValue).argParser(fn); + } else if (fn instanceof RegExp) { + // deprecated + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + option.default(defaultValue).argParser(fn); + } else { + option.default(fn); + } + + return this.addOption(option); + } + /** * Define option with `flags`, `description` and optional * coercion `fn`. @@ -719,22 +744,7 @@ Read more on https://git.io/JJc0W`); */ option(flags, description, fn, defaultValue) { - const option = new Option(flags, description); - if (typeof fn === 'function') { - option.default(defaultValue).argParser(fn); - } else if (fn instanceof RegExp) { - // deprecated - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - option.default(defaultValue).argParser(fn); - } else { - option.default(fn); - } - - return this.addOption(option); + return this._optionEx({}, flags, description, fn, defaultValue); }; /** @@ -752,9 +762,7 @@ Read more on https://git.io/JJc0W`); */ requiredOption(flags, description, fn, defaultValue) { - this.option(flags, description, fn, defaultValue); - this.options[this.options.length - 1].makeOptionMandatory(); - return this; + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); }; /**