1 | const { readFileSync: read, writeFileSync: write } = require('fs');
|
2 | const { join } = require('path');
|
3 |
|
4 | const chalk = require('chalk');
|
5 |
|
6 | const pkg = require('../../package.json');
|
7 |
|
8 | const Command = require('./Command');
|
9 |
|
10 | class TeachCommandError extends Command.CommandError {
|
11 | constructor(...args) {
|
12 | super(...args);
|
13 | this.name = 'TeachCommandError';
|
14 | }
|
15 | }
|
16 |
|
17 | module.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 = () =>
|
45 | JSON.stringify(commands, Object.keys(commands).sort(), 2);
|
46 |
|
47 | if (!command) {
|
48 | throw new TeachCommandError('The --command flag is required.');
|
49 | }
|
50 |
|
51 | if (typeof command !== 'string') {
|
52 | throw new TeachCommandError('The value of --command must be a String.');
|
53 | }
|
54 |
|
55 | if (forget) {
|
56 | delete commands[command];
|
57 | write(dataPath, format(), 'utf-8');
|
58 | return;
|
59 | }
|
60 |
|
61 | if (!commandModule) {
|
62 | throw new TeachCommandError('The --module flag is required.');
|
63 | }
|
64 |
|
65 | if (typeof commandModule !== 'string') {
|
66 | throw new TeachCommandError('The value of --module must be a String.');
|
67 | }
|
68 |
|
69 | if (commands[command]) {
|
70 | throw new TeachCommandError(
|
71 | `The '${command}' command was already added via ${
|
72 | commands[command]
|
73 | }. Use \`webpack teach --command ${command} --forget\` and try again.`
|
74 | );
|
75 | }
|
76 |
|
77 | try {
|
78 |
|
79 | require(commandModule);
|
80 | } catch (e) {
|
81 | throw new TeachCommandError(
|
82 | `The command module '${commandModule}' was not found.`
|
83 | );
|
84 | }
|
85 |
|
86 | commands[command] = commandModule;
|
87 |
|
88 | write(dataPath, format(), 'utf-8');
|
89 | }
|
90 | };
|