Skip to content

Commit

Permalink
feat: suggest the closest match based on the Levenshtein distance alg…
Browse files Browse the repository at this point in the history
…orithm (#2010)

* feat: suggest the closest match for an unknown flag

* tests: add test case for flag suggestion

* tests: assert for exit code
  • Loading branch information
jamesgeorge007 committed Nov 2, 2020
1 parent 07d18b0 commit 491a582
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/webpack-cli/lib/bootstrap.js
Expand Up @@ -3,6 +3,7 @@ const { core } = require('./utils/cli-flags');
const logger = require('./utils/logger');
const { isCommandUsed } = require('./utils/arg-utils');
const argParser = require('./utils/arg-parser');
const leven = require('leven');

process.title = 'webpack-cli';

Expand Down Expand Up @@ -39,6 +40,11 @@ const runCLI = async (cliArgs) => {
if (parsedArgs.unknownArgs.length > 0) {
parsedArgs.unknownArgs.forEach(async (unknown) => {
logger.error(`Unknown argument: ${unknown}`);
const strippedFlag = unknown.substr(2);
const { name: suggestion } = core.find((flag) => leven(strippedFlag, flag.name) < 3);
if (suggestion) {
logger.raw(`Did you mean --${suggestion}?`);
}
});

process.exit(2);
Expand Down
1 change: 1 addition & 0 deletions packages/webpack-cli/package.json
Expand Up @@ -37,6 +37,7 @@
"execa": "^4.1.0",
"import-local": "^3.0.2",
"interpret": "^2.2.0",
"leven": "^3.1.0",
"rechoir": "^0.7.0",
"v8-compile-cache": "^2.2.0",
"webpack-merge": "^4.2.2"
Expand Down
9 changes: 8 additions & 1 deletion test/unknown/unknown.test.js
Expand Up @@ -2,8 +2,15 @@ const { run } = require('../utils/test-utils');

describe('unknown behaviour', () => {
it('warns the user if an unknown flag is passed in', () => {
const { stderr } = run(__dirname, ['--unknown']);
const { stderr, exitCode } = run(__dirname, ['--unknown']);
expect(stderr).toBeTruthy();
expect(stderr).toContain('Unknown argument: --unknown');
expect(exitCode).toBe(2);
});
it('suggests the closest match to an unknown flag', () => {
const { stderr, stdout, exitCode } = run(__dirname, ['--entyr', './a.js']);
expect(stderr).toContain('Unknown argument: --entyr');
expect(stdout).toContain('Did you mean --entry?');
expect(exitCode).toBe(2);
});
});

0 comments on commit 491a582

Please sign in to comment.