Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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.

checkInvalidCLIOptions.js 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. const _ = require('lodash');
  3. const chalk = require('chalk');
  4. const EOL = require('os').EOL;
  5. const levenshtein = require('fastest-levenshtein');
  6. /**
  7. * @param {{ [key: string]: { alias?: string } }} allowedOptions
  8. * @return {string[]}
  9. */
  10. const buildAllowedOptions = (allowedOptions) => {
  11. let options = Object.keys(allowedOptions);
  12. options = options.reduce((opts, opt) => {
  13. const alias = allowedOptions[opt].alias;
  14. if (alias) {
  15. opts.push(alias);
  16. }
  17. return opts;
  18. }, options);
  19. options.sort();
  20. return options;
  21. };
  22. /**
  23. * @param {string[]} all
  24. * @param {string} invalid
  25. * @return {null|string}
  26. */
  27. const suggest = (all, invalid) => {
  28. const maxThreshold = 10;
  29. for (let threshold = 1; threshold <= maxThreshold; threshold++) {
  30. const suggestion = all.find((option) => levenshtein.distance(option, invalid) <= threshold);
  31. if (suggestion) {
  32. return suggestion;
  33. }
  34. }
  35. return null;
  36. };
  37. /**
  38. * @param {string} opt
  39. * @return {string}
  40. */
  41. const cliOption = (opt) => {
  42. if (opt.length === 1) {
  43. return `"-${opt}"`;
  44. }
  45. return `"--${_.kebabCase(opt)}"`;
  46. };
  47. /**
  48. * @param {string} invalid
  49. * @param {string|null} suggestion
  50. * @return {string}
  51. */
  52. const buildMessageLine = (invalid, suggestion) => {
  53. let line = `Invalid option ${chalk.red(cliOption(invalid))}.`;
  54. if (suggestion) {
  55. line += ` Did you mean ${chalk.cyan(cliOption(suggestion))}?`;
  56. }
  57. return line + EOL;
  58. };
  59. /**
  60. * @param {{ [key: string]: any }} allowedOptions
  61. * @param {{ [key: string]: any }} inputOptions
  62. * @return {string}
  63. */
  64. module.exports = function checkInvalidCLIOptions(allowedOptions, inputOptions) {
  65. const allOptions = buildAllowedOptions(allowedOptions);
  66. return Object.keys(inputOptions)
  67. .filter((opt) => !allOptions.includes(opt))
  68. .map(_.kebabCase)
  69. .reduce((msg, invalid) => {
  70. // NOTE: No suggestion for shortcut options because it's too difficult
  71. const suggestion = invalid.length >= 2 ? suggest(allOptions, invalid) : null;
  72. return msg + buildMessageLine(invalid, suggestion);
  73. }, '');
  74. };