Skip to content

Commit d73e8ad

Browse files
chore: cleanup version invocation, argParser (#1865)
* chore: cleanup version group, invoke only once * fix: tests * fix: tests * fix: tests * chore: fix typo Co-authored-by: James George <[email protected]>
1 parent 305c188 commit d73e8ad

File tree

9 files changed

+91
-91
lines changed

9 files changed

+91
-91
lines changed

packages/info/src/options.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,10 @@ export default [
55
type: String,
66
description: 'To get the output in specified format (accept json or markdown)',
77
},
8+
{
9+
name: 'version',
10+
usage: '--version',
11+
type: Boolean,
12+
description: 'Display the version of the package',
13+
},
814
];

packages/webpack-cli/__tests__/arg-parser.test.js

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -357,12 +357,6 @@ describe('arg-parser', () => {
357357
expect(helpCb.mock.calls[0][0]).toEqual(['--help']);
358358
});
359359

360-
it('calls version callback on --version', () => {
361-
const versionCb = jest.fn();
362-
argParser(helpAndVersionOptions, ['--version'], true, '', () => {}, versionCb);
363-
expect(versionCb.mock.calls.length).toEqual(1);
364-
});
365-
366360
it('parses webpack args', () => {
367361
const res = argParser(core, ['--entry', 'test.js', '--hot', '-o', './dist/', '--stats'], true);
368362
expect(res.unknownArgs.length).toEqual(0);

packages/webpack-cli/lib/bootstrap.js

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
const { options } = require('colorette');
22
const WebpackCLI = require('./webpack-cli');
3-
const { core, commands } = require('./utils/cli-flags');
3+
const { core } = require('./utils/cli-flags');
4+
const versionRunner = require('./groups/runVersion');
45
const logger = require('./utils/logger');
6+
const { isCommandUsed } = require('./utils/arg-utils');
57
const cliExecuter = require('./utils/cli-executer');
68
const argParser = require('./utils/arg-parser');
79
require('./utils/process-log');
@@ -10,27 +12,20 @@ process.title = 'webpack-cli';
1012
// Create a new instance of the CLI object
1113
const cli = new WebpackCLI();
1214

13-
const isCommandUsed = (args) =>
14-
commands.find((cmd) => {
15-
return args.includes(cmd.name) || args.includes(cmd.alias);
16-
});
17-
1815
async function runCLI(cliArgs) {
1916
let args;
2017

2118
const commandIsUsed = isCommandUsed(cliArgs);
22-
const runVersion = () => {
23-
cli.runVersion(cliArgs, commandIsUsed);
24-
};
25-
const parsedArgs = argParser(core, cliArgs, true, process.title, cli.runHelp, runVersion, commands);
26-
27-
if (parsedArgs.unknownArgs.includes('help')) {
19+
const parsedArgs = argParser(core, cliArgs, true, process.title, cli.runHelp);
20+
if (parsedArgs.unknownArgs.includes('help') || parsedArgs.opts.help) {
21+
options.enabled = !cliArgs.includes('--no-color');
2822
cli.runHelp(cliArgs);
2923
process.exit(0);
3024
}
3125

32-
if (parsedArgs.unknownArgs.includes('version')) {
33-
runVersion();
26+
if (parsedArgs.unknownArgs.includes('version') || parsedArgs.opts.version) {
27+
options.enabled = !cliArgs.includes('--no-color');
28+
versionRunner(cliArgs, commandIsUsed);
3429
process.exit(0);
3530
}
3631

packages/webpack-cli/lib/groups/HelpGroup.js

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const { yellow, bold, underline } = require('colorette');
22
const { core, commands } = require('../utils/cli-flags');
3-
const { defaultCommands } = require('../utils/commands');
43
const logger = require('../utils/logger');
54
const commandLineUsage = require('command-line-usage');
65

@@ -46,40 +45,6 @@ class HelpGroup {
4645
logger.raw('\n Made with ♥️ by the webpack team');
4746
}
4847

49-
outputVersion(externalPkg, commandsUsed, invalidArgs) {
50-
if (externalPkg && commandsUsed.length === 1 && invalidArgs.length === 0) {
51-
try {
52-
if ([externalPkg.alias, externalPkg.name].some((pkg) => commandsUsed.includes(pkg))) {
53-
const { name, version } = require(`@webpack-cli/${defaultCommands[externalPkg.name]}/package.json`);
54-
logger.raw(`\n${name} ${version}`);
55-
} else {
56-
const { name, version } = require(`${externalPkg.name}/package.json`);
57-
logger.raw(`\n${name} ${version}`);
58-
}
59-
} catch (e) {
60-
logger.error('Error: External package not found.');
61-
process.exit(2);
62-
}
63-
}
64-
65-
if (commandsUsed.length > 1) {
66-
logger.error('You provided multiple commands. Please use only one command at a time.\n');
67-
process.exit(2);
68-
}
69-
70-
if (invalidArgs.length > 0) {
71-
const argType = invalidArgs[0].startsWith('-') ? 'option' : 'command';
72-
logger.error(`Error: Invalid ${argType} '${invalidArgs[0]}'.`);
73-
logger.info('Run webpack --help to see available commands and arguments.\n');
74-
process.exit(2);
75-
}
76-
77-
const pkgJSON = require('../../package.json');
78-
const webpack = require('webpack');
79-
logger.raw(`\nwebpack-cli ${pkgJSON.version}`);
80-
logger.raw(`\nwebpack ${webpack.version}\n`);
81-
}
82-
8348
run() {
8449
const o = (s) => yellow(s);
8550
const options = require('../utils/cli-flags');
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const logger = require('../utils/logger');
2+
const { defaultCommands } = require('../utils/commands');
3+
const { isCommandUsed } = require('../utils/arg-utils');
4+
const { commands, allNames, hasUnknownArgs } = require('../utils/unknown-args');
5+
6+
const outputVersion = (args) => {
7+
// This is used to throw err when there are multiple command along with version
8+
const commandsUsed = args.filter((val) => commands.includes(val));
9+
10+
// The command with which version is invoked
11+
const commandUsed = isCommandUsed(args);
12+
const invalidArgs = hasUnknownArgs(args, ...allNames);
13+
if (commandsUsed && commandsUsed.length === 1 && invalidArgs.length === 0) {
14+
try {
15+
if ([commandUsed.alias, commandUsed.name].some((pkg) => commandsUsed.includes(pkg))) {
16+
const { name, version } = require(`@webpack-cli/${defaultCommands[commandUsed.name]}/package.json`);
17+
logger.raw(`\n${name} ${version}`);
18+
} else {
19+
const { name, version } = require(`${commandUsed.name}/package.json`);
20+
logger.raw(`\n${name} ${version}`);
21+
}
22+
} catch (e) {
23+
logger.error('Error: External package not found.');
24+
process.exit(2);
25+
}
26+
}
27+
28+
if (commandsUsed.length > 1) {
29+
logger.error('You provided multiple commands. Please use only one command at a time.\n');
30+
process.exit(2);
31+
}
32+
33+
if (invalidArgs.length > 0) {
34+
const argType = invalidArgs[0].startsWith('-') ? 'option' : 'command';
35+
logger.error(`Error: Invalid ${argType} '${invalidArgs[0]}'.`);
36+
logger.info('Run webpack --help to see available commands and arguments.\n');
37+
process.exit(2);
38+
}
39+
40+
const pkgJSON = require('../../package.json');
41+
const webpack = require('webpack');
42+
logger.raw(`\nwebpack-cli ${pkgJSON.version}`);
43+
logger.raw(`\nwebpack ${webpack.version}\n`);
44+
};
45+
46+
module.exports = outputVersion;

packages/webpack-cli/lib/utils/arg-parser.js

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const commander = require('commander');
22
const logger = require('./logger');
3-
3+
const { commands } = require('./cli-flags');
44
const { defaultCommands } = require('./commands');
55

66
/**
@@ -12,38 +12,28 @@ const { defaultCommands } = require('./commands');
1212
* @param {boolean} argsOnly false if all of process.argv has been provided, true if
1313
* args is only a subset of process.argv that removes the first couple elements
1414
*/
15-
function argParser(options, args, argsOnly = false, name = '', helpFunction = undefined, versionFunction = undefined, commands) {
15+
function argParser(options, args, argsOnly = false, name = '', helpFunction) {
1616
const parser = new commander.Command();
1717
// Set parser name
1818
parser.name(name);
1919
parser.storeOptionsAsProperties(false);
2020

21-
if (commands) {
22-
commands.reduce((parserInstance, cmd) => {
23-
parser
24-
.command(cmd.name)
25-
.alias(cmd.alias)
26-
.description(cmd.description)
27-
.usage(cmd.usage)
28-
.allowUnknownOption(true)
29-
.action(async () => {
30-
const cliArgs = args.slice(args.indexOf(cmd.name) + 1 || args.indexOf(cmd.alias) + 1);
31-
return await require('../commands/ExternalCommand').run(defaultCommands[cmd.name], ...cliArgs);
32-
});
33-
return parser;
34-
}, parser);
35-
36-
// Prevent default behavior
37-
parser.on('command:*', () => {});
38-
}
21+
commands.reduce((parserInstance, cmd) => {
22+
parser
23+
.command(cmd.name)
24+
.alias(cmd.alias)
25+
.description(cmd.description)
26+
.usage(cmd.usage)
27+
.allowUnknownOption(true)
28+
.action(async () => {
29+
const cliArgs = args.slice(args.indexOf(cmd.name) + 1 || args.indexOf(cmd.alias) + 1);
30+
return await require('../commands/ExternalCommand').run(defaultCommands[cmd.name], ...cliArgs);
31+
});
32+
return parser;
33+
}, parser);
3934

40-
// Use customized version output if available
41-
if (versionFunction) {
42-
parser.on('option:version', () => {
43-
versionFunction();
44-
process.exit(0);
45-
});
46-
}
35+
// Prevent default behavior
36+
parser.on('command:*', () => {});
4737

4838
// Use customized help output if available
4939
if (helpFunction) {

packages/webpack-cli/lib/utils/arg-utils.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const { commands } = require('./cli-flags');
2+
13
function hyphenToUpperCase(name) {
24
if (!name) {
35
return name;
@@ -18,6 +20,12 @@ function arrayToObject(arr) {
1820
}, {});
1921
}
2022

23+
const isCommandUsed = (args) =>
24+
commands.find((cmd) => {
25+
return args.includes(cmd.name) || args.includes(cmd.alias);
26+
});
27+
2128
module.exports = {
2229
arrayToObject,
30+
isCommandUsed,
2331
};

packages/webpack-cli/lib/utils/cli-flags.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ const commands = [
5353
type: String,
5454
description: 'To get the output in specified format ( accept json or markdown )',
5555
},
56+
{
57+
name: 'version',
58+
type: Boolean,
59+
description: 'Print version information of info package',
60+
},
5661
],
5762
},
5863
{

packages/webpack-cli/lib/webpack-cli.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -235,15 +235,6 @@ class WebpackCLI extends GroupHelper {
235235
options.enabled = !args.includes('--no-color');
236236
return new HelpGroup().outputHelp(isCommand, subject, invalidArgs);
237237
}
238-
239-
runVersion(args, externalPkg) {
240-
const HelpGroup = require('./groups/HelpGroup');
241-
const { commands, allNames, hasUnknownArgs } = require('./utils/unknown-args');
242-
const commandsUsed = args.filter((val) => commands.includes(val));
243-
const invalidArgs = hasUnknownArgs(args, ...allNames);
244-
options.enabled = !args.includes('--no-color');
245-
return new HelpGroup().outputVersion(externalPkg, commandsUsed, invalidArgs);
246-
}
247238
}
248239

249240
module.exports = WebpackCLI;

0 commit comments

Comments
 (0)