usage.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. if (extra)
  350. ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
  351. else
  352. ui.div();
  353. });
  354. ui.div();
  355. });
  356. if (examples.length) {
  357. ui.div(__('Examples:'));
  358. examples.forEach(example => {
  359. example[0] = example[0].replace(/\$0/g, base$0);
  360. });
  361. examples.forEach(example => {
  362. if (example[1] === '') {
  363. ui.div({
  364. text: example[0],
  365. padding: [0, 2, 0, 2],
  366. });
  367. }
  368. else {
  369. ui.div({
  370. text: example[0],
  371. padding: [0, 2, 0, 2],
  372. width: maxWidth(examples, theWrap) + 4,
  373. }, {
  374. text: example[1],
  375. });
  376. }
  377. });
  378. ui.div();
  379. }
  380. if (epilogs.length > 0) {
  381. const e = epilogs
  382. .map(epilog => epilog.replace(/\$0/g, base$0))
  383. .join('\n');
  384. ui.div(`${e}\n`);
  385. }
  386. return ui.toString().replace(/\s*$/, '');
  387. };
  388. function maxWidth(table, theWrap, modifier) {
  389. let width = 0;
  390. if (!Array.isArray(table)) {
  391. table = Object.values(table).map(v => [v]);
  392. }
  393. table.forEach(v => {
  394. width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
  395. });
  396. if (theWrap)
  397. width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
  398. return width;
  399. }
  400. function normalizeAliases() {
  401. const demandedOptions = yargs.getDemandedOptions();
  402. const options = yargs.getOptions();
  403. (Object.keys(options.alias) || []).forEach(key => {
  404. options.alias[key].forEach(alias => {
  405. if (descriptions[alias])
  406. self.describe(key, descriptions[alias]);
  407. if (alias in demandedOptions)
  408. yargs.demandOption(key, demandedOptions[alias]);
  409. if (options.boolean.includes(alias))
  410. yargs.boolean(key);
  411. if (options.count.includes(alias))
  412. yargs.count(key);
  413. if (options.string.includes(alias))
  414. yargs.string(key);
  415. if (options.normalize.includes(alias))
  416. yargs.normalize(key);
  417. if (options.array.includes(alias))
  418. yargs.array(key);
  419. if (options.number.includes(alias))
  420. yargs.number(key);
  421. });
  422. });
  423. }
  424. let cachedHelpMessage;
  425. self.cacheHelpMessage = function () {
  426. cachedHelpMessage = this.help();
  427. };
  428. self.clearCachedHelpMessage = function () {
  429. cachedHelpMessage = undefined;
  430. };
  431. self.hasCachedHelpMessage = function () {
  432. return !!cachedHelpMessage;
  433. };
  434. function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
  435. let groupedKeys = [];
  436. let toCheck = null;
  437. Object.keys(groups).forEach(group => {
  438. groupedKeys = groupedKeys.concat(groups[group]);
  439. });
  440. keys.forEach(key => {
  441. toCheck = [key].concat(aliases[key]);
  442. if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
  443. groups[defaultGroup].push(key);
  444. }
  445. });
  446. return groupedKeys;
  447. }
  448. function filterHiddenOptions(key) {
  449. return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
  450. yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
  451. }
  452. self.showHelp = (level) => {
  453. const logger = yargs.getInternalMethods().getLoggerInstance();
  454. if (!level)
  455. level = 'error';
  456. const emit = typeof level === 'function' ? level : logger[level];
  457. emit(self.help());
  458. };
  459. self.functionDescription = fn => {
  460. const description = fn.name
  461. ? shim.Parser.decamelize(fn.name, '-')
  462. : __('generated-value');
  463. return ['(', description, ')'].join('');
  464. };
  465. self.stringifiedValues = function stringifiedValues(values, separator) {
  466. let string = '';
  467. const sep = separator || ', ';
  468. const array = [].concat(values);
  469. if (!values || !array.length)
  470. return string;
  471. array.forEach(value => {
  472. if (string.length)
  473. string += sep;
  474. string += JSON.stringify(value);
  475. });
  476. return string;
  477. };
  478. function defaultString(value, defaultDescription) {
  479. let string = `[${__('default:')} `;
  480. if (value === undefined && !defaultDescription)
  481. return null;
  482. if (defaultDescription) {
  483. string += defaultDescription;
  484. }
  485. else {
  486. switch (typeof value) {
  487. case 'string':
  488. string += `"${value}"`;
  489. break;
  490. case 'object':
  491. string += JSON.stringify(value);
  492. break;
  493. default:
  494. string += value;
  495. }
  496. }
  497. return `${string}]`;
  498. }
  499. function windowWidth() {
  500. const maxWidth = 80;
  501. if (shim.process.stdColumns) {
  502. return Math.min(maxWidth, shim.process.stdColumns);
  503. }
  504. else {
  505. return maxWidth;
  506. }
  507. }
  508. let version = null;
  509. self.version = ver => {
  510. version = ver;
  511. };
  512. self.showVersion = level => {
  513. const logger = yargs.getInternalMethods().getLoggerInstance();
  514. if (!level)
  515. level = 'error';
  516. const emit = typeof level === 'function' ? level : logger[level];
  517. emit(version);
  518. };
  519. self.reset = function reset(localLookup) {
  520. failMessage = null;
  521. failureOutput = false;
  522. usages = [];
  523. usageDisabled = false;
  524. epilogs = [];
  525. examples = [];
  526. commands = [];
  527. descriptions = objFilter(descriptions, k => !localLookup[k]);
  528. return self;
  529. };
  530. const frozens = [];
  531. self.freeze = function freeze() {
  532. frozens.push({
  533. failMessage,
  534. failureOutput,
  535. usages,
  536. usageDisabled,
  537. epilogs,
  538. examples,
  539. commands,
  540. descriptions,
  541. });
  542. };
  543. self.unfreeze = function unfreeze(defaultCommand = false) {
  544. const frozen = frozens.pop();
  545. if (!frozen)
  546. return;
  547. if (defaultCommand) {
  548. descriptions = { ...frozen.descriptions, ...descriptions };
  549. commands = [...frozen.commands, ...commands];
  550. usages = [...frozen.usages, ...usages];
  551. examples = [...frozen.examples, ...examples];
  552. epilogs = [...frozen.epilogs, ...epilogs];
  553. }
  554. else {
  555. ({
  556. failMessage,
  557. failureOutput,
  558. usages,
  559. usageDisabled,
  560. epilogs,
  561. examples,
  562. commands,
  563. descriptions,
  564. } = frozen);
  565. }
  566. };
  567. return self;
  568. }
  569. function isIndentedText(text) {
  570. return typeof text === 'object';
  571. }
  572. function addIndentation(text, indent) {
  573. return isIndentedText(text)
  574. ? { text: text.text, indentation: text.indentation + indent }
  575. : { text, indentation: indent };
  576. }
  577. function getIndentation(text) {
  578. return isIndentedText(text) ? text.indentation : 0;
  579. }
  580. function getText(text) {
  581. return isIndentedText(text) ? text.text : text;
  582. }