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