yargs-factory.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. import { command as Command, } from './command.js';
  2. import { assertNotStrictEqual, assertSingleKey, objectKeys, } from './typings/common-types.js';
  3. import { YError } from './yerror.js';
  4. import { usage as Usage } from './usage.js';
  5. import { argsert } from './argsert.js';
  6. import { completion as Completion, } from './completion.js';
  7. import { validation as Validation, } from './validation.js';
  8. import { objFilter } from './utils/obj-filter.js';
  9. import { applyExtends } from './utils/apply-extends.js';
  10. import { globalMiddlewareFactory, } from './middleware.js';
  11. import { isPromise } from './utils/is-promise.js';
  12. import setBlocking from './utils/set-blocking.js';
  13. let shim;
  14. export function YargsWithShim(_shim) {
  15. shim = _shim;
  16. return Yargs;
  17. }
  18. function Yargs(processArgs = [], cwd = shim.process.cwd(), parentRequire) {
  19. const self = {};
  20. let command;
  21. let completion = null;
  22. let groups = {};
  23. const globalMiddleware = [];
  24. let output = '';
  25. const preservedGroups = {};
  26. let usage;
  27. let validation;
  28. let handlerFinishCommand = null;
  29. const y18n = shim.y18n;
  30. self.middleware = globalMiddlewareFactory(globalMiddleware, self);
  31. self.scriptName = function (scriptName) {
  32. self.customScriptName = true;
  33. self.$0 = scriptName;
  34. return self;
  35. };
  36. let default$0;
  37. if (/\b(node|iojs|electron)(\.exe)?$/.test(shim.process.argv()[0])) {
  38. default$0 = shim.process.argv().slice(1, 2);
  39. }
  40. else {
  41. default$0 = shim.process.argv().slice(0, 1);
  42. }
  43. self.$0 = default$0
  44. .map(x => {
  45. const b = rebase(cwd, x);
  46. return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
  47. })
  48. .join(' ')
  49. .trim();
  50. if (shim.getEnv('_') && shim.getProcessArgvBin() === shim.getEnv('_')) {
  51. self.$0 = shim
  52. .getEnv('_')
  53. .replace(`${shim.path.dirname(shim.process.execPath())}/`, '');
  54. }
  55. const context = { resets: -1, commands: [], fullCommands: [], files: [] };
  56. self.getContext = () => context;
  57. let hasOutput = false;
  58. let exitError = null;
  59. self.exit = (code, err) => {
  60. hasOutput = true;
  61. exitError = err;
  62. if (exitProcess)
  63. shim.process.exit(code);
  64. };
  65. let completionCommand = null;
  66. self.completion = function (cmd, desc, fn) {
  67. argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
  68. if (typeof desc === 'function') {
  69. fn = desc;
  70. desc = undefined;
  71. }
  72. completionCommand = cmd || completionCommand || 'completion';
  73. if (!desc && desc !== false) {
  74. desc = 'generate completion script';
  75. }
  76. self.command(completionCommand, desc);
  77. if (fn)
  78. completion.registerFunction(fn);
  79. return self;
  80. };
  81. let options;
  82. self.resetOptions = self.reset = function resetOptions(aliases = {}) {
  83. context.resets++;
  84. options = options || {};
  85. const tmpOptions = {};
  86. tmpOptions.local = options.local ? options.local : [];
  87. tmpOptions.configObjects = options.configObjects
  88. ? options.configObjects
  89. : [];
  90. const localLookup = {};
  91. tmpOptions.local.forEach(l => {
  92. localLookup[l] = true;
  93. (aliases[l] || []).forEach(a => {
  94. localLookup[a] = true;
  95. });
  96. });
  97. Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => {
  98. const keys = groups[groupName].filter(key => !(key in localLookup));
  99. if (keys.length > 0) {
  100. acc[groupName] = keys;
  101. }
  102. return acc;
  103. }, {}));
  104. groups = {};
  105. const arrayOptions = [
  106. 'array',
  107. 'boolean',
  108. 'string',
  109. 'skipValidation',
  110. 'count',
  111. 'normalize',
  112. 'number',
  113. 'hiddenOptions',
  114. ];
  115. const objectOptions = [
  116. 'narg',
  117. 'key',
  118. 'alias',
  119. 'default',
  120. 'defaultDescription',
  121. 'config',
  122. 'choices',
  123. 'demandedOptions',
  124. 'demandedCommands',
  125. 'coerce',
  126. 'deprecatedOptions',
  127. ];
  128. arrayOptions.forEach(k => {
  129. tmpOptions[k] = (options[k] || []).filter((k) => !localLookup[k]);
  130. });
  131. objectOptions.forEach((k) => {
  132. tmpOptions[k] = objFilter(options[k], k => !localLookup[k]);
  133. });
  134. tmpOptions.envPrefix = options.envPrefix;
  135. options = tmpOptions;
  136. usage = usage ? usage.reset(localLookup) : Usage(self, y18n, shim);
  137. validation = validation
  138. ? validation.reset(localLookup)
  139. : Validation(self, usage, y18n, shim);
  140. command = command
  141. ? command.reset()
  142. : Command(self, usage, validation, globalMiddleware, shim);
  143. if (!completion)
  144. completion = Completion(self, usage, command, shim);
  145. completionCommand = null;
  146. output = '';
  147. exitError = null;
  148. hasOutput = false;
  149. self.parsed = false;
  150. return self;
  151. };
  152. self.resetOptions();
  153. const frozens = [];
  154. function freeze() {
  155. frozens.push({
  156. options,
  157. configObjects: options.configObjects.slice(0),
  158. exitProcess,
  159. groups,
  160. strict,
  161. strictCommands,
  162. strictOptions,
  163. completionCommand,
  164. output,
  165. exitError,
  166. hasOutput,
  167. parsed: self.parsed,
  168. parseFn,
  169. parseContext,
  170. handlerFinishCommand,
  171. });
  172. usage.freeze();
  173. validation.freeze();
  174. command.freeze();
  175. }
  176. function unfreeze() {
  177. const frozen = frozens.pop();
  178. assertNotStrictEqual(frozen, undefined, shim);
  179. let configObjects;
  180. ({
  181. options,
  182. configObjects,
  183. exitProcess,
  184. groups,
  185. output,
  186. exitError,
  187. hasOutput,
  188. parsed: self.parsed,
  189. strict,
  190. strictCommands,
  191. strictOptions,
  192. completionCommand,
  193. parseFn,
  194. parseContext,
  195. handlerFinishCommand,
  196. } = frozen);
  197. options.configObjects = configObjects;
  198. usage.unfreeze();
  199. validation.unfreeze();
  200. command.unfreeze();
  201. }
  202. self.boolean = function (keys) {
  203. argsert('<array|string>', [keys], arguments.length);
  204. populateParserHintArray('boolean', keys);
  205. return self;
  206. };
  207. self.array = function (keys) {
  208. argsert('<array|string>', [keys], arguments.length);
  209. populateParserHintArray('array', keys);
  210. return self;
  211. };
  212. self.number = function (keys) {
  213. argsert('<array|string>', [keys], arguments.length);
  214. populateParserHintArray('number', keys);
  215. return self;
  216. };
  217. self.normalize = function (keys) {
  218. argsert('<array|string>', [keys], arguments.length);
  219. populateParserHintArray('normalize', keys);
  220. return self;
  221. };
  222. self.count = function (keys) {
  223. argsert('<array|string>', [keys], arguments.length);
  224. populateParserHintArray('count', keys);
  225. return self;
  226. };
  227. self.string = function (keys) {
  228. argsert('<array|string>', [keys], arguments.length);
  229. populateParserHintArray('string', keys);
  230. return self;
  231. };
  232. self.requiresArg = function (keys) {
  233. argsert('<array|string|object> [number]', [keys], arguments.length);
  234. if (typeof keys === 'string' && options.narg[keys]) {
  235. return self;
  236. }
  237. else {
  238. populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN);
  239. }
  240. return self;
  241. };
  242. self.skipValidation = function (keys) {
  243. argsert('<array|string>', [keys], arguments.length);
  244. populateParserHintArray('skipValidation', keys);
  245. return self;
  246. };
  247. function populateParserHintArray(type, keys) {
  248. keys = [].concat(keys);
  249. keys.forEach(key => {
  250. key = sanitizeKey(key);
  251. options[type].push(key);
  252. });
  253. }
  254. self.nargs = function (key, value) {
  255. argsert('<string|object|array> [number]', [key, value], arguments.length);
  256. populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value);
  257. return self;
  258. };
  259. self.choices = function (key, value) {
  260. argsert('<object|string|array> [string|array]', [key, value], arguments.length);
  261. populateParserHintArrayDictionary(self.choices, 'choices', key, value);
  262. return self;
  263. };
  264. self.alias = function (key, value) {
  265. argsert('<object|string|array> [string|array]', [key, value], arguments.length);
  266. populateParserHintArrayDictionary(self.alias, 'alias', key, value);
  267. return self;
  268. };
  269. self.default = self.defaults = function (key, value, defaultDescription) {
  270. argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
  271. if (defaultDescription) {
  272. assertSingleKey(key, shim);
  273. options.defaultDescription[key] = defaultDescription;
  274. }
  275. if (typeof value === 'function') {
  276. assertSingleKey(key, shim);
  277. if (!options.defaultDescription[key])
  278. options.defaultDescription[key] = usage.functionDescription(value);
  279. value = value.call();
  280. }
  281. populateParserHintSingleValueDictionary(self.default, 'default', key, value);
  282. return self;
  283. };
  284. self.describe = function (key, desc) {
  285. argsert('<object|string|array> [string]', [key, desc], arguments.length);
  286. setKey(key, true);
  287. usage.describe(key, desc);
  288. return self;
  289. };
  290. function setKey(key, set) {
  291. populateParserHintSingleValueDictionary(setKey, 'key', key, set);
  292. return self;
  293. }
  294. function demandOption(keys, msg) {
  295. argsert('<object|string|array> [string]', [keys, msg], arguments.length);
  296. populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg);
  297. return self;
  298. }
  299. self.demandOption = demandOption;
  300. self.coerce = function (keys, value) {
  301. argsert('<object|string|array> [function]', [keys, value], arguments.length);
  302. populateParserHintSingleValueDictionary(self.coerce, 'coerce', keys, value);
  303. return self;
  304. };
  305. function populateParserHintSingleValueDictionary(builder, type, key, value) {
  306. populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
  307. options[type][key] = value;
  308. });
  309. }
  310. function populateParserHintArrayDictionary(builder, type, key, value) {
  311. populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
  312. options[type][key] = (options[type][key] || []).concat(value);
  313. });
  314. }
  315. function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) {
  316. if (Array.isArray(key)) {
  317. key.forEach(k => {
  318. builder(k, value);
  319. });
  320. }
  321. else if (((key) => typeof key === 'object')(key)) {
  322. for (const k of objectKeys(key)) {
  323. builder(k, key[k]);
  324. }
  325. }
  326. else {
  327. singleKeyHandler(type, sanitizeKey(key), value);
  328. }
  329. }
  330. function sanitizeKey(key) {
  331. if (key === '__proto__')
  332. return '___proto___';
  333. return key;
  334. }
  335. function deleteFromParserHintObject(optionKey) {
  336. objectKeys(options).forEach((hintKey) => {
  337. if (((key) => key === 'configObjects')(hintKey))
  338. return;
  339. const hint = options[hintKey];
  340. if (Array.isArray(hint)) {
  341. if (~hint.indexOf(optionKey))
  342. hint.splice(hint.indexOf(optionKey), 1);
  343. }
  344. else if (typeof hint === 'object') {
  345. delete hint[optionKey];
  346. }
  347. });
  348. delete usage.getDescriptions()[optionKey];
  349. }
  350. self.config = function config(key = 'config', msg, parseFn) {
  351. argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
  352. if (typeof key === 'object' && !Array.isArray(key)) {
  353. key = applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim);
  354. options.configObjects = (options.configObjects || []).concat(key);
  355. return self;
  356. }
  357. if (typeof msg === 'function') {
  358. parseFn = msg;
  359. msg = undefined;
  360. }
  361. self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'));
  362. (Array.isArray(key) ? key : [key]).forEach(k => {
  363. options.config[k] = parseFn || true;
  364. });
  365. return self;
  366. };
  367. self.example = function (cmd, description) {
  368. argsert('<string|array> [string]', [cmd, description], arguments.length);
  369. if (Array.isArray(cmd)) {
  370. cmd.forEach(exampleParams => self.example(...exampleParams));
  371. }
  372. else {
  373. usage.example(cmd, description);
  374. }
  375. return self;
  376. };
  377. self.command = function (cmd, description, builder, handler, middlewares, deprecated) {
  378. argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
  379. command.addHandler(cmd, description, builder, handler, middlewares, deprecated);
  380. return self;
  381. };
  382. self.commandDir = function (dir, opts) {
  383. argsert('<string> [object]', [dir, opts], arguments.length);
  384. const req = parentRequire || shim.require;
  385. command.addDirectory(dir, self.getContext(), req, shim.getCallerFile(), opts);
  386. return self;
  387. };
  388. self.demand = self.required = self.require = function demand(keys, max, msg) {
  389. if (Array.isArray(max)) {
  390. max.forEach(key => {
  391. assertNotStrictEqual(msg, true, shim);
  392. demandOption(key, msg);
  393. });
  394. max = Infinity;
  395. }
  396. else if (typeof max !== 'number') {
  397. msg = max;
  398. max = Infinity;
  399. }
  400. if (typeof keys === 'number') {
  401. assertNotStrictEqual(msg, true, shim);
  402. self.demandCommand(keys, max, msg, msg);
  403. }
  404. else if (Array.isArray(keys)) {
  405. keys.forEach(key => {
  406. assertNotStrictEqual(msg, true, shim);
  407. demandOption(key, msg);
  408. });
  409. }
  410. else {
  411. if (typeof msg === 'string') {
  412. demandOption(keys, msg);
  413. }
  414. else if (msg === true || typeof msg === 'undefined') {
  415. demandOption(keys);
  416. }
  417. }
  418. return self;
  419. };
  420. self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) {
  421. argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
  422. if (typeof max !== 'number') {
  423. minMsg = max;
  424. max = Infinity;
  425. }
  426. self.global('_', false);
  427. options.demandedCommands._ = {
  428. min,
  429. max,
  430. minMsg,
  431. maxMsg,
  432. };
  433. return self;
  434. };
  435. self.getDemandedOptions = () => {
  436. argsert([], 0);
  437. return options.demandedOptions;
  438. };
  439. self.getDemandedCommands = () => {
  440. argsert([], 0);
  441. return options.demandedCommands;
  442. };
  443. self.deprecateOption = function deprecateOption(option, message) {
  444. argsert('<string> [string|boolean]', [option, message], arguments.length);
  445. options.deprecatedOptions[option] = message;
  446. return self;
  447. };
  448. self.getDeprecatedOptions = () => {
  449. argsert([], 0);
  450. return options.deprecatedOptions;
  451. };
  452. self.implies = function (key, value) {
  453. argsert('<string|object> [number|string|array]', [key, value], arguments.length);
  454. validation.implies(key, value);
  455. return self;
  456. };
  457. self.conflicts = function (key1, key2) {
  458. argsert('<string|object> [string|array]', [key1, key2], arguments.length);
  459. validation.conflicts(key1, key2);
  460. return self;
  461. };
  462. self.usage = function (msg, description, builder, handler) {
  463. argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
  464. if (description !== undefined) {
  465. assertNotStrictEqual(msg, null, shim);
  466. if ((msg || '').match(/^\$0( |$)/)) {
  467. return self.command(msg, description, builder, handler);
  468. }
  469. else {
  470. throw new YError('.usage() description must start with $0 if being used as alias for .command()');
  471. }
  472. }
  473. else {
  474. usage.usage(msg);
  475. return self;
  476. }
  477. };
  478. self.epilogue = self.epilog = function (msg) {
  479. argsert('<string>', [msg], arguments.length);
  480. usage.epilog(msg);
  481. return self;
  482. };
  483. self.fail = function (f) {
  484. argsert('<function>', [f], arguments.length);
  485. usage.failFn(f);
  486. return self;
  487. };
  488. self.onFinishCommand = function (f) {
  489. argsert('<function>', [f], arguments.length);
  490. handlerFinishCommand = f;
  491. return self;
  492. };
  493. self.getHandlerFinishCommand = () => handlerFinishCommand;
  494. self.check = function (f, _global) {
  495. argsert('<function> [boolean]', [f, _global], arguments.length);
  496. validation.check(f, _global !== false);
  497. return self;
  498. };
  499. self.global = function global(globals, global) {
  500. argsert('<string|array> [boolean]', [globals, global], arguments.length);
  501. globals = [].concat(globals);
  502. if (global !== false) {
  503. options.local = options.local.filter(l => globals.indexOf(l) === -1);
  504. }
  505. else {
  506. globals.forEach(g => {
  507. if (options.local.indexOf(g) === -1)
  508. options.local.push(g);
  509. });
  510. }
  511. return self;
  512. };
  513. self.pkgConf = function pkgConf(key, rootPath) {
  514. argsert('<string> [string]', [key, rootPath], arguments.length);
  515. let conf = null;
  516. const obj = pkgUp(rootPath || cwd);
  517. if (obj[key] && typeof obj[key] === 'object') {
  518. conf = applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim);
  519. options.configObjects = (options.configObjects || []).concat(conf);
  520. }
  521. return self;
  522. };
  523. const pkgs = {};
  524. function pkgUp(rootPath) {
  525. const npath = rootPath || '*';
  526. if (pkgs[npath])
  527. return pkgs[npath];
  528. let obj = {};
  529. try {
  530. let startDir = rootPath || shim.mainFilename;
  531. if (!rootPath && shim.path.extname(startDir)) {
  532. startDir = shim.path.dirname(startDir);
  533. }
  534. const pkgJsonPath = shim.findUp(startDir, (dir, names) => {
  535. if (names.includes('package.json')) {
  536. return 'package.json';
  537. }
  538. else {
  539. return undefined;
  540. }
  541. });
  542. assertNotStrictEqual(pkgJsonPath, undefined, shim);
  543. obj = JSON.parse(shim.readFileSync(pkgJsonPath, 'utf8'));
  544. }
  545. catch (_noop) { }
  546. pkgs[npath] = obj || {};
  547. return pkgs[npath];
  548. }
  549. let parseFn = null;
  550. let parseContext = null;
  551. self.parse = function parse(args, shortCircuit, _parseFn) {
  552. argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
  553. freeze();
  554. if (typeof args === 'undefined') {
  555. const argv = self._parseArgs(processArgs);
  556. const tmpParsed = self.parsed;
  557. unfreeze();
  558. self.parsed = tmpParsed;
  559. return argv;
  560. }
  561. if (typeof shortCircuit === 'object') {
  562. parseContext = shortCircuit;
  563. shortCircuit = _parseFn;
  564. }
  565. if (typeof shortCircuit === 'function') {
  566. parseFn = shortCircuit;
  567. shortCircuit = false;
  568. }
  569. if (!shortCircuit)
  570. processArgs = args;
  571. if (parseFn)
  572. exitProcess = false;
  573. const parsed = self._parseArgs(args, !!shortCircuit);
  574. completion.setParsed(self.parsed);
  575. if (parseFn)
  576. parseFn(exitError, parsed, output);
  577. unfreeze();
  578. return parsed;
  579. };
  580. self._getParseContext = () => parseContext || {};
  581. self._hasParseCallback = () => !!parseFn;
  582. self.option = self.options = function option(key, opt) {
  583. argsert('<string|object> [object]', [key, opt], arguments.length);
  584. if (typeof key === 'object') {
  585. Object.keys(key).forEach(k => {
  586. self.options(k, key[k]);
  587. });
  588. }
  589. else {
  590. if (typeof opt !== 'object') {
  591. opt = {};
  592. }
  593. options.key[key] = true;
  594. if (opt.alias)
  595. self.alias(key, opt.alias);
  596. const deprecate = opt.deprecate || opt.deprecated;
  597. if (deprecate) {
  598. self.deprecateOption(key, deprecate);
  599. }
  600. const demand = opt.demand || opt.required || opt.require;
  601. if (demand) {
  602. self.demand(key, demand);
  603. }
  604. if (opt.demandOption) {
  605. self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
  606. }
  607. if (opt.conflicts) {
  608. self.conflicts(key, opt.conflicts);
  609. }
  610. if ('default' in opt) {
  611. self.default(key, opt.default);
  612. }
  613. if (opt.implies !== undefined) {
  614. self.implies(key, opt.implies);
  615. }
  616. if (opt.nargs !== undefined) {
  617. self.nargs(key, opt.nargs);
  618. }
  619. if (opt.config) {
  620. self.config(key, opt.configParser);
  621. }
  622. if (opt.normalize) {
  623. self.normalize(key);
  624. }
  625. if (opt.choices) {
  626. self.choices(key, opt.choices);
  627. }
  628. if (opt.coerce) {
  629. self.coerce(key, opt.coerce);
  630. }
  631. if (opt.group) {
  632. self.group(key, opt.group);
  633. }
  634. if (opt.boolean || opt.type === 'boolean') {
  635. self.boolean(key);
  636. if (opt.alias)
  637. self.boolean(opt.alias);
  638. }
  639. if (opt.array || opt.type === 'array') {
  640. self.array(key);
  641. if (opt.alias)
  642. self.array(opt.alias);
  643. }
  644. if (opt.number || opt.type === 'number') {
  645. self.number(key);
  646. if (opt.alias)
  647. self.number(opt.alias);
  648. }
  649. if (opt.string || opt.type === 'string') {
  650. self.string(key);
  651. if (opt.alias)
  652. self.string(opt.alias);
  653. }
  654. if (opt.count || opt.type === 'count') {
  655. self.count(key);
  656. }
  657. if (typeof opt.global === 'boolean') {
  658. self.global(key, opt.global);
  659. }
  660. if (opt.defaultDescription) {
  661. options.defaultDescription[key] = opt.defaultDescription;
  662. }
  663. if (opt.skipValidation) {
  664. self.skipValidation(key);
  665. }
  666. const desc = opt.describe || opt.description || opt.desc;
  667. self.describe(key, desc);
  668. if (opt.hidden) {
  669. self.hide(key);
  670. }
  671. if (opt.requiresArg) {
  672. self.requiresArg(key);
  673. }
  674. }
  675. return self;
  676. };
  677. self.getOptions = () => options;
  678. self.positional = function (key, opts) {
  679. argsert('<string> <object>', [key, opts], arguments.length);
  680. if (context.resets === 0) {
  681. throw new YError(".positional() can only be called in a command's builder function");
  682. }
  683. const supportedOpts = [
  684. 'default',
  685. 'defaultDescription',
  686. 'implies',
  687. 'normalize',
  688. 'choices',
  689. 'conflicts',
  690. 'coerce',
  691. 'type',
  692. 'describe',
  693. 'desc',
  694. 'description',
  695. 'alias',
  696. ];
  697. opts = objFilter(opts, (k, v) => {
  698. let accept = supportedOpts.indexOf(k) !== -1;
  699. if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1)
  700. accept = false;
  701. return accept;
  702. });
  703. const fullCommand = context.fullCommands[context.fullCommands.length - 1];
  704. const parseOptions = fullCommand
  705. ? command.cmdToParseOptions(fullCommand)
  706. : {
  707. array: [],
  708. alias: {},
  709. default: {},
  710. demand: {},
  711. };
  712. objectKeys(parseOptions).forEach(pk => {
  713. const parseOption = parseOptions[pk];
  714. if (Array.isArray(parseOption)) {
  715. if (parseOption.indexOf(key) !== -1)
  716. opts[pk] = true;
  717. }
  718. else {
  719. if (parseOption[key] && !(pk in opts))
  720. opts[pk] = parseOption[key];
  721. }
  722. });
  723. self.group(key, usage.getPositionalGroupName());
  724. return self.option(key, opts);
  725. };
  726. self.group = function group(opts, groupName) {
  727. argsert('<string|array> <string>', [opts, groupName], arguments.length);
  728. const existing = preservedGroups[groupName] || groups[groupName];
  729. if (preservedGroups[groupName]) {
  730. delete preservedGroups[groupName];
  731. }
  732. const seen = {};
  733. groups[groupName] = (existing || []).concat(opts).filter(key => {
  734. if (seen[key])
  735. return false;
  736. return (seen[key] = true);
  737. });
  738. return self;
  739. };
  740. self.getGroups = () => Object.assign({}, groups, preservedGroups);
  741. self.env = function (prefix) {
  742. argsert('[string|boolean]', [prefix], arguments.length);
  743. if (prefix === false)
  744. delete options.envPrefix;
  745. else
  746. options.envPrefix = prefix || '';
  747. return self;
  748. };
  749. self.wrap = function (cols) {
  750. argsert('<number|null|undefined>', [cols], arguments.length);
  751. usage.wrap(cols);
  752. return self;
  753. };
  754. let strict = false;
  755. self.strict = function (enabled) {
  756. argsert('[boolean]', [enabled], arguments.length);
  757. strict = enabled !== false;
  758. return self;
  759. };
  760. self.getStrict = () => strict;
  761. let strictCommands = false;
  762. self.strictCommands = function (enabled) {
  763. argsert('[boolean]', [enabled], arguments.length);
  764. strictCommands = enabled !== false;
  765. return self;
  766. };
  767. self.getStrictCommands = () => strictCommands;
  768. let strictOptions = false;
  769. self.strictOptions = function (enabled) {
  770. argsert('[boolean]', [enabled], arguments.length);
  771. strictOptions = enabled !== false;
  772. return self;
  773. };
  774. self.getStrictOptions = () => strictOptions;
  775. let parserConfig = {};
  776. self.parserConfiguration = function parserConfiguration(config) {
  777. argsert('<object>', [config], arguments.length);
  778. parserConfig = config;
  779. return self;
  780. };
  781. self.getParserConfiguration = () => parserConfig;
  782. self.showHelp = function (level) {
  783. argsert('[string|function]', [level], arguments.length);
  784. if (!self.parsed)
  785. self._parseArgs(processArgs);
  786. if (command.hasDefaultCommand()) {
  787. context.resets++;
  788. command.runDefaultBuilderOn(self);
  789. }
  790. usage.showHelp(level);
  791. return self;
  792. };
  793. let versionOpt = null;
  794. self.version = function version(opt, msg, ver) {
  795. const defaultVersionOpt = 'version';
  796. argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
  797. if (versionOpt) {
  798. deleteFromParserHintObject(versionOpt);
  799. usage.version(undefined);
  800. versionOpt = null;
  801. }
  802. if (arguments.length === 0) {
  803. ver = guessVersion();
  804. opt = defaultVersionOpt;
  805. }
  806. else if (arguments.length === 1) {
  807. if (opt === false) {
  808. return self;
  809. }
  810. ver = opt;
  811. opt = defaultVersionOpt;
  812. }
  813. else if (arguments.length === 2) {
  814. ver = msg;
  815. msg = undefined;
  816. }
  817. versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
  818. msg = msg || usage.deferY18nLookup('Show version number');
  819. usage.version(ver || undefined);
  820. self.boolean(versionOpt);
  821. self.describe(versionOpt, msg);
  822. return self;
  823. };
  824. function guessVersion() {
  825. const obj = pkgUp();
  826. return obj.version || 'unknown';
  827. }
  828. let helpOpt = null;
  829. self.addHelpOpt = self.help = function addHelpOpt(opt, msg) {
  830. const defaultHelpOpt = 'help';
  831. argsert('[string|boolean] [string]', [opt, msg], arguments.length);
  832. if (helpOpt) {
  833. deleteFromParserHintObject(helpOpt);
  834. helpOpt = null;
  835. }
  836. if (arguments.length === 1) {
  837. if (opt === false)
  838. return self;
  839. }
  840. helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
  841. self.boolean(helpOpt);
  842. self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'));
  843. return self;
  844. };
  845. const defaultShowHiddenOpt = 'show-hidden';
  846. options.showHiddenOpt = defaultShowHiddenOpt;
  847. self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) {
  848. argsert('[string|boolean] [string]', [opt, msg], arguments.length);
  849. if (arguments.length === 1) {
  850. if (opt === false)
  851. return self;
  852. }
  853. const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt;
  854. self.boolean(showHiddenOpt);
  855. self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options'));
  856. options.showHiddenOpt = showHiddenOpt;
  857. return self;
  858. };
  859. self.hide = function hide(key) {
  860. argsert('<string>', [key], arguments.length);
  861. options.hiddenOptions.push(key);
  862. return self;
  863. };
  864. self.showHelpOnFail = function showHelpOnFail(enabled, message) {
  865. argsert('[boolean|string] [string]', [enabled, message], arguments.length);
  866. usage.showHelpOnFail(enabled, message);
  867. return self;
  868. };
  869. let exitProcess = true;
  870. self.exitProcess = function (enabled = true) {
  871. argsert('[boolean]', [enabled], arguments.length);
  872. exitProcess = enabled;
  873. return self;
  874. };
  875. self.getExitProcess = () => exitProcess;
  876. self.showCompletionScript = function ($0, cmd) {
  877. argsert('[string] [string]', [$0, cmd], arguments.length);
  878. $0 = $0 || self.$0;
  879. _logger.log(completion.generateCompletionScript($0, cmd || completionCommand || 'completion'));
  880. return self;
  881. };
  882. self.getCompletion = function (args, done) {
  883. argsert('<array> <function>', [args, done], arguments.length);
  884. completion.getCompletion(args, done);
  885. };
  886. self.locale = function (locale) {
  887. argsert('[string]', [locale], arguments.length);
  888. if (!locale) {
  889. guessLocale();
  890. return y18n.getLocale();
  891. }
  892. detectLocale = false;
  893. y18n.setLocale(locale);
  894. return self;
  895. };
  896. self.updateStrings = self.updateLocale = function (obj) {
  897. argsert('<object>', [obj], arguments.length);
  898. detectLocale = false;
  899. y18n.updateLocale(obj);
  900. return self;
  901. };
  902. let detectLocale = true;
  903. self.detectLocale = function (detect) {
  904. argsert('<boolean>', [detect], arguments.length);
  905. detectLocale = detect;
  906. return self;
  907. };
  908. self.getDetectLocale = () => detectLocale;
  909. const _logger = {
  910. log(...args) {
  911. if (!self._hasParseCallback())
  912. console.log(...args);
  913. hasOutput = true;
  914. if (output.length)
  915. output += '\n';
  916. output += args.join(' ');
  917. },
  918. error(...args) {
  919. if (!self._hasParseCallback())
  920. console.error(...args);
  921. hasOutput = true;
  922. if (output.length)
  923. output += '\n';
  924. output += args.join(' ');
  925. },
  926. };
  927. self._getLoggerInstance = () => _logger;
  928. self._hasOutput = () => hasOutput;
  929. self._setHasOutput = () => {
  930. hasOutput = true;
  931. };
  932. let recommendCommands;
  933. self.recommendCommands = function (recommend = true) {
  934. argsert('[boolean]', [recommend], arguments.length);
  935. recommendCommands = recommend;
  936. return self;
  937. };
  938. self.getUsageInstance = () => usage;
  939. self.getValidationInstance = () => validation;
  940. self.getCommandInstance = () => command;
  941. self.terminalWidth = () => {
  942. argsert([], 0);
  943. return shim.process.stdColumns;
  944. };
  945. Object.defineProperty(self, 'argv', {
  946. get: () => self._parseArgs(processArgs),
  947. enumerable: true,
  948. });
  949. self._parseArgs = function parseArgs(args, shortCircuit, _calledFromCommand, commandIndex) {
  950. let skipValidation = !!_calledFromCommand;
  951. args = args || processArgs;
  952. options.__ = y18n.__;
  953. options.configuration = self.getParserConfiguration();
  954. const populateDoubleDash = !!options.configuration['populate--'];
  955. const config = Object.assign({}, options.configuration, {
  956. 'populate--': true,
  957. });
  958. const parsed = shim.Parser.detailed(args, Object.assign({}, options, {
  959. configuration: Object.assign({ 'parse-positional-numbers': false }, config),
  960. }));
  961. let argv = parsed.argv;
  962. if (parseContext)
  963. argv = Object.assign({}, argv, parseContext);
  964. const aliases = parsed.aliases;
  965. argv.$0 = self.$0;
  966. self.parsed = parsed;
  967. try {
  968. guessLocale();
  969. if (shortCircuit) {
  970. return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
  971. }
  972. if (helpOpt) {
  973. const helpCmds = [helpOpt]
  974. .concat(aliases[helpOpt] || [])
  975. .filter(k => k.length > 1);
  976. if (~helpCmds.indexOf('' + argv._[argv._.length - 1])) {
  977. argv._.pop();
  978. argv[helpOpt] = true;
  979. }
  980. }
  981. const handlerKeys = command.getCommands();
  982. const requestCompletions = completion.completionKey in argv;
  983. const skipRecommendation = argv[helpOpt] || requestCompletions;
  984. const skipDefaultCommand = skipRecommendation &&
  985. (handlerKeys.length > 1 || handlerKeys[0] !== '$0');
  986. if (argv._.length) {
  987. if (handlerKeys.length) {
  988. let firstUnknownCommand;
  989. for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
  990. cmd = String(argv._[i]);
  991. if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
  992. const innerArgv = command.runCommand(cmd, self, parsed, i + 1);
  993. return self._postProcess(innerArgv, populateDoubleDash);
  994. }
  995. else if (!firstUnknownCommand && cmd !== completionCommand) {
  996. firstUnknownCommand = cmd;
  997. break;
  998. }
  999. }
  1000. if (command.hasDefaultCommand() && !skipDefaultCommand) {
  1001. const innerArgv = command.runCommand(null, self, parsed);
  1002. return self._postProcess(innerArgv, populateDoubleDash);
  1003. }
  1004. if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
  1005. validation.recommendCommands(firstUnknownCommand, handlerKeys);
  1006. }
  1007. }
  1008. if (completionCommand &&
  1009. ~argv._.indexOf(completionCommand) &&
  1010. !requestCompletions) {
  1011. if (exitProcess)
  1012. setBlocking(true);
  1013. self.showCompletionScript();
  1014. self.exit(0);
  1015. }
  1016. }
  1017. else if (command.hasDefaultCommand() && !skipDefaultCommand) {
  1018. const innerArgv = command.runCommand(null, self, parsed);
  1019. return self._postProcess(innerArgv, populateDoubleDash);
  1020. }
  1021. if (requestCompletions) {
  1022. if (exitProcess)
  1023. setBlocking(true);
  1024. args = [].concat(args);
  1025. const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1);
  1026. completion.getCompletion(completionArgs, completions => {
  1027. (completions || []).forEach(completion => {
  1028. _logger.log(completion);
  1029. });
  1030. self.exit(0);
  1031. });
  1032. return self._postProcess(argv, !populateDoubleDash, _calledFromCommand);
  1033. }
  1034. if (!hasOutput) {
  1035. Object.keys(argv).forEach(key => {
  1036. if (key === helpOpt && argv[key]) {
  1037. if (exitProcess)
  1038. setBlocking(true);
  1039. skipValidation = true;
  1040. self.showHelp('log');
  1041. self.exit(0);
  1042. }
  1043. else if (key === versionOpt && argv[key]) {
  1044. if (exitProcess)
  1045. setBlocking(true);
  1046. skipValidation = true;
  1047. usage.showVersion();
  1048. self.exit(0);
  1049. }
  1050. });
  1051. }
  1052. if (!skipValidation && options.skipValidation.length > 0) {
  1053. skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true);
  1054. }
  1055. if (!skipValidation) {
  1056. if (parsed.error)
  1057. throw new YError(parsed.error.message);
  1058. if (!requestCompletions) {
  1059. self._runValidation(argv, aliases, {}, parsed.error);
  1060. }
  1061. }
  1062. }
  1063. catch (err) {
  1064. if (err instanceof YError)
  1065. usage.fail(err.message, err);
  1066. else
  1067. throw err;
  1068. }
  1069. return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
  1070. };
  1071. self._postProcess = function (argv, populateDoubleDash, calledFromCommand = false) {
  1072. if (isPromise(argv))
  1073. return argv;
  1074. if (calledFromCommand)
  1075. return argv;
  1076. if (!populateDoubleDash) {
  1077. argv = self._copyDoubleDash(argv);
  1078. }
  1079. const parsePositionalNumbers = self.getParserConfiguration()['parse-positional-numbers'] ||
  1080. self.getParserConfiguration()['parse-positional-numbers'] === undefined;
  1081. if (parsePositionalNumbers) {
  1082. argv = self._parsePositionalNumbers(argv);
  1083. }
  1084. return argv;
  1085. };
  1086. self._copyDoubleDash = function (argv) {
  1087. if (!argv._ || !argv['--'])
  1088. return argv;
  1089. argv._.push.apply(argv._, argv['--']);
  1090. try {
  1091. delete argv['--'];
  1092. }
  1093. catch (_err) { }
  1094. return argv;
  1095. };
  1096. self._parsePositionalNumbers = function (argv) {
  1097. const args = argv['--'] ? argv['--'] : argv._;
  1098. for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
  1099. if (shim.Parser.looksLikeNumber(arg) &&
  1100. Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
  1101. args[i] = Number(arg);
  1102. }
  1103. }
  1104. return argv;
  1105. };
  1106. self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors, isDefaultCommand = false) {
  1107. if (parseErrors)
  1108. throw new YError(parseErrors.message);
  1109. validation.nonOptionCount(argv);
  1110. validation.requiredArguments(argv);
  1111. let failedStrictCommands = false;
  1112. if (strictCommands) {
  1113. failedStrictCommands = validation.unknownCommands(argv);
  1114. }
  1115. if (strict && !failedStrictCommands) {
  1116. validation.unknownArguments(argv, aliases, positionalMap, isDefaultCommand);
  1117. }
  1118. else if (strictOptions) {
  1119. validation.unknownArguments(argv, aliases, {}, false, false);
  1120. }
  1121. validation.customChecks(argv, aliases);
  1122. validation.limitedChoices(argv);
  1123. validation.implications(argv);
  1124. validation.conflicting(argv);
  1125. };
  1126. function guessLocale() {
  1127. if (!detectLocale)
  1128. return;
  1129. const locale = shim.getEnv('LC_ALL') ||
  1130. shim.getEnv('LC_MESSAGES') ||
  1131. shim.getEnv('LANG') ||
  1132. shim.getEnv('LANGUAGE') ||
  1133. 'en_US';
  1134. self.locale(locale.replace(/[.:].*/, ''));
  1135. }
  1136. self.help();
  1137. self.version();
  1138. return self;
  1139. }
  1140. export const rebase = (base, dir) => shim.path.relative(base, dir);
  1141. export function isYargsInstance(y) {
  1142. return !!y && typeof y._parseArgs === 'function';
  1143. }