usage.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import { objFilter } from './utils/obj-filter.js';
  2. import { YError } from './yerror.js';
  3. import setBlocking from './utils/set-blocking.js';
  4. function isBoolean(fail) {
  5. return typeof fail === 'boolean';
  6. }
  7. export function usage(yargs, shim) {
  8. const __ = shim.y18n.__;
  9. const self = {};
  10. const fails = [];
  11. self.failFn = function failFn(f) {
  12. fails.push(f);
  13. };
  14. let failMessage = null;
  15. let globalFailMessage = null;
  16. let showHelpOnFail = true;
  17. self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
  18. const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
  19. if (yargs.getInternalMethods().isGlobalContext()) {
  20. globalFailMessage = message;
  21. }
  22. failMessage = message;
  23. showHelpOnFail = enabled;
  24. return self;
  25. };
  26. let failureOutput = false;
  27. self.fail = function fail(msg, err) {
  28. const logger = yargs.getInternalMethods().getLoggerInstance();
  29. if (fails.length) {
  30. for (let i = fails.length - 1; i >= 0; --i) {
  31. const fail = fails[i];
  32. if (isBoolean(fail)) {
  33. if (err)
  34. throw err;
  35. else if (msg)
  36. throw Error(msg);
  37. }
  38. else {
  39. fail(msg, err, self);
  40. }
  41. }
  42. }
  43. else {
  44. if (yargs.getExitProcess())
  45. setBlocking(true);
  46. if (!failureOutput) {
  47. failureOutput = true;
  48. if (showHelpOnFail) {
  49. yargs.showHelp('error');
  50. logger.error();
  51. }
  52. if (msg || err)
  53. logger.error(msg || err);
  54. const globalOrCommandFailMessage = failMessage || globalFailMessage;
  55. if (globalOrCommandFailMessage) {
  56. if (msg || err)
  57. logger.error('');
  58. logger.error(globalOrCommandFailMessage);
  59. }
  60. }
  61. err = err || new YError(msg);
  62. if (yargs.getExitProcess()) {
  63. return yargs.exit(1);
  64. }
  65. else if (yargs.getInternalMethods().hasParseCallback()) {
  66. return yargs.exit(1, err);
  67. }
  68. else {
  69. throw err;
  70. }
  71. }
  72. };
  73. let usages = [];
  74. let usageDisabled = false;
  75. self.usage = (msg, description) => {
  76. if (msg === null) {
  77. usageDisabled = true;
  78. usages = [];
  79. return self;
  80. }
  81. usageDisabled = false;
  82. usages.push([msg, description || '']);
  83. return self;
  84. };
  85. self.getUsage = () => {
  86. return usages;
  87. };
  88. self.getUsageDisabled = () => {
  89. return usageDisabled;
  90. };
  91. self.getPositionalGroupName = () => {
  92. return __('Positionals:');
  93. };
  94. let examples = [];
  95. self.example = (cmd, description) => {
  96. examples.push([cmd, description || '']);
  97. };
  98. let commands = [];
  99. self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
  100. if (isDefault) {
  101. commands = commands.map(cmdArray => {
  102. cmdArray[2] = false;
  103. return cmdArray;
  104. });
  105. }
  106. commands.push([cmd, description || '', isDefault, aliases, deprecated]);
  107. };
  108. self.getCommands = () => commands;
  109. let descriptions = {};
  110. self.describe = function describe(keyOrKeys, desc) {
  111. if (Array.isArray(keyOrKeys)) {
  112. keyOrKeys.forEach(k => {
  113. self.describe(k, desc);
  114. });
  115. }
  116. else if (typeof keyOrKeys === 'object') {
  117. Object.keys(keyOrKeys).forEach(k => {
  118. self.describe(k, keyOrKeys[k]);
  119. });
  120. }
  121. else {
  122. descriptions[keyOrKeys] = desc;
  123. }
  124. };
  125. self.getDescriptions = () => descriptions;
  126. let epilogs = [];
  127. self.epilog = msg => {
  128. epilogs.push(msg);
  129. };
  130. let wrapSet = false;
  131. let wrap;
  132. self.wrap = cols => {
  133. wrapSet = true;
  134. wrap = cols;
  135. };
  136. self.getWrap = () => {
  137. if (shim.getEnv('YARGS_DISABLE_WRAP')) {
  138. return null;
  139. }
  140. if (!wrapSet) {
  141. wrap = windowWidth();
  142. wrapSet = true;
  143. }
  144. return wrap;
  145. };
  146. const deferY18nLookupPrefix = '__yargsString__:';
  147. self.deferY18nLookup = str => deferY18nLookupPrefix + str;
  148. self.help = function help() {
  149. if (cachedHelpMessage)
  150. return cachedHelpMessage;
  151. normalizeAliases();
  152. const base$0 = yargs.customScriptName
  153. ? yargs.$0
  154. : shim.path.basename(yargs.$0);
  155. const demandedOptions = yargs.getDemandedOptions();
  156. const demandedCommands = yargs.getDemandedCommands();
  157. const deprecatedOptions = yargs.getDeprecatedOptions();
  158. const groups = yargs.getGroups();
  159. const options = yargs.getOptions();
  160. let keys = [];
  161. keys = keys.concat(Object.keys(descriptions));
  162. keys = keys.concat(Object.keys(demandedOptions));
  163. keys = keys.concat(Object.keys(demandedCommands));
  164. keys = keys.concat(Object.keys(options.default));
  165. keys = keys.filter(filterHiddenOptions);
  166. keys = Object.keys(keys.reduce((acc, key) => {
  167. if (key !== '_')
  168. acc[key] = true;
  169. return acc;
  170. }, {}));
  171. const theWrap = self.getWrap();
  172. const ui = shim.cliui({
  173. width: theWrap,
  174. wrap: !!theWrap,
  175. });
  176. if (!usageDisabled) {
  177. if (usages.length) {
  178. usages.forEach(usage => {
  179. ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` });
  180. if (usage[1]) {
  181. ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
  182. }
  183. });
  184. ui.div();
  185. }
  186. else if (commands.length) {
  187. let u = null;
  188. if (demandedCommands._) {
  189. u = `${base$0} <${__('command')}>\n`;
  190. }
  191. else {
  192. u = `${base$0} [${__('command')}]\n`;
  193. }
  194. ui.div(`${u}`);
  195. }
  196. }
  197. if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
  198. ui.div(__('Commands:'));
  199. const context = yargs.getInternalMethods().getContext();
  200. const parentCommands = context.commands.length
  201. ? `${context.commands.join(' ')} `
  202. : '';
  203. if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
  204. true) {
  205. commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
  206. }
  207. const prefix = base$0 ? `${base$0} ` : '';
  208. commands.forEach(command => {
  209. const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
  210. ui.span({
  211. text: commandString,
  212. padding: [0, 2, 0, 2],
  213. width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
  214. }, { text: command[1] });
  215. const hints = [];
  216. if (command[2])
  217. hints.push(`[${__('default')}]`);
  218. if (command[3] && command[3].length) {
  219. hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
  220. }
  221. if (command[4]) {
  222. if (typeof command[4] === 'string') {
  223. hints.push(`[${__('deprecated: %s', command[4])}]`);
  224. }
  225. else {
  226. hints.push(`[${__('deprecated')}]`);
  227. }
  228. }
  229. if (hints.length) {
  230. ui.div({
  231. text: hints.join(' '),
  232. padding: [0, 0, 0, 2],
  233. align: 'right',
  234. });
  235. }
  236. else {
  237. ui.div();
  238. }
  239. });
  240. ui.div();
  241. }
  242. const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
  243. keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
  244. aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
  245. const defaultGroup = __('Options:');
  246. if (!groups[defaultGroup])
  247. groups[defaultGroup] = [];
  248. addUngroupedKeys(keys, options.alias, groups, defaultGroup);
  249. const isLongSwitch = (sw) => /^--/.test(getText(sw));
  250. const displayedGroups = Object.keys(groups)
  251. .filter(groupName => groups[groupName].length > 0)
  252. .map(groupName => {
  253. const normalizedKeys = groups[groupName]
  254. .filter(filterHiddenOptions)
  255. .map(key => {
  256. if (aliasKeys.includes(key))
  257. return key;
  258. for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
  259. if ((options.alias[aliasKey] || []).includes(key))
  260. return aliasKey;
  261. }
  262. return key;
  263. });
  264. return { groupName, normalizedKeys };
  265. })
  266. .filter(({ normalizedKeys }) => normalizedKeys.length > 0)
  267. .map(({ groupName, normalizedKeys }) => {
  268. const switches = normalizedKeys.reduce((acc, key) => {
  269. acc[key] = [key]
  270. .concat(options.alias[key] || [])
  271. .map(sw => {
  272. if (groupName === self.getPositionalGroupName())
  273. return sw;
  274. else {
  275. return ((/^[0-9]$/.test(sw)
  276. ? options.boolean.includes(key)
  277. ? '-'
  278. : '--'
  279. : sw.length > 1
  280. ? '--'
  281. : '-') + sw);
  282. }
  283. })
  284. .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
  285. ? 0
  286. : isLongSwitch(sw1)
  287. ? 1
  288. : -1)
  289. .join(', ');
  290. return acc;
  291. }, {});
  292. return { groupName, normalizedKeys, switches };
  293. });
  294. const shortSwitchesUsed = displayedGroups
  295. .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
  296. .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
  297. if (shortSwitchesUsed) {
  298. displayedGroups
  299. .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
  300. .forEach(({ normalizedKeys, switches }) => {
  301. normalizedKeys.forEach(key => {
  302. if (isLongSwitch(switches[key])) {
  303. switches[key] = addIndentation(switches[key], '-x, '.length);
  304. }
  305. });
  306. });
  307. }
  308. displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
  309. ui.div(groupName);
  310. normalizedKeys.forEach(key => {
  311. const kswitch = switches[key];
  312. let desc = descriptions[key] || '';
  313. let type = null;
  314. if (desc.includes(deferY18nLookupPrefix))
  315. desc = __(desc.substring(deferY18nLookupPrefix.length));
  316. if (options.boolean.includes(key))
  317. type = `[${__('boolean')}]`;
  318. if (options.count.includes(key))
  319. type = `[${__('count')}]`;
  320. if (options.string.includes(key))
  321. type = `[${__('string')}]`;
  322. if (options.normalize.includes(key))
  323. type = `[${__('string')}]`;
  324. if (options.array.includes(key))
  325. type = `[${__('array')}]`;
  326. if (options.number.includes(key))
  327. type = `[${__('number')}]`;
  328. const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
  329. ? `[${__('deprecated: %s', deprecated)}]`
  330. : `[${__('deprecated')}]`;
  331. const extra = [
  332. key in deprecatedOptions
  333. ? deprecatedExtra(deprecatedOptions[key])
  334. : null,
  335. type,
  336. key in demandedOptions ? `[${__('required')}]` : null,
  337. options.choices && options.choices[key]
  338. ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
  339. : null,
  340. defaultString(options.default[key], options.defaultDescription[key]),
  341. ]
  342. .filter(Boolean)
  343. .join(' ');
  344. ui.span({
  345. text: getText(kswitch),
  346. padding: [0, 2, 0, 2 + getIndentation(kswitch)],
  347. width: maxWidth(switches, theWrap) + 4,
  348. }, desc);
  349. const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
  350. true;
  351. if (extra && !shouldHideOptionExtras)
  352. ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
  353. else
  354. ui.div();
  355. });
  356. ui.div();
  357. });
  358. if (examples.length) {
  359. ui.div(__('Examples:'));
  360. examples.forEach(example => {
  361. example[0] = example[0].replace(/\$0/g, base$0);
  362. });
  363. examples.forEach(example => {
  364. if (example[1] === '') {
  365. ui.div({
  366. text: example[0],
  367. padding: [0, 2, 0, 2],
  368. });
  369. }
  370. else {
  371. ui.div({
  372. text: example[0],
  373. padding: [0, 2, 0, 2],
  374. width: maxWidth(examples, theWrap) + 4,
  375. }, {
  376. text: example[1],
  377. });
  378. }
  379. });
  380. ui.div();
  381. }
  382. if (epilogs.length > 0) {
  383. const e = epilogs
  384. .map(epilog => epilog.replace(/\$0/g, base$0))
  385. .join('\n');
  386. ui.div(`${e}\n`);
  387. }
  388. return ui.toString().replace(/\s*$/, '');
  389. };
  390. function maxWidth(table, theWrap, modifier) {
  391. let width = 0;
  392. if (!Array.isArray(table)) {
  393. table = Object.values(table).map(v => [v]);
  394. }
  395. table.forEach(v => {
  396. width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
  397. });
  398. if (theWrap)
  399. width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
  400. return width;
  401. }
  402. function normalizeAliases() {
  403. const demandedOptions = yargs.getDemandedOptions();
  404. const options = yargs.getOptions();
  405. (Object.keys(options.alias) || []).forEach(key => {
  406. options.alias[key].forEach(alias => {
  407. if (descriptions[alias])
  408. self.describe(key, descriptions[alias]);
  409. if (alias in demandedOptions)
  410. yargs.demandOption(key, demandedOptions[alias]);
  411. if (options.boolean.includes(alias))
  412. yargs.boolean(key);
  413. if (options.count.includes(alias))
  414. yargs.count(key);
  415. if (options.string.includes(alias))
  416. yargs.string(key);
  417. if (options.normalize.includes(alias))
  418. yargs.normalize(key);
  419. if (options.array.includes(alias))
  420. yargs.array(key);
  421. if (options.number.includes(alias))
  422. yargs.number(key);
  423. });
  424. });
  425. }
  426. let cachedHelpMessage;
  427. self.cacheHelpMessage = function () {
  428. cachedHelpMessage = this.help();
  429. };
  430. self.clearCachedHelpMessage = function () {
  431. cachedHelpMessage = undefined;
  432. };
  433. self.hasCachedHelpMessage = function () {
  434. return !!cachedHelpMessage;
  435. };
  436. function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
  437. let groupedKeys = [];
  438. let toCheck = null;
  439. Object.keys(groups).forEach(group => {
  440. groupedKeys = groupedKeys.concat(groups[group]);
  441. });
  442. keys.forEach(key => {
  443. toCheck = [key].concat(aliases[key]);
  444. if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
  445. groups[defaultGroup].push(key);
  446. }
  447. });
  448. return groupedKeys;
  449. }
  450. function filterHiddenOptions(key) {
  451. return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
  452. yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
  453. }
  454. self.showHelp = (level) => {
  455. const logger = yargs.getInternalMethods().getLoggerInstance();
  456. if (!level)
  457. level = 'error';
  458. const emit = typeof level === 'function' ? level : logger[level];
  459. emit(self.help());
  460. };
  461. self.functionDescription = fn => {
  462. const description = fn.name
  463. ? shim.Parser.decamelize(fn.name, '-')
  464. : __('generated-value');
  465. return ['(', description, ')'].join('');
  466. };
  467. self.stringifiedValues = function stringifiedValues(values, separator) {
  468. let string = '';
  469. const sep = separator || ', ';
  470. const array = [].concat(values);
  471. if (!values || !array.length)
  472. return string;
  473. array.forEach(value => {
  474. if (string.length)
  475. string += sep;
  476. string += JSON.stringify(value);
  477. });
  478. return string;
  479. };
  480. function defaultString(value, defaultDescription) {
  481. let string = `[${__('default:')} `;
  482. if (value === undefined && !defaultDescription)
  483. return null;
  484. if (defaultDescription) {
  485. string += defaultDescription;
  486. }
  487. else {
  488. switch (typeof value) {
  489. case 'string':
  490. string += `"${value}"`;
  491. break;
  492. case 'object':
  493. string += JSON.stringify(value);
  494. break;
  495. default:
  496. string += value;
  497. }
  498. }
  499. return `${string}]`;
  500. }
  501. function windowWidth() {
  502. const maxWidth = 80;
  503. if (shim.process.stdColumns) {
  504. return Math.min(maxWidth, shim.process.stdColumns);
  505. }
  506. else {
  507. return maxWidth;
  508. }
  509. }
  510. let version = null;
  511. self.version = ver => {
  512. version = ver;
  513. };
  514. self.showVersion = level => {
  515. const logger = yargs.getInternalMethods().getLoggerInstance();
  516. if (!level)
  517. level = 'error';
  518. const emit = typeof level === 'function' ? level : logger[level];
  519. emit(version);
  520. };
  521. self.reset = function reset(localLookup) {
  522. failMessage = null;
  523. failureOutput = false;
  524. usages = [];
  525. usageDisabled = false;
  526. epilogs = [];
  527. examples = [];
  528. commands = [];
  529. descriptions = objFilter(descriptions, k => !localLookup[k]);
  530. return self;
  531. };
  532. const frozens = [];
  533. self.freeze = function freeze() {
  534. frozens.push({
  535. failMessage,
  536. failureOutput,
  537. usages,
  538. usageDisabled,
  539. epilogs,
  540. examples,
  541. commands,
  542. descriptions,
  543. });
  544. };
  545. self.unfreeze = function unfreeze(defaultCommand = false) {
  546. const frozen = frozens.pop();
  547. if (!frozen)
  548. return;
  549. if (defaultCommand) {
  550. descriptions = { ...frozen.descriptions, ...descriptions };
  551. commands = [...frozen.commands, ...commands];
  552. usages = [...frozen.usages, ...usages];
  553. examples = [...frozen.examples, ...examples];
  554. epilogs = [...frozen.epilogs, ...epilogs];
  555. }
  556. else {
  557. ({
  558. failMessage,
  559. failureOutput,
  560. usages,
  561. usageDisabled,
  562. epilogs,
  563. examples,
  564. commands,
  565. descriptions,
  566. } = frozen);
  567. }
  568. };
  569. return self;
  570. }
  571. function isIndentedText(text) {
  572. return typeof text === 'object';
  573. }
  574. function addIndentation(text, indent) {
  575. return isIndentedText(text)
  576. ? { text: text.text, indentation: text.indentation + indent }
  577. : { text, indentation: indent };
  578. }
  579. function getIndentation(text) {
  580. return isIndentedText(text) ? text.indentation : 0;
  581. }
  582. function getText(text) {
  583. return isIndentedText(text) ? text.text : text;
  584. }