UNPKG

2.43 kBJavaScriptView Raw
1const { readFileSync: read, writeFileSync: write } = require('fs');
2const { join } = require('path');
3
4const chalk = require('chalk');
5
6const pkg = require('../../package.json');
7
8const Command = require('./Command');
9
10class TeachCommandError extends Command.CommandError {
11 constructor(...args) {
12 super(...args);
13 this.name = 'TeachCommandError';
14 }
15}
16
17module.exports = class TeachCommand extends Command {
18 help() {
19 return chalk`
20 {blue teach} v${pkg.version}
21
22 Teaches webpack-command that a command has been installed and is available.
23
24 {underline Usage}
25 $ webpack teach --command <command> --module <module>
26
27 {underline Options}
28 --command The name of a command that users will type
29 --forget Instructs the tool to forget a previously added command
30 --module The npm module name of a command
31
32 {underline Examples}
33 $ webpack teach --command init --module webpack-command-init
34 $ webpack teach --command init --forget
35`;
36 }
37
38 run(cli) {
39 const { flags } = cli;
40 const { command, forget, module: commandModule } = flags;
41 const dataPath = join(__dirname, '../../data/commands.json');
42 const dataFile = read(dataPath, 'utf-8');
43 const commands = JSON.parse(dataFile);
44 const format = () => JSON.stringify(commands, Object.keys(commands).sort(), 2);
45
46 if (!command) {
47 throw new TeachCommandError('The --command flag is required.');
48 }
49
50 if (typeof command !== 'string') {
51 throw new TeachCommandError('The value of --command must be a String.');
52 }
53
54 if (forget) {
55 delete commands[command];
56 write(dataPath, format(), 'utf-8');
57 return;
58 }
59
60 if (!commandModule) {
61 throw new TeachCommandError('The --module flag is required.');
62 }
63
64 if (typeof commandModule !== 'string') {
65 throw new TeachCommandError('The value of --module must be a String.');
66 }
67
68 if (commands[command]) {
69 throw new TeachCommandError(
70 `The '${command}' command was already added via ${commands[command]}. Use \`webpack teach --command ${command} --forget\` and try again.`
71 );
72 }
73
74 try {
75 // eslint-disable-next-line global-require, import/no-dynamic-require
76 require(commandModule);
77 } catch (e) {
78 throw new TeachCommandError(`The command module '${commandModule}' was not found.`);
79 }
80
81 commands[command] = commandModule;
82
83 write(dataPath, format(), 'utf-8');
84 }
85};