forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bsb
executable file
·493 lines (448 loc) · 14.1 KB
/
bsb
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!/usr/bin/env node
//@ts-check
"use strict";
/* This script is supposed to be running in project root directory
* It matters since we need read .sourcedirs(location)
* and its content are file/directories with regard to project root
*/
var child_process = require('child_process')
var os = require('os');
var path = require('path')
var bsconfig = 'bsconfig.json'
var bsb_exe = path.join(__dirname,process.platform,'bsb.exe')
var LAST_SUCCESS_BUILD_STAMP = 0
process.env.BSB_PROJECT_ROOT=process.cwd()
// console.log('BSB_PROJECT_ROOT:', process.env.BSB_PROJECT_ROOT)
// All clients of type MiniWebSocket
/**
* @type {any[]}
*/
var wsClients = []
var watch_mode = false
var verbose = false
/**
* @type {string | undefined}
*/
var postBuild = undefined
var useWebSocket = false
var webSocketHost = 'localhost'
var webSocketPort = 9999
/**
* @returns {string}
*/
function getDateAsString(){
var n = new Date()
return n.getHours() + ":" + n.getMinutes() + ":" + n.getSeconds()
}
/**
* @time{[number,number]}
*/
var startTime
function updateStartTime(){
startTime = process.hrtime()
return ''
}
function updateFinishTime(){
var diff = process.hrtime(startTime)
return diff[0] * 1e9 + diff[1]
}
/**
*
* @param {*} str
*/
function dlog(str){
if(verbose){
console.log(str)
}
}
function notifyClients() {
wsClients = wsClients.filter(x => !x.closed && !x.socket.destroyed )
var wsClientsLen = wsClients.length
dlog(`Alive sockets number: ${wsClientsLen}`)
var data = JSON.stringify(
{
LAST_SUCCESS_BUILD_STAMP: LAST_SUCCESS_BUILD_STAMP
}
)
for (var i = 0; i < wsClientsLen; ++ i ) {
// in reverse order, the last pushed get notified earlier
var client = wsClients[wsClientsLen - i - 1]
if (!client.closed) {
client.sendText(data)
}
}
}
function setUpWebSocket() {
var WebSocket = require('./lib/minisocket.js').MiniWebSocket
var id = setInterval(notifyClients, 3000)
require('http').createServer()
.on('upgrade', function (req, socket, upgradeHead) {
dlog("connection opened");
var ws = new WebSocket(req, socket, upgradeHead);
socket.on("error",function (err){
dlog(`Socket Error ${err}`)
})
wsClients.push(ws)
})
.on('error', function (err) {
// @ts-ignore
if(err !== undefined && err.code === "EADDRINUSE" ){
var error = std_is_tty?`\x1b[1;31mERROR:\x1b[0m` : `ERROR:`
console.error(`${error} The websocket port number ${webSocketPort} is in use.
Please pick a different one using the \`-ws [host:]port\` flag from bsb.`)
} else {
console.error(err)
}
process.exit(2)
})
.listen(webSocketPort, webSocketHost);
}
/**
* @type {string[]}
*/
var delegate_args = []
var process_argv = process.argv
for (var i = 2; i < process_argv.length; ++i) {
var current = process_argv[i]
if (current === '-build-success') {
// TODO boundary safety check
// Not really needed
postBuild = process_argv[++i]
} else if (current === "-ws") {
var hostAndPortNumber = (process_argv[++i] || '').split(':');
/**
* @type {number}
*/
var portNumber;
if (hostAndPortNumber.length === 1) {
portNumber = parseInt(hostAndPortNumber[0])
} else {
webSocketHost = hostAndPortNumber[0]
portNumber = parseInt(hostAndPortNumber[1])
}
if (!isNaN (portNumber)) {
webSocketPort = portNumber
}
dlog(`WebSocket host & port number: ${webSocketHost}:${webSocketPort}`)
useWebSocket = true
} else {
delegate_args.push(current)
if (current === '-w') {
watch_mode = true
} else if (current === "-verbose") {
verbose = true
}
}
}
if(
process.env.NINJA_ANSI_FORCED === undefined
){
if(require ('tty').isatty(1)){
process.env.NINJA_ANSI_FORCED = '1'
}
} else {
dlog(`NINJA_ANSI_FORCED: "${process.env.NINJA_ANSI_FORCED}"`)
}
// Note the watch mode flag `-w` is not very useful to bsb.exe
// A trick is played that for such flags `bsb.exe -make-world -w`
// it will exit ignoreing `-make-world` since it will be triggered
// again in bsb
// The following process atm only spawned `bsb.exe` directly
try {
child_process.execFileSync(bsb_exe, delegate_args, { stdio: 'inherit' })
} catch (e) {
if (e.code === "ENOENT") {
// when bsb is actually not found
console.error(String(e))
process.exit(2)
}
if (!watch_mode) {
process.exit(2)
}
}
if (watch_mode) {
var fs = require('fs')
var path = require('path')
if (useWebSocket) {
setUpWebSocket()
}
// for column one based error message
var cwd = process.cwd()
var lockFileName = path.join(cwd, ".bsb.lock")
/**
* @type {[string,string][]}
*/
var reasons_to_rebuild = [];
/**
* watchers are held so that we close it later
*/
var watchers = [];
function onUncaughtException(err){
console.error("Uncaught Exception", err)
process.exit(1)
}
function onExit() {
try {
fs.unlinkSync(lockFileName)
} catch (err) {
process.exitCode = 1
}
}
function exitProcess() {
process.exit(0)
}
/**
* @return {boolean}
*/
function acquireLockFile() {
try {
// We use [~perm:0o664] rather than our usual default perms, [0o666], because
// lock files shouldn't rely on the umask to disallow tampering by other.
var fd = fs.openSync(lockFileName, 'wx', 0o664)
try {
fs.writeFileSync(fd, String(process.pid), 'ascii')
fs.closeSync(fd)
} catch (err) {
}
process.on('exit', onExit)
process.on('uncaughtException', onUncaughtException)
// OS signal handlers
// Ctrl+C
process.on('SIGINT', exitProcess)
// kill pid
process.on('SIGUSR1', exitProcess)
process.on('SIGUSR2', exitProcess)
process.on('SIGTERM', exitProcess)
process.on('SIGHUP', exitProcess)
process.stdin.on('close', exitProcess)
// close when stdin stops
if (os.platform() !== "win32") {
process.stdin.on('end', exitProcess)
process.stdin.resume()
}
return true
} catch (exn) {
return false
}
}
var is_building = false;
function releaseBuild() {
is_building = false
}
function acquireBuild() {
if (is_building) {
return false
}
else {
is_building = true
return true
}
}
var sourcedirs = path.join('lib', 'bs', '.sourcedirs.json')
var watch_generated = []
function watch_build(watch_config) {
var watch_files = watch_config.dirs
watch_generated = watch_config.generated
// close and remove all unused watchers
watchers = watchers.filter(function (watcher) {
if (watcher.dir === bsconfig) {
return true;
} else if (watch_files.indexOf(watcher.dir) < 0) {
dlog(`${watcher.dir} is no longer watched`);
watcher.watcher.close();
return false
} else {
return true;
}
})
// adding new watchers
for (var i = 0; i < watch_files.length; ++i) {
var dir = watch_files[i]
if (!watchers.find(function (watcher) { return watcher.dir === dir })) {
dlog(`watching dir ${dir} now`)
var watcher = fs.watch(dir, on_change);
watchers.push({ dir: dir, watcher: watcher })
} else {
// console.log(dir, 'already watched')
}
}
};
/**
*
* @param {string} eventType
* @param {string} fileName
*/
function validEvent(eventType, fileName) {
// Return true if filename is nil, filename is only provided on Linux, macOS, Windows, and AIX.
// On other systems, we just have to assume that any change is valid.
// This could cause problems if source builds (generating js files in the same directory) are supported.
if (!fileName)
return true;
return !(fileName === '.merlin' ||
fileName.endsWith('.js') ||
fileName.endsWith('.gen.tsx') ||
watch_generated.indexOf(fileName) >= 0 ||
fileName.endsWith('.swp')
)
}
/**
* @return {boolean}
*/
function needRebuild() {
return reasons_to_rebuild.length != 0
}
var error_is_tty = process.stderr.isTTY
var std_is_tty = process.stdout.isTTY
function logFinish(code) {
if (std_is_tty) {
if (code === 0) {
console.log("\x1b[36m>>>> Finish compiling\x1b[0m", Math.floor(updateFinishTime()/1e6),"mseconds")
} else {
console.log("\x1b[1;31m>>>> Finish compiling(exit: " + code + ")\x1b[0m")
}
} else {
if (code === 0) {
console.log(">>>> Finish compiling")
} else {
console.log(">>>> Finish compiling(exit: " + code + ")")
}
}
}
function logStart() {
if (std_is_tty) {
console.log("\x1b[36m>>>> Start compiling\x1b[0m",updateStartTime());
} else {
console.log(">>>> Start compiling");
}
}
/**
*
* @param code {number}
* @param signal {string}
*/
function build_finished_callback(code, signal) {
if(code === 0){
LAST_SUCCESS_BUILD_STAMP = + new Date() ;
notifyClients()
if(postBuild){
dlog(`running postbuild command: ${postBuild}`)
child_process.exec(postBuild)
}
}
logFinish(code)
releaseBuild()
if (needRebuild()) {
build()
} else {
var files = getWatchFiles(sourcedirs);
watch_build(files)
}
}
/**
* TODO: how to make it captured by vscode
* @param output {string}
* @param highlight {string}
*/
function error_output(output, highlight) {
if (error_is_tty && highlight) {
process.stderr.write(output.replace(highlight, '\x1b[1;31m' + highlight + '\x1b[0m'))
} else {
process.stderr.write(output)
}
}
// Note this function filters the error output
// it relies on the fact that ninja will merege stdout and stderr
// of the compiler output, if it does not
// then we should have a way to not filter the compiler output
function build() {
if (acquireBuild()) {
logStart()
if (reasons_to_rebuild.length === 0) {
dlog("Rebuilding since just got started")
} else {
dlog(`Rebuilding since ${reasons_to_rebuild}`)
}
reasons_to_rebuild = [];
var p = child_process
.spawn(bsb_exe, [], { stdio: ['inherit', 'inherit', 'pipe'] });
p.on('exit', build_finished_callback)
p.stderr
.setEncoding('utf8')
// @ts-ignore
.on('data', function (s) { error_output(s, 'ninja: error') })
}
}
/**
*
* @param {string} event
* @param {string} reason
*/
function on_change(event, reason) {
if (validEvent(event, reason)) {
dlog(`Event ${event} ${reason}`);
reasons_to_rebuild.push([event, reason])
// Some editors are using temporary files to store edits.
// This results in two sync change events: change + rename and two sync builds.
// Using setImmediate will ensure that only one build done.
setImmediate(() => {
if (needRebuild()) {
if (process.env.BS_WATCH_CLEAR && console.clear) {console.clear()}
build()
}
})
}
}
function getWatchFiles(file) {
if (fs.existsSync(file)) {
return JSON.parse(fs.readFileSync(file, 'utf8'))
} else {
return { dirs: [], generated: [] }
}
}
/**
*
* @param potential_pid {number}
*/
function existPid(potential_pid) {
try {
return process.kill(potential_pid, 0)
} catch (err) {
return false
}
}
// Initialization and get locker file
while (true) {
if (acquireLockFile()) {
break;
} else {
var potential_pid;
try {
var content = fs.readFileSync(lockFileName, 'ascii')
potential_pid = parseInt(content)
} catch (err) {
// ignore
}
var validPid = potential_pid !== undefined && !isNaN(potential_pid)
if (validPid && !existPid(potential_pid)) {
console.log('Stale file detected : ', lockFileName)
try {
fs.unlinkSync(lockFileName)
} catch (err) {
}
console.log('Retry:')
continue;
} else {
error_output('Error: could not acquire lockfile', 'Error')
console.error(' ' + lockFileName)
console.log('Could be another process running in the background',
'\nEither kill that process or delete the staled lock')
if (validPid) {
console.error('Try run command: ', '`kill ', potential_pid, ' || rm -f .bsb.lock`')
}
process.exit(2)
}
}
}
watchers.push({ watcher: fs.watch(bsconfig, on_change), dir: bsconfig });
build()
}