GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

548 lines
19 KiB

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