Skip to content

Commit

Permalink
Back to shared implementation method for .option and .requiredOption (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowspawn authored Sep 26, 2020
1 parent e5512a4 commit b4fbe67
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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);
};

/**
Expand All @@ -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);
};

/**
Expand Down

0 comments on commit b4fbe67

Please sign in to comment.