-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
executable file
·238 lines (185 loc) · 5.14 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env node
const ChildProcess = require('child_process');
const FS = require('fs');
const Path = require('path');
const Chalk = require('chalk');
const NSFW = require('nsfw');
const Tmp = require('tmp');
const {
execArgv,
options: {debounce: debounceDelay, 'node-modules': toIncludeNodeModules},
modulePath,
args,
} = require('./@cli');
const {guessRealPath} = require('./@utils');
const CHANGED_FILE_PRINTING_LIMIT = 10;
const CWD = process.cwd();
let subprocess;
let exited;
let exitedWithError;
console.info(Chalk.yellow('[nodemand] start'));
void up();
process.on('SIGINT', onSignalToExit);
process.on('SIGTERM', onSignalToExit);
process.on('SIGHUP', onSignalToExit);
async function up(pathSet = new Set()) {
const reportedPathSet = new Set();
let restartScheduled = false;
let restartStarted = false;
let restartScheduleDebounceTimer;
const changedPathSet = new Set();
const nsfw = await NSFW(CWD, events => {
for (const event of events) {
let paths;
switch (event.action) {
case NSFW.actions.RENAMED:
paths = [
Path.join(event.directory, event.oldFile),
Path.join(event.newDirectory, event.newFile),
];
break;
default:
paths = [Path.join(event.directory, event.file)];
break;
}
const watchingPaths = [...pathSet, ...reportedPathSet];
for (let path of paths) {
path = guessRealPath(path);
for (const watchingPath of watchingPaths) {
// This handles platform specific stuffs like case sensitivity.
if (Path.relative(path, watchingPath) === '') {
scheduleRestart(path);
break;
}
}
}
}
});
await nsfw.start();
exited = false;
exitedWithError = false;
const reportFilePath = Tmp.tmpNameSync();
subprocess = ChildProcess.fork(modulePath, args, {
stdio: 'inherit',
execArgv: [
...process.execArgv,
'--expose-internals',
...execArgv,
'--require',
Path.join(__dirname, 'injection.js'),
],
env: {
...process.env,
NODEMAND_REPORT_FILE_PATH: reportFilePath,
},
});
subprocess.on('message', message => {
if (!message || typeof message !== 'object') {
return;
}
switch (message.type) {
case 'add-paths': {
addPaths(message.paths, message.initial);
break;
}
}
});
subprocess.on('exit', code => {
exited = true;
if (typeof code === 'number') {
exitedWithError = code !== 0;
console.info(
(exitedWithError ? Chalk.red : Chalk.green)(
`[nodemand] process exited with code ${code}`,
),
);
} else {
console.info(Chalk.cyan('[nodemand] process exited'));
}
if (FS.existsSync(reportFilePath)) {
const paths = JSON.parse(FS.readFileSync(reportFilePath, 'utf8'));
addPaths(paths, false);
FS.unlinkSync(reportFilePath);
}
});
function addPaths(paths, initial) {
if (restartScheduled) {
return;
}
paths = paths.map(path => {
try {
return FS.realpathSync(path);
} catch (error) {
return path;
}
});
paths = paths.filter(
path =>
// Exclude nodemand modules.
Path.relative(__dirname, path).startsWith('..') ||
// Exclude paths outside of CWD.
Path.relative(CWD, path).startsWith('..'),
);
if (!toIncludeNodeModules) {
paths = paths.filter(path => !/[\\/]node_modules[\\/]/.test(path));
}
for (const path of paths) {
reportedPathSet.add(path);
}
if (initial) {
pathSet.clear();
}
}
function scheduleRestart(path) {
if (restartStarted) {
return;
}
if (!restartScheduled) {
restartScheduled = true;
console.info(Chalk.yellow('[nodemand] restart scheduled'));
}
if (!changedPathSet.has(path)) {
changedPathSet.add(path);
const changedCount = changedPathSet.size;
if (changedCount <= CHANGED_FILE_PRINTING_LIMIT) {
console.info(` ${Chalk.dim(path)}`);
} else if (changedCount === CHANGED_FILE_PRINTING_LIMIT + 1) {
console.info(` ${Chalk.dim('...')}`);
}
}
clearTimeout(restartScheduleDebounceTimer);
restartScheduleDebounceTimer = setTimeout(() => {
restart().catch(error => {
console.error(Chalk.red(error.message));
process.exit(1);
});
}, debounceDelay);
}
async function restart() {
restartStarted = true;
await nsfw.stop();
await stopSubprocess();
console.info(Chalk.yellow('[nodemand] restart'));
up(exitedWithError ? reportedPathSet : undefined);
}
}
function onSignalToExit() {
stopSubprocess().then(
() => process.exit(),
error => {
console.error(Chalk.red(error.message));
process.exit(1);
},
);
}
async function stopSubprocess() {
if (exited) {
return;
}
console.info(Chalk.yellow(`[nodemand] killing process ${subprocess.pid}`));
if (!subprocess.kill('SIGTERM')) {
console.error(Chalk.red('Error killing the process'));
process.exit(1);
}
await new Promise(resolve => subprocess.on('exit', resolve));
}