Skip to content

Commit

Permalink
fix: provide useful error on unknown command
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akait authored Dec 31, 2020
1 parent d885426 commit d6380bb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
18 changes: 17 additions & 1 deletion packages/webpack-cli/lib/webpack-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ class WebpackCLI {
},
];

const knownCommands = [bundleCommandOptions, versionCommandOptions, helpCommandOptions, ...externalBuiltInCommandsInfo];
const isKnownCommand = (name) => knownCommands.find((command) => command.name === name || command.alias === name);

const getCommandNameAndOptions = (args) => {
let commandName;
const options = [];
Expand Down Expand Up @@ -687,7 +690,20 @@ class WebpackCLI {
await outputVersion(optionsForVersion, program);
}

await loadCommandByName(commandName, true);
if (isKnownCommand(commandName)) {
await loadCommandByName(commandName, true);
} else {
logger.error(`Unknown command '${commandName}'`);

const found = knownCommands.find((commandOptions) => distance(commandName, commandOptions.name) < 3);

if (found) {
logger.error(`Did you mean '${found.name}' (alias '${found.alias}')?`);
}

logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}

await this.program.parseAsync([commandName, ...options], { from: 'user' });
});
Expand Down
18 changes: 14 additions & 4 deletions test/unknown/unknown.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,22 @@ describe('unknown behaviour', () => {
expect(stdout).toBeFalsy();
});

it('should ask to install command if an unknown command passed', () => {
it('should log error if an unknown command passed', () => {
const { exitCode, stderr, stdout } = run(__dirname, ['qqq'], true, [], { TERM_PROGRAM: false });

expect(exitCode).toBe(0);
expect(stripAnsi(stderr)).toContain("For using this command you need to install: 'qqq' package");
expect(stripAnsi(stderr)).toContain("Would you like to install 'qqq' package? (That will run 'npm install -D qqq')");
expect(exitCode).toBe(2);
expect(stripAnsi(stderr)).toContain("Unknown command 'qqq'");
expect(stripAnsi(stderr)).toContain("Run 'webpack --help' to see available commands and options");
expect(stdout).toBeFalsy();
});

it('should log error and provide suggestion if an unknown command passed', () => {
const { exitCode, stderr, stdout } = run(__dirname, ['server'], true, [], { TERM_PROGRAM: false });

expect(exitCode).toBe(2);
expect(stripAnsi(stderr)).toContain("Unknown command 'server'");
expect(stripAnsi(stderr)).toContain("Did you mean 'serve' (alias 's')?");
expect(stripAnsi(stderr)).toContain("Run 'webpack --help' to see available commands and options");
expect(stdout).toBeFalsy();
});
});

0 comments on commit d6380bb

Please sign in to comment.