-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
bootstrap.js
91 lines (83 loc) · 3.24 KB
/
bootstrap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const WebpackCLI = require('./webpack-cli');
const { core, commands } = require('./utils/cli-flags');
const cmdArgs = require('command-line-args');
require('./utils/process-log');
const isFlagPresent = (args, flag) => args.find(arg => [flag, `--${flag}`].includes(arg));
const isArgCommandName = (arg, cmd) => arg === cmd.name || arg === cmd.alias;
const stripDashedFlags = (args, cmd) => {
const slicedArgs = args.slice(2);
if (cmd.name === 'serve') {
return slicedArgs.filter(arg => !isArgCommandName(arg, cmd));
}
else {
return slicedArgs.filter(arg => ~arg.indexOf('--') && !isArgCommandName(arg, cmd));
}
};
const isCommandUsed = commands =>
commands.find(cmd => {
return process.argv.includes(cmd.name) || process.argv.includes(cmd.alias);
});
async function runCLI(cli, commandIsUsed) {
let args;
const helpFlagExists = isFlagPresent(process.argv, 'help');
const versionFlagExists = isFlagPresent(process.argv, 'version');
if (helpFlagExists) {
cli.runHelp();
return;
} else if (versionFlagExists) {
cli.runVersion();
return;
}
if (commandIsUsed) {
commandIsUsed.defaultOption = true;
args = stripDashedFlags(process.argv, commandIsUsed);
return await cli.runCommand(commandIsUsed, ...args);
} else {
try {
args = cmdArgs(core, { stopAtFirstUnknown: false, partial: true });
const result = await cli.run(args, core);
if (!result) {
return;
}
} catch (err) {
if (err.name === 'UNKNOWN_VALUE') {
process.cliLogger.error(`Parse Error (unknown argument): ${err.value}`);
return;
}
else if (err.name === 'ALREADY_SET') {
const argsMap = {};
const keysToDelete = [];
process.argv.forEach((arg, idx) => {
const oldMapValue = argsMap[arg];
argsMap[arg] = {
value: process.argv[idx],
type: (arg.charAt(0) === '-' && arg.charAt(1) === '-') ? 'dash' : 'cmd',
pos: idx
}
// Swap idx of overriden value
if (oldMapValue) {
argsMap[arg].pos = oldMapValue.pos;
keysToDelete.push(idx + 1);
}
})
// Filter out the value for the overriden key
const newArgKeys = Object.keys(argsMap).filter(arg => !keysToDelete.includes(argsMap[arg].pos));
process.argv = newArgKeys;
args = cmdArgs(core, { stopAtFirstUnknown: false, partial: true });
const result = await cli.run(args, core);
if (!result) {
return;
}
process.cliLogger.warn(`duplicate flags found, defaulting to last set value`);
} else {
process.cliLogger.error(err);
}
}
}
}
// eslint-disable-next-line space-before-function-paren
(async () => {
const commandIsUsed = isCommandUsed(commands);
const cli = new WebpackCLI();
await runCLI(cli, commandIsUsed);
})();