yargs-parser.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. import { tokenizeArgString } from './tokenize-arg-string.js';
  2. import { camelCase, decamelize, looksLikeNumber } from './string-utils.js';
  3. let mixin;
  4. export class YargsParser {
  5. constructor(_mixin) {
  6. mixin = _mixin;
  7. }
  8. parse(argsInput, options) {
  9. const opts = Object.assign({
  10. alias: undefined,
  11. array: undefined,
  12. boolean: undefined,
  13. config: undefined,
  14. configObjects: undefined,
  15. configuration: undefined,
  16. coerce: undefined,
  17. count: undefined,
  18. default: undefined,
  19. envPrefix: undefined,
  20. narg: undefined,
  21. normalize: undefined,
  22. string: undefined,
  23. number: undefined,
  24. __: undefined,
  25. key: undefined
  26. }, options);
  27. // allow a string argument to be passed in rather
  28. // than an argv array.
  29. const args = tokenizeArgString(argsInput);
  30. // aliases might have transitive relationships, normalize this.
  31. const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
  32. const configuration = Object.assign({
  33. 'boolean-negation': true,
  34. 'camel-case-expansion': true,
  35. 'combine-arrays': false,
  36. 'dot-notation': true,
  37. 'duplicate-arguments-array': true,
  38. 'flatten-duplicate-arrays': true,
  39. 'greedy-arrays': true,
  40. 'halt-at-non-option': false,
  41. 'nargs-eats-options': false,
  42. 'negation-prefix': 'no-',
  43. 'parse-numbers': true,
  44. 'parse-positional-numbers': true,
  45. 'populate--': false,
  46. 'set-placeholder-key': false,
  47. 'short-option-groups': true,
  48. 'strip-aliased': false,
  49. 'strip-dashed': false,
  50. 'unknown-options-as-args': false
  51. }, opts.configuration);
  52. const defaults = Object.assign(Object.create(null), opts.default);
  53. const configObjects = opts.configObjects || [];
  54. const envPrefix = opts.envPrefix;
  55. const notFlagsOption = configuration['populate--'];
  56. const notFlagsArgv = notFlagsOption ? '--' : '_';
  57. const newAliases = Object.create(null);
  58. const defaulted = Object.create(null);
  59. // allow a i18n handler to be passed in, default to a fake one (util.format).
  60. const __ = opts.__ || mixin.format;
  61. const flags = {
  62. aliases: Object.create(null),
  63. arrays: Object.create(null),
  64. bools: Object.create(null),
  65. strings: Object.create(null),
  66. numbers: Object.create(null),
  67. counts: Object.create(null),
  68. normalize: Object.create(null),
  69. configs: Object.create(null),
  70. nargs: Object.create(null),
  71. coercions: Object.create(null),
  72. keys: []
  73. };
  74. const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
  75. const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
  76. [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
  77. const key = typeof opt === 'object' ? opt.key : opt;
  78. // assign to flags[bools|strings|numbers]
  79. const assignment = Object.keys(opt).map(function (key) {
  80. const arrayFlagKeys = {
  81. boolean: 'bools',
  82. string: 'strings',
  83. number: 'numbers'
  84. };
  85. return arrayFlagKeys[key];
  86. }).filter(Boolean).pop();
  87. // assign key to be coerced
  88. if (assignment) {
  89. flags[assignment][key] = true;
  90. }
  91. flags.arrays[key] = true;
  92. flags.keys.push(key);
  93. });
  94. [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
  95. flags.bools[key] = true;
  96. flags.keys.push(key);
  97. });
  98. [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
  99. flags.strings[key] = true;
  100. flags.keys.push(key);
  101. });
  102. [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
  103. flags.numbers[key] = true;
  104. flags.keys.push(key);
  105. });
  106. [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
  107. flags.counts[key] = true;
  108. flags.keys.push(key);
  109. });
  110. [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
  111. flags.normalize[key] = true;
  112. flags.keys.push(key);
  113. });
  114. if (typeof opts.narg === 'object') {
  115. Object.entries(opts.narg).forEach(([key, value]) => {
  116. if (typeof value === 'number') {
  117. flags.nargs[key] = value;
  118. flags.keys.push(key);
  119. }
  120. });
  121. }
  122. if (typeof opts.coerce === 'object') {
  123. Object.entries(opts.coerce).forEach(([key, value]) => {
  124. if (typeof value === 'function') {
  125. flags.coercions[key] = value;
  126. flags.keys.push(key);
  127. }
  128. });
  129. }
  130. if (typeof opts.config !== 'undefined') {
  131. if (Array.isArray(opts.config) || typeof opts.config === 'string') {
  132. ;
  133. [].concat(opts.config).filter(Boolean).forEach(function (key) {
  134. flags.configs[key] = true;
  135. });
  136. }
  137. else if (typeof opts.config === 'object') {
  138. Object.entries(opts.config).forEach(([key, value]) => {
  139. if (typeof value === 'boolean' || typeof value === 'function') {
  140. flags.configs[key] = value;
  141. }
  142. });
  143. }
  144. }
  145. // create a lookup table that takes into account all
  146. // combinations of aliases: {f: ['foo'], foo: ['f']}
  147. extendAliases(opts.key, aliases, opts.default, flags.arrays);
  148. // apply default values to all aliases.
  149. Object.keys(defaults).forEach(function (key) {
  150. (flags.aliases[key] || []).forEach(function (alias) {
  151. defaults[alias] = defaults[key];
  152. });
  153. });
  154. let error = null;
  155. checkConfiguration();
  156. let notFlags = [];
  157. const argv = Object.assign(Object.create(null), { _: [] });
  158. // TODO(bcoe): for the first pass at removing object prototype we didn't
  159. // remove all prototypes from objects returned by this API, we might want
  160. // to gradually move towards doing so.
  161. const argvReturn = {};
  162. for (let i = 0; i < args.length; i++) {
  163. const arg = args[i];
  164. let broken;
  165. let key;
  166. let letters;
  167. let m;
  168. let next;
  169. let value;
  170. // any unknown option (except for end-of-options, "--")
  171. if (arg !== '--' && isUnknownOptionAsArg(arg)) {
  172. pushPositional(arg);
  173. // ---, ---=, ----, etc,
  174. }
  175. else if (arg.match(/---+(=|$)/)) {
  176. // options without key name are invalid.
  177. pushPositional(arg);
  178. continue;
  179. // -- separated by =
  180. }
  181. else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
  182. // Using [\s\S] instead of . because js doesn't support the
  183. // 'dotall' regex modifier. See:
  184. // http://stackoverflow.com/a/1068308/13216
  185. m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
  186. // arrays format = '--f=a b c'
  187. if (m !== null && Array.isArray(m) && m.length >= 3) {
  188. if (checkAllAliases(m[1], flags.arrays)) {
  189. i = eatArray(i, m[1], args, m[2]);
  190. }
  191. else if (checkAllAliases(m[1], flags.nargs) !== false) {
  192. // nargs format = '--f=monkey washing cat'
  193. i = eatNargs(i, m[1], args, m[2]);
  194. }
  195. else {
  196. setArg(m[1], m[2]);
  197. }
  198. }
  199. }
  200. else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
  201. m = arg.match(negatedBoolean);
  202. if (m !== null && Array.isArray(m) && m.length >= 2) {
  203. key = m[1];
  204. setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
  205. }
  206. // -- separated by space.
  207. }
  208. else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
  209. m = arg.match(/^--?(.+)/);
  210. if (m !== null && Array.isArray(m) && m.length >= 2) {
  211. key = m[1];
  212. if (checkAllAliases(key, flags.arrays)) {
  213. // array format = '--foo a b c'
  214. i = eatArray(i, key, args);
  215. }
  216. else if (checkAllAliases(key, flags.nargs) !== false) {
  217. // nargs format = '--foo a b c'
  218. // should be truthy even if: flags.nargs[key] === 0
  219. i = eatNargs(i, key, args);
  220. }
  221. else {
  222. next = args[i + 1];
  223. if (next !== undefined && (!next.match(/^-/) ||
  224. next.match(negative)) &&
  225. !checkAllAliases(key, flags.bools) &&
  226. !checkAllAliases(key, flags.counts)) {
  227. setArg(key, next);
  228. i++;
  229. }
  230. else if (/^(true|false)$/.test(next)) {
  231. setArg(key, next);
  232. i++;
  233. }
  234. else {
  235. setArg(key, defaultValue(key));
  236. }
  237. }
  238. }
  239. // dot-notation flag separated by '='.
  240. }
  241. else if (arg.match(/^-.\..+=/)) {
  242. m = arg.match(/^-([^=]+)=([\s\S]*)$/);
  243. if (m !== null && Array.isArray(m) && m.length >= 3) {
  244. setArg(m[1], m[2]);
  245. }
  246. // dot-notation flag separated by space.
  247. }
  248. else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
  249. next = args[i + 1];
  250. m = arg.match(/^-(.\..+)/);
  251. if (m !== null && Array.isArray(m) && m.length >= 2) {
  252. key = m[1];
  253. if (next !== undefined && !next.match(/^-/) &&
  254. !checkAllAliases(key, flags.bools) &&
  255. !checkAllAliases(key, flags.counts)) {
  256. setArg(key, next);
  257. i++;
  258. }
  259. else {
  260. setArg(key, defaultValue(key));
  261. }
  262. }
  263. }
  264. else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
  265. letters = arg.slice(1, -1).split('');
  266. broken = false;
  267. for (let j = 0; j < letters.length; j++) {
  268. next = arg.slice(j + 2);
  269. if (letters[j + 1] && letters[j + 1] === '=') {
  270. value = arg.slice(j + 3);
  271. key = letters[j];
  272. if (checkAllAliases(key, flags.arrays)) {
  273. // array format = '-f=a b c'
  274. i = eatArray(i, key, args, value);
  275. }
  276. else if (checkAllAliases(key, flags.nargs) !== false) {
  277. // nargs format = '-f=monkey washing cat'
  278. i = eatNargs(i, key, args, value);
  279. }
  280. else {
  281. setArg(key, value);
  282. }
  283. broken = true;
  284. break;
  285. }
  286. if (next === '-') {
  287. setArg(letters[j], next);
  288. continue;
  289. }
  290. // current letter is an alphabetic character and next value is a number
  291. if (/[A-Za-z]/.test(letters[j]) &&
  292. /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
  293. checkAllAliases(next, flags.bools) === false) {
  294. setArg(letters[j], next);
  295. broken = true;
  296. break;
  297. }
  298. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  299. setArg(letters[j], next);
  300. broken = true;
  301. break;
  302. }
  303. else {
  304. setArg(letters[j], defaultValue(letters[j]));
  305. }
  306. }
  307. key = arg.slice(-1)[0];
  308. if (!broken && key !== '-') {
  309. if (checkAllAliases(key, flags.arrays)) {
  310. // array format = '-f a b c'
  311. i = eatArray(i, key, args);
  312. }
  313. else if (checkAllAliases(key, flags.nargs) !== false) {
  314. // nargs format = '-f a b c'
  315. // should be truthy even if: flags.nargs[key] === 0
  316. i = eatNargs(i, key, args);
  317. }
  318. else {
  319. next = args[i + 1];
  320. if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
  321. next.match(negative)) &&
  322. !checkAllAliases(key, flags.bools) &&
  323. !checkAllAliases(key, flags.counts)) {
  324. setArg(key, next);
  325. i++;
  326. }
  327. else if (/^(true|false)$/.test(next)) {
  328. setArg(key, next);
  329. i++;
  330. }
  331. else {
  332. setArg(key, defaultValue(key));
  333. }
  334. }
  335. }
  336. }
  337. else if (arg.match(/^-[0-9]$/) &&
  338. arg.match(negative) &&
  339. checkAllAliases(arg.slice(1), flags.bools)) {
  340. // single-digit boolean alias, e.g: xargs -0
  341. key = arg.slice(1);
  342. setArg(key, defaultValue(key));
  343. }
  344. else if (arg === '--') {
  345. notFlags = args.slice(i + 1);
  346. break;
  347. }
  348. else if (configuration['halt-at-non-option']) {
  349. notFlags = args.slice(i);
  350. break;
  351. }
  352. else {
  353. pushPositional(arg);
  354. }
  355. }
  356. // order of precedence:
  357. // 1. command line arg
  358. // 2. value from env var
  359. // 3. value from config file
  360. // 4. value from config objects
  361. // 5. configured default value
  362. applyEnvVars(argv, true); // special case: check env vars that point to config file
  363. applyEnvVars(argv, false);
  364. setConfig(argv);
  365. setConfigObjects();
  366. applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
  367. applyCoercions(argv);
  368. if (configuration['set-placeholder-key'])
  369. setPlaceholderKeys(argv);
  370. // for any counts either not in args or without an explicit default, set to 0
  371. Object.keys(flags.counts).forEach(function (key) {
  372. if (!hasKey(argv, key.split('.')))
  373. setArg(key, 0);
  374. });
  375. // '--' defaults to undefined.
  376. if (notFlagsOption && notFlags.length)
  377. argv[notFlagsArgv] = [];
  378. notFlags.forEach(function (key) {
  379. argv[notFlagsArgv].push(key);
  380. });
  381. if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
  382. Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
  383. delete argv[key];
  384. });
  385. }
  386. if (configuration['strip-aliased']) {
  387. ;
  388. [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
  389. if (configuration['camel-case-expansion'] && alias.includes('-')) {
  390. delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
  391. }
  392. delete argv[alias];
  393. });
  394. }
  395. // Push argument into positional array, applying numeric coercion:
  396. function pushPositional(arg) {
  397. const maybeCoercedNumber = maybeCoerceNumber('_', arg);
  398. if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
  399. argv._.push(maybeCoercedNumber);
  400. }
  401. }
  402. // how many arguments should we consume, based
  403. // on the nargs option?
  404. function eatNargs(i, key, args, argAfterEqualSign) {
  405. let ii;
  406. let toEat = checkAllAliases(key, flags.nargs);
  407. // NaN has a special meaning for the array type, indicating that one or
  408. // more values are expected.
  409. toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
  410. if (toEat === 0) {
  411. if (!isUndefined(argAfterEqualSign)) {
  412. error = Error(__('Argument unexpected for: %s', key));
  413. }
  414. setArg(key, defaultValue(key));
  415. return i;
  416. }
  417. let available = isUndefined(argAfterEqualSign) ? 0 : 1;
  418. if (configuration['nargs-eats-options']) {
  419. // classic behavior, yargs eats positional and dash arguments.
  420. if (args.length - (i + 1) + available < toEat) {
  421. error = Error(__('Not enough arguments following: %s', key));
  422. }
  423. available = toEat;
  424. }
  425. else {
  426. // nargs will not consume flag arguments, e.g., -abc, --foo,
  427. // and terminates when one is observed.
  428. for (ii = i + 1; ii < args.length; ii++) {
  429. if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
  430. available++;
  431. else
  432. break;
  433. }
  434. if (available < toEat)
  435. error = Error(__('Not enough arguments following: %s', key));
  436. }
  437. let consumed = Math.min(available, toEat);
  438. if (!isUndefined(argAfterEqualSign) && consumed > 0) {
  439. setArg(key, argAfterEqualSign);
  440. consumed--;
  441. }
  442. for (ii = i + 1; ii < (consumed + i + 1); ii++) {
  443. setArg(key, args[ii]);
  444. }
  445. return (i + consumed);
  446. }
  447. // if an option is an array, eat all non-hyphenated arguments
  448. // following it... YUM!
  449. // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
  450. function eatArray(i, key, args, argAfterEqualSign) {
  451. let argsToSet = [];
  452. let next = argAfterEqualSign || args[i + 1];
  453. // If both array and nargs are configured, enforce the nargs count:
  454. const nargsCount = checkAllAliases(key, flags.nargs);
  455. if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
  456. argsToSet.push(true);
  457. }
  458. else if (isUndefined(next) ||
  459. (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
  460. // for keys without value ==> argsToSet remains an empty []
  461. // set user default value, if available
  462. if (defaults[key] !== undefined) {
  463. const defVal = defaults[key];
  464. argsToSet = Array.isArray(defVal) ? defVal : [defVal];
  465. }
  466. }
  467. else {
  468. // value in --option=value is eaten as is
  469. if (!isUndefined(argAfterEqualSign)) {
  470. argsToSet.push(processValue(key, argAfterEqualSign));
  471. }
  472. for (let ii = i + 1; ii < args.length; ii++) {
  473. if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
  474. (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
  475. break;
  476. next = args[ii];
  477. if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
  478. break;
  479. i = ii;
  480. argsToSet.push(processValue(key, next));
  481. }
  482. }
  483. // If both array and nargs are configured, create an error if less than
  484. // nargs positionals were found. NaN has special meaning, indicating
  485. // that at least one value is required (more are okay).
  486. if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
  487. (isNaN(nargsCount) && argsToSet.length === 0))) {
  488. error = Error(__('Not enough arguments following: %s', key));
  489. }
  490. setArg(key, argsToSet);
  491. return i;
  492. }
  493. function setArg(key, val) {
  494. if (/-/.test(key) && configuration['camel-case-expansion']) {
  495. const alias = key.split('.').map(function (prop) {
  496. return camelCase(prop);
  497. }).join('.');
  498. addNewAlias(key, alias);
  499. }
  500. const value = processValue(key, val);
  501. const splitKey = key.split('.');
  502. setKey(argv, splitKey, value);
  503. // handle populating aliases of the full key
  504. if (flags.aliases[key]) {
  505. flags.aliases[key].forEach(function (x) {
  506. const keyProperties = x.split('.');
  507. setKey(argv, keyProperties, value);
  508. });
  509. }
  510. // handle populating aliases of the first element of the dot-notation key
  511. if (splitKey.length > 1 && configuration['dot-notation']) {
  512. ;
  513. (flags.aliases[splitKey[0]] || []).forEach(function (x) {
  514. let keyProperties = x.split('.');
  515. // expand alias with nested objects in key
  516. const a = [].concat(splitKey);
  517. a.shift(); // nuke the old key.
  518. keyProperties = keyProperties.concat(a);
  519. // populate alias only if is not already an alias of the full key
  520. // (already populated above)
  521. if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
  522. setKey(argv, keyProperties, value);
  523. }
  524. });
  525. }
  526. // Set normalize getter and setter when key is in 'normalize' but isn't an array
  527. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  528. const keys = [key].concat(flags.aliases[key] || []);
  529. keys.forEach(function (key) {
  530. Object.defineProperty(argvReturn, key, {
  531. enumerable: true,
  532. get() {
  533. return val;
  534. },
  535. set(value) {
  536. val = typeof value === 'string' ? mixin.normalize(value) : value;
  537. }
  538. });
  539. });
  540. }
  541. }
  542. function addNewAlias(key, alias) {
  543. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  544. flags.aliases[key] = [alias];
  545. newAliases[alias] = true;
  546. }
  547. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  548. addNewAlias(alias, key);
  549. }
  550. }
  551. function processValue(key, val) {
  552. // strings may be quoted, clean this up as we assign values.
  553. if (typeof val === 'string' &&
  554. (val[0] === "'" || val[0] === '"') &&
  555. val[val.length - 1] === val[0]) {
  556. val = val.substring(1, val.length - 1);
  557. }
  558. // handle parsing boolean arguments --foo=true --bar false.
  559. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  560. if (typeof val === 'string')
  561. val = val === 'true';
  562. }
  563. let value = Array.isArray(val)
  564. ? val.map(function (v) { return maybeCoerceNumber(key, v); })
  565. : maybeCoerceNumber(key, val);
  566. // increment a count given as arg (either no value or value parsed as boolean)
  567. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  568. value = increment();
  569. }
  570. // Set normalized value when key is in 'normalize' and in 'arrays'
  571. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  572. if (Array.isArray(val))
  573. value = val.map((val) => { return mixin.normalize(val); });
  574. else
  575. value = mixin.normalize(val);
  576. }
  577. return value;
  578. }
  579. function maybeCoerceNumber(key, value) {
  580. if (!configuration['parse-positional-numbers'] && key === '_')
  581. return value;
  582. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
  583. const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
  584. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
  585. value = Number(value);
  586. }
  587. }
  588. return value;
  589. }
  590. // set args from config.json file, this should be
  591. // applied last so that defaults can be applied.
  592. function setConfig(argv) {
  593. const configLookup = Object.create(null);
  594. // expand defaults/aliases, in-case any happen to reference
  595. // the config.json file.
  596. applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
  597. Object.keys(flags.configs).forEach(function (configKey) {
  598. const configPath = argv[configKey] || configLookup[configKey];
  599. if (configPath) {
  600. try {
  601. let config = null;
  602. const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
  603. const resolveConfig = flags.configs[configKey];
  604. if (typeof resolveConfig === 'function') {
  605. try {
  606. config = resolveConfig(resolvedConfigPath);
  607. }
  608. catch (e) {
  609. config = e;
  610. }
  611. if (config instanceof Error) {
  612. error = config;
  613. return;
  614. }
  615. }
  616. else {
  617. config = mixin.require(resolvedConfigPath);
  618. }
  619. setConfigObject(config);
  620. }
  621. catch (ex) {
  622. // Deno will receive a PermissionDenied error if an attempt is
  623. // made to load config without the --allow-read flag:
  624. if (ex.name === 'PermissionDenied')
  625. error = ex;
  626. else if (argv[configKey])
  627. error = Error(__('Invalid JSON config file: %s', configPath));
  628. }
  629. }
  630. });
  631. }
  632. // set args from config object.
  633. // it recursively checks nested objects.
  634. function setConfigObject(config, prev) {
  635. Object.keys(config).forEach(function (key) {
  636. const value = config[key];
  637. const fullKey = prev ? prev + '.' + key : key;
  638. // if the value is an inner object and we have dot-notation
  639. // enabled, treat inner objects in config the same as
  640. // heavily nested dot notations (foo.bar.apple).
  641. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  642. // if the value is an object but not an array, check nested object
  643. setConfigObject(value, fullKey);
  644. }
  645. else {
  646. // setting arguments via CLI takes precedence over
  647. // values within the config file.
  648. if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
  649. setArg(fullKey, value);
  650. }
  651. }
  652. });
  653. }
  654. // set all config objects passed in opts
  655. function setConfigObjects() {
  656. if (typeof configObjects !== 'undefined') {
  657. configObjects.forEach(function (configObject) {
  658. setConfigObject(configObject);
  659. });
  660. }
  661. }
  662. function applyEnvVars(argv, configOnly) {
  663. if (typeof envPrefix === 'undefined')
  664. return;
  665. const prefix = typeof envPrefix === 'string' ? envPrefix : '';
  666. const env = mixin.env();
  667. Object.keys(env).forEach(function (envVar) {
  668. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  669. // get array of nested keys and convert them to camel case
  670. const keys = envVar.split('__').map(function (key, i) {
  671. if (i === 0) {
  672. key = key.substring(prefix.length);
  673. }
  674. return camelCase(key);
  675. });
  676. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
  677. setArg(keys.join('.'), env[envVar]);
  678. }
  679. }
  680. });
  681. }
  682. function applyCoercions(argv) {
  683. let coerce;
  684. const applied = new Set();
  685. Object.keys(argv).forEach(function (key) {
  686. if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
  687. coerce = checkAllAliases(key, flags.coercions);
  688. if (typeof coerce === 'function') {
  689. try {
  690. const value = maybeCoerceNumber(key, coerce(argv[key]));
  691. ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  692. applied.add(ali);
  693. argv[ali] = value;
  694. });
  695. }
  696. catch (err) {
  697. error = err;
  698. }
  699. }
  700. }
  701. });
  702. }
  703. function setPlaceholderKeys(argv) {
  704. flags.keys.forEach((key) => {
  705. // don't set placeholder keys for dot notation options 'foo.bar'.
  706. if (~key.indexOf('.'))
  707. return;
  708. if (typeof argv[key] === 'undefined')
  709. argv[key] = undefined;
  710. });
  711. return argv;
  712. }
  713. function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
  714. Object.keys(defaults).forEach(function (key) {
  715. if (!hasKey(obj, key.split('.'))) {
  716. setKey(obj, key.split('.'), defaults[key]);
  717. if (canLog)
  718. defaulted[key] = true;
  719. (aliases[key] || []).forEach(function (x) {
  720. if (hasKey(obj, x.split('.')))
  721. return;
  722. setKey(obj, x.split('.'), defaults[key]);
  723. });
  724. }
  725. });
  726. }
  727. function hasKey(obj, keys) {
  728. let o = obj;
  729. if (!configuration['dot-notation'])
  730. keys = [keys.join('.')];
  731. keys.slice(0, -1).forEach(function (key) {
  732. o = (o[key] || {});
  733. });
  734. const key = keys[keys.length - 1];
  735. if (typeof o !== 'object')
  736. return false;
  737. else
  738. return key in o;
  739. }
  740. function setKey(obj, keys, value) {
  741. let o = obj;
  742. if (!configuration['dot-notation'])
  743. keys = [keys.join('.')];
  744. keys.slice(0, -1).forEach(function (key) {
  745. // TODO(bcoe): in the next major version of yargs, switch to
  746. // Object.create(null) for dot notation:
  747. key = sanitizeKey(key);
  748. if (typeof o === 'object' && o[key] === undefined) {
  749. o[key] = {};
  750. }
  751. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  752. // ensure that o[key] is an array, and that the last item is an empty object.
  753. if (Array.isArray(o[key])) {
  754. o[key].push({});
  755. }
  756. else {
  757. o[key] = [o[key], {}];
  758. }
  759. // we want to update the empty object at the end of the o[key] array, so set o to that object
  760. o = o[key][o[key].length - 1];
  761. }
  762. else {
  763. o = o[key];
  764. }
  765. });
  766. // TODO(bcoe): in the next major version of yargs, switch to
  767. // Object.create(null) for dot notation:
  768. const key = sanitizeKey(keys[keys.length - 1]);
  769. const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
  770. const isValueArray = Array.isArray(value);
  771. let duplicate = configuration['duplicate-arguments-array'];
  772. // nargs has higher priority than duplicate
  773. if (!duplicate && checkAllAliases(key, flags.nargs)) {
  774. duplicate = true;
  775. if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
  776. o[key] = undefined;
  777. }
  778. }
  779. if (value === increment()) {
  780. o[key] = increment(o[key]);
  781. }
  782. else if (Array.isArray(o[key])) {
  783. if (duplicate && isTypeArray && isValueArray) {
  784. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
  785. }
  786. else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  787. o[key] = value;
  788. }
  789. else {
  790. o[key] = o[key].concat([value]);
  791. }
  792. }
  793. else if (o[key] === undefined && isTypeArray) {
  794. o[key] = isValueArray ? value : [value];
  795. }
  796. else if (duplicate && !(o[key] === undefined ||
  797. checkAllAliases(key, flags.counts) ||
  798. checkAllAliases(key, flags.bools))) {
  799. o[key] = [o[key], value];
  800. }
  801. else {
  802. o[key] = value;
  803. }
  804. }
  805. // extend the aliases list with inferred aliases.
  806. function extendAliases(...args) {
  807. args.forEach(function (obj) {
  808. Object.keys(obj || {}).forEach(function (key) {
  809. // short-circuit if we've already added a key
  810. // to the aliases array, for example it might
  811. // exist in both 'opts.default' and 'opts.key'.
  812. if (flags.aliases[key])
  813. return;
  814. flags.aliases[key] = [].concat(aliases[key] || []);
  815. // For "--option-name", also set argv.optionName
  816. flags.aliases[key].concat(key).forEach(function (x) {
  817. if (/-/.test(x) && configuration['camel-case-expansion']) {
  818. const c = camelCase(x);
  819. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  820. flags.aliases[key].push(c);
  821. newAliases[c] = true;
  822. }
  823. }
  824. });
  825. // For "--optionName", also set argv['option-name']
  826. flags.aliases[key].concat(key).forEach(function (x) {
  827. if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
  828. const c = decamelize(x, '-');
  829. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  830. flags.aliases[key].push(c);
  831. newAliases[c] = true;
  832. }
  833. }
  834. });
  835. flags.aliases[key].forEach(function (x) {
  836. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  837. return x !== y;
  838. }));
  839. });
  840. });
  841. });
  842. }
  843. function checkAllAliases(key, flag) {
  844. const toCheck = [].concat(flags.aliases[key] || [], key);
  845. const keys = Object.keys(flag);
  846. const setAlias = toCheck.find(key => keys.includes(key));
  847. return setAlias ? flag[setAlias] : false;
  848. }
  849. function hasAnyFlag(key) {
  850. const flagsKeys = Object.keys(flags);
  851. const toCheck = [].concat(flagsKeys.map(k => flags[k]));
  852. return toCheck.some(function (flag) {
  853. return Array.isArray(flag) ? flag.includes(key) : flag[key];
  854. });
  855. }
  856. function hasFlagsMatching(arg, ...patterns) {
  857. const toCheck = [].concat(...patterns);
  858. return toCheck.some(function (pattern) {
  859. const match = arg.match(pattern);
  860. return match && hasAnyFlag(match[1]);
  861. });
  862. }
  863. // based on a simplified version of the short flag group parsing logic
  864. function hasAllShortFlags(arg) {
  865. // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
  866. if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
  867. return false;
  868. }
  869. let hasAllFlags = true;
  870. let next;
  871. const letters = arg.slice(1).split('');
  872. for (let j = 0; j < letters.length; j++) {
  873. next = arg.slice(j + 2);
  874. if (!hasAnyFlag(letters[j])) {
  875. hasAllFlags = false;
  876. break;
  877. }
  878. if ((letters[j + 1] && letters[j + 1] === '=') ||
  879. next === '-' ||
  880. (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
  881. (letters[j + 1] && letters[j + 1].match(/\W/))) {
  882. break;
  883. }
  884. }
  885. return hasAllFlags;
  886. }
  887. function isUnknownOptionAsArg(arg) {
  888. return configuration['unknown-options-as-args'] && isUnknownOption(arg);
  889. }
  890. function isUnknownOption(arg) {
  891. // ignore negative numbers
  892. if (arg.match(negative)) {
  893. return false;
  894. }
  895. // if this is a short option group and all of them are configured, it isn't unknown
  896. if (hasAllShortFlags(arg)) {
  897. return false;
  898. }
  899. // e.g. '--count=2'
  900. const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
  901. // e.g. '-a' or '--arg'
  902. const normalFlag = /^-+([^=]+?)$/;
  903. // e.g. '-a-'
  904. const flagEndingInHyphen = /^-+([^=]+?)-$/;
  905. // e.g. '-abc123'
  906. const flagEndingInDigits = /^-+([^=]+?\d+)$/;
  907. // e.g. '-a/usr/local'
  908. const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
  909. // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
  910. return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
  911. }
  912. // make a best effort to pick a default value
  913. // for an option based on name and type.
  914. function defaultValue(key) {
  915. if (!checkAllAliases(key, flags.bools) &&
  916. !checkAllAliases(key, flags.counts) &&
  917. `${key}` in defaults) {
  918. return defaults[key];
  919. }
  920. else {
  921. return defaultForType(guessType(key));
  922. }
  923. }
  924. // return a default value, given the type of a flag.,
  925. function defaultForType(type) {
  926. const def = {
  927. boolean: true,
  928. string: '',
  929. number: undefined,
  930. array: []
  931. };
  932. return def[type];
  933. }
  934. // given a flag, enforce a default type.
  935. function guessType(key) {
  936. let type = 'boolean';
  937. if (checkAllAliases(key, flags.strings))
  938. type = 'string';
  939. else if (checkAllAliases(key, flags.numbers))
  940. type = 'number';
  941. else if (checkAllAliases(key, flags.bools))
  942. type = 'boolean';
  943. else if (checkAllAliases(key, flags.arrays))
  944. type = 'array';
  945. return type;
  946. }
  947. function isUndefined(num) {
  948. return num === undefined;
  949. }
  950. // check user configuration settings for inconsistencies
  951. function checkConfiguration() {
  952. // count keys should not be set as array/narg
  953. Object.keys(flags.counts).find(key => {
  954. if (checkAllAliases(key, flags.arrays)) {
  955. error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
  956. return true;
  957. }
  958. else if (checkAllAliases(key, flags.nargs)) {
  959. error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
  960. return true;
  961. }
  962. return false;
  963. });
  964. }
  965. return {
  966. aliases: Object.assign({}, flags.aliases),
  967. argv: Object.assign(argvReturn, argv),
  968. configuration: configuration,
  969. defaulted: Object.assign({}, defaulted),
  970. error: error,
  971. newAliases: Object.assign({}, newAliases)
  972. };
  973. }
  974. }
  975. // if any aliases reference each other, we should
  976. // merge them together.
  977. function combineAliases(aliases) {
  978. const aliasArrays = [];
  979. const combined = Object.create(null);
  980. let change = true;
  981. // turn alias lookup hash {key: ['alias1', 'alias2']} into
  982. // a simple array ['key', 'alias1', 'alias2']
  983. Object.keys(aliases).forEach(function (key) {
  984. aliasArrays.push([].concat(aliases[key], key));
  985. });
  986. // combine arrays until zero changes are
  987. // made in an iteration.
  988. while (change) {
  989. change = false;
  990. for (let i = 0; i < aliasArrays.length; i++) {
  991. for (let ii = i + 1; ii < aliasArrays.length; ii++) {
  992. const intersect = aliasArrays[i].filter(function (v) {
  993. return aliasArrays[ii].indexOf(v) !== -1;
  994. });
  995. if (intersect.length) {
  996. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
  997. aliasArrays.splice(ii, 1);
  998. change = true;
  999. break;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. // map arrays back to the hash-lookup (de-dupe while
  1005. // we're at it).
  1006. aliasArrays.forEach(function (aliasArray) {
  1007. aliasArray = aliasArray.filter(function (v, i, self) {
  1008. return self.indexOf(v) === i;
  1009. });
  1010. const lastAlias = aliasArray.pop();
  1011. if (lastAlias !== undefined && typeof lastAlias === 'string') {
  1012. combined[lastAlias] = aliasArray;
  1013. }
  1014. });
  1015. return combined;
  1016. }
  1017. // this function should only be called when a count is given as an arg
  1018. // it is NOT called to set a default value
  1019. // thus we can start the count at 1 instead of 0
  1020. function increment(orig) {
  1021. return orig !== undefined ? orig + 1 : 1;
  1022. }
  1023. // TODO(bcoe): in the next major version of yargs, switch to
  1024. // Object.create(null) for dot notation:
  1025. function sanitizeKey(key) {
  1026. if (key === '__proto__')
  1027. return '___proto___';
  1028. return key;
  1029. }