-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
106 lines (86 loc) · 2.13 KB
/
watch.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const chokidar = require('chokidar');
const cp = require('child_process');
let appProcesses;
const cwd = process.cwd();
const commands = process.argv[2].split(',');
void async function startWatch() {
const reload = reloadAll();
chokidar
.watch(cwd, {
ignoreInitial: true,
ignored: /\.test-cache|node_modules|opencv*/
})
.on('all', reload)
.on('ready', reload)
.on('error', exit);
}();
function createAppProcesses() {
const msg = appProcesses ? 'restarted' : 'started';
appProcesses = new Map;
for (let command of commands) {
const process = cp.exec(`npm run ${ command }`, {
stdio: "inherit"
})
.on('error', onAppProcessError(command))
.on('exit', onAppProcessExit(command));
console.log(`Robot ${ msg } (${ command })`);
appProcesses.set(command, process);
}
}
function exit(err) {
console.log(err);
process.exit(1);
}
async function killAppProcesses() {
if (appProcesses && appProcesses.size) {
return await Promise.all(
[ ...appProcesses.values() ].map(process =>
new Promise(resolve => {
process.on('exit', resolve);
process.kill();
})
)
);
}
}
function onAppProcessError(command) {
return (error) => {
appProcesses.delete(command);
console.error(error);
console.log(`Robot encountered an error (npm run ${ command })`);
};
}
function onAppProcessExit(command) {
return () => {
appProcesses.delete(command);
console.log(`Robot stopped (npm run ${ command })`);
};
}
function reloadAll() {
let reloading = false;
let reloadAgain = false;
const reload = async filepath => {
if (filepath) {
console.log(`Detected change (${ filepath })...`);
} else {
console.log('Initializing watch');
}
if (reloading) {
reloadAgain = true;
} else {
reloading = true;
reloadAgain = false;
await killAppProcesses();
createAppProcesses();
reloading = false;
if (reloadAgain) {
await reload(filepath);
}
}
};
return reload;
}
process.on('unhandledRejection', err => {
console.log(err);
process.exit(1);
});