-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (63 loc) · 2.16 KB
/
index.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
const { spawn } = require('child_process');
const NAME = 'ShellScriptPlugin';
class ShellScriptPlugin {
constructor (hooks = {}) {
this._hooks = hooks;
this._process = {};
}
apply (compiler) {
this.watch = compiler.watch;
Object.keys(this._hooks).forEach(name => {
if (!compiler.hooks[name]) {
this._handlerError(`The hook [${name}] is not exist in webpack compiler`);
} else {
compiler.hooks[name].tap(NAME, () => {
this._hooks[name].forEach(script => this._runScript(script));
});
}
});
}
_parseScrpit (script) {
if (typeof script === 'string') {
const [command, ...args] = script.split(' ');
return { command, args };
}
const [command, ...args] = script;
return { command, args };
}
_killProcess (key) {
this._process[key].kill();
}
_runScript (script) {
const key = typeof script === 'string' ? script : JSON.stringify(script);
if (this._process[key]) this._killProcess(key);
const { command, args } = this._parseScrpit(script);
this._process[key] = spawn(command, args, { stdio: 'pipe' });
this._process[key].on('error', this._onScriptError.bind(this, key));
this._process[key].stderr.on('data', this._onScriptError.bind(this, key));
this._process[key].on('exit', this._onScriptComplete.bind(this, key));
}
_log (msg) {
msg = `\n[${NAME}] ${msg}\n`;
console.log(msg);
}
_handlerError (msg) {
msg = `\n[${NAME}] ${msg}\n`;
if (!this.watch) {
throw Error(msg);
}
console.error(msg);
}
_onScriptError (script, error) {
this._handlerError(`Running Script ${script} Error: ${error}`);
}
_onScriptComplete (key, error, msg) {
this._process[key] = null;
if (msg === 'SIGTERM' || msg === 'SIGINT') {
this._log(`Killing script: ${key}\n`);
} else if (!error) {
this._log(`Completed script: ${key}\n`);
}
}
}
module.exports = ShellScriptPlugin;