-
Notifications
You must be signed in to change notification settings - Fork 5
/
autorun
executable file
·639 lines (554 loc) · 19.3 KB
/
autorun
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#!/usr/bin/env node
"use strict"
const fs = require('fs')
const childproc = require('child_process')
const {basename, normalize, dirname} = require('path')
// signals to try, in order, to shut down a process
const killSignals = [
//'SIGINT',
'SIGTERM',
'SIGKILL',
]
// how long to wait for a process to exit after sending a signal before trying the next signal
const killTimeout = 10000 //ms
// terminal ANSI styling
function termStyle(wstream, hint /* :bool|undefined */) {
let ncolors = 0
if (hint === true) {
// use colors regardless of TTY or not
let t = process.env.TERM || ""
ncolors = (
t && ['xterm','screen','vt100'].some(s => t.indexOf(s) != -1) ? (
t.indexOf('256color') != -1 ? 8 : 4
) : 2
)
} else if (hint !== false && wstream.isTTY) {
// unless hint is explicitly false, use colors if stdout is a TTY
ncolors = wstream.getColorDepth()
}
const sfn = (
ncolors >= 8 ? (open16, open256, close) => {
let a = '\x1b[' + open256 + 'm', b = '\x1b[' + close + 'm'
return s => a + s + b
} :
ncolors > 0 ? (open16, open256, close) => {
let a = '\x1b[' + open16 + 'm', b = '\x1b[' + close + 'm'
return s => a + s + b
} :
() => s => s
)
const [ black, red, green, yellow, blue, magenta, cyan, white ] =
Array.apply(null, new Array(8)).map((_, i) => '38;5;' + i )
const [ brightBlack, brightRed, brightGreen, brightYellow, brightBlue,
brightMagenta, brightCyan, brightWhite ] =
Array.apply(null, new Array(16)).map((_, i) => '38;5;' + i ).slice(8)
// const [ brightBlack, brightRed, brightGreen, brightYellow, brightBlue,
// brightMagenta, brightCyan, brightWhite ] = FG.slice(8, 16)
// const FG = Array.apply(null, new Array(256)).map((_, i) => '38;5;' + i )
// const BG = Array.apply(null, new Array(256)).map((_, i) => '48;5;' + i )
// const [ black, red, green, yellow, blue, magenta, cyan, white ] = FG.slice(0, 8)
// const [ brightBlack, brightRed, brightGreen, brightYellow, brightBlue,
// brightMagenta, brightCyan, brightWhite ] = FG.slice(8, 16)
// // standard
// console.log(FG.slice(0, 8).map((s, i) => `\x1b[${s}m((${s}))\x1b[0m`).join(" "))
// console.log(FG.slice(0, 8).map((s, i) => `\x1b[1m\x1b[${s}m((${s}))\x1b[0m`).join(" "))
// // bright
// console.log(FG.slice(8, 16).map((s, i) => `\x1b[${s}m((${s}))\x1b[0m`).join(" "))
// // greyscale black -> white
// console.log(FG.slice(232, 256).map((s, i) => `\x1b[${s}m((${s}))\x1b[0m`).join(" "))
return {
ncolors,
reset: "\x1b[0m",
// name 16c 256c close
// effects
bold : sfn('1', '1', '22'),
italic : sfn('3', '3', '23'),
underline : sfn('4', '4', '24'),
inverse : sfn('7', '7', '27'),
// standard colors
white : sfn('37', brightWhite, '39'),
black : sfn('30', brightBlack, '39'),
red : sfn('31', red, '39'),
green : sfn('32', green, '39'),
blue : sfn('34', blue, '39'),
cyan : sfn('36', cyan, '39'),
magenta : sfn('35', magenta, '39'),
yellow : sfn('33', yellow, '39'),
// extended colors
purple : sfn('35', '38;5;141', '39'),
pink : sfn('35', '38;5;211', '39'),
lightyellow : sfn('93', '38;5;229', '39'),
orange : sfn('33', '38;5;215', '39'),
// greyscale. Goes from black to white
grey5 : sfn('90', '38;5;236', '39'),
grey4 : sfn('90', '38;5;240', '39'),
grey3 : sfn('90', '38;5;244', '39'),
grey : sfn('90', '38;5;244', '39'),
grey2 : sfn('90', '38;5;248', '39'),
grey1 : sfn('90', '38;5;252', '39'),
}
}
const nocolor = process.argv.includes("-no-color")
const yescolor = process.argv.includes("-color")
const outstyle = termStyle(process.stdout, nocolor ? false : yescolor || undefined)
const errstyle = termStyle(process.stderr, nocolor ? false : yescolor || undefined)
function isfile(filename) {
try { return fs.statSync(filename).isFile() } catch (_) { return false }
}
function parseargs(args, defaultOpts) {
let optsEnded = false, m
const opts = defaultOpts ? Object.extend({},defaultOpts) : {}
const re = /^-{1,2}([^=:]+)(?:\s*[=:]\s*(.+)|)$/
let argStartIndex = 0
for (let L = args.length; argStartIndex != L; ++argStartIndex) {
let arg = args[argStartIndex]
if (arg == '--') {
++argStartIndex
break
} else if (arg[0] != '-') {
break
}
let m = re.exec(arg)
opts[m[1]] = m[2] === undefined ? true : m[2]
}
return {opts, args: argStartIndex == 0 ? args : args.slice(argStartIndex)}
}
const runningProcesses = new Set()
const killproc = process.platform == 'win32' ? (proc, sig) => {
// process groups not supported on windows.
process.kill(proc.pid, sig)
} : (proc, sig) => {
// negative pid on most posix OSes means "process group", includes its child processes.
process.kill(-proc.pid, sig)
}
process.on('exit', function (exitCode) {
for (let p of runningProcesses) {
killproc(p, 'SIGKILL')
}
runningProcesses.clear()
process.exitCode = exitCode
})
function shutdown(sig, exitCode) {
process.removeListener('SIGINT', shutdown)
process.removeListener('SIGTERM', shutdown)
process.stdout.write("\n")
process.exitCode = exitCode
if (runningProcesses.size == 0) {
process.exit(0)
} else {
process.exitCode = exitCode
Promise.all(Array.from(runningProcesses).map(p => terminate(p))).then(exitCodes => {
const exitCode = exitCodes.reduce((a, c) => Math.min(Math.max(a, c)), 0)
process.stdout.write("\n")
process.exit(exitCode)
}).catch(err => {
console.error(err.stack || String(err))
process.exit(exitCode || 1)
})
runningProcesses.clear()
}
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
// process state
const NOT_STARTED = 0, RUNNING = 1, EXITED = 2
function terminate(proc) { // :Promise<exitCode:number>
// console.log("\nTERMINATE\n")
if (!proc || proc.state != RUNNING) {
// console.log("\nTERMINATE A\n")
return Promise.resolve(0)
}
return new Promise((resolve, reject) => {
let signalIndex = 0
let killTimer = null
let timeoutReached = false
proc.once('exit', (exitCode) => {
// console.log("\nTERMINATE exit\n")
clearTimeout(killTimer)
if (!timeoutReached) {
// setTimeout(resolve, 1000)
resolve(exitCode)
}
})
let kill = function() {
let sig = killSignals[signalIndex++]
if (sig == undefined) {
timeoutReached = true
// console.log("\nTERMINATE timeout\n")
return reject(new Error(`timeout (${killTimeout})`))
}
// console.log(`\nTERMINATE kill sig=${sig}\n`)
killproc(proc, sig)
// proc.kill(sig)
clearTimeout(killTimer)
killTimer = setTimeout(kill, killTimeout)
}
kill()
proc.unref()
})
}
function spawn(args) { // :Promise<ChildProcess>
return new Promise((resolve, reject) => {
const opts = {
stdio: ['pipe','inherit','inherit'],
shell: true,
detached: true,
}
const proc = childproc.spawn(args[0], args.slice(1), opts)
proc.state = NOT_STARTED
let cleanup = null
proc.stdin.end()
// proc.stdout.on('data', (data) => {
// console.log(`stdout: ${data}`);
// });
// proc.stderr.on('data', (data) => {
// console.error(`stderr: ${data}`);
// });
runningProcesses.add(proc)
let onexit = function() {
proc.state = EXITED
runningProcesses.delete(proc)
if (cleanup) {
process.removeListener('exit', cleanup)
process.removeListener('error', cleanup)
}
}
const checkalive = function() {
if (proc.state == NOT_STARTED) {
if (proc.pid !== undefined) {
proc.state = RUNNING
proc.terminate = terminate.bind(null, proc); // :Promise<void>
cleanup = function() {
// proc.kill('SIGKILL')
}
process.on('exit', cleanup)
process.on('error', cleanup)
resolve(proc)
} else {
process.nextTick(checkalive)
}
}
}
process.nextTick(checkalive)
proc.on('exit', onexit)
const onErr = function(err) {
if (proc.state == NOT_STARTED) {
onexit()
reject(err)
proc.removeListener('error', onErr)
}
}
proc.on('error', onErr)
})
}
function mtime(file) {
try {
const st = fs.statSync(file)
if (st.isFile()) {
return st.mtime.getTime()
}
} catch (_) {}
return 0
}
function main() {
const {opts, args} = parseargs(process.argv.slice(2))
const progname = basename(process.argv[1])
const askedForHelp = opts.h || opts.help
let reactionTime = 100
if (askedForHelp || args.length == 0) {
const desc0 = [
'Automatically spawn and manage processes as file changes.',
], desc1 = [
`Usage: ${progname} [options] <file> ... [-- <cmdpattern>]`
,'options:'
,' -h[elp] Show description and detailed help for this program.'
,' -v[erbose] Print some details to stdout.'
,' -s[top] Exit with an error if <file> disappears from the file system.'
,' -c[lear] Clear terminal screen before (re)starting the command.'
,' -no-clear Disable clear even when stdio are TTYs.'
,' -color Enable stylized output even if stdio is not TTY.'
,' -no-color Disable stylized output even if stdio is TTY.'
,` -r[eact-in]=<msec> React within <msec> to file changes. Defaults to ${reactionTime}.`
,' -no-banner Don\'t print banner to stdout when restarting the command.'
], desc2 = [
''
,'<file> Files to watch for changes'
,''
,'<cmdpattern> Pattern for command to execute, replacing ":" with <file>.'
,' If not specified or if <cmdpattern> does not include a ":"'
,' argument, <file> is executed with <cmdpattern> as arguments.'
,' If you need to pass an argument of value ":", use "\\" which'
,' will be expanded to ":" rather than <file>.'
,''
,'Examples:'
,` ${progname} foo.sh # foo.sh`
,` ${progname} foo.sh vars.sh # foo.sh`
,` ${progname} foo.sh -- : bar # foo.sh bar`
,` ${progname} foo.js -- node --check : # node --check foo.js`
,` ${progname} foo.py -- python : \\\\: a # python foo.py : a`
,''
];
if (askedForHelp) {
console.error(desc0.concat(desc1.concat(desc2)).join('\n'))
process.exit(0)
} else {
console.error(desc1.join('\n') + `\nTry "${progname} -help" for more information`)
process.exit(1)
}
}
const die = function(msg) {
console.error(`${progname}: ${msg}`)
process.exit(1)
}
const verbose = opts.v || opts.verbose
const logverbose = verbose ? console.log.bind(console) : function(){}
const clear = (
// -c, -clear Unconditionally clear
// -no-clear Disable clear
// (unspecified) Clear only if stdout and stderr are TTYs
(opts.c || opts["clear"] || opts["clear-screen"]) ? true :
!opts["no-clear"] && process.stdout.isTTY && process.stderr.isTTY
)
if ('r' in opts || 'react-in' in opts) {
let v = parseInt(opts.r || opts['react-in'])
if (typeof v != 'number' || isNaN(v) || v <= 0) {
die(`invalid -react-in value: ${opts.r || opts['react-in']}`)
}
reactionTime = v
}
const p = args.indexOf('--')
const infiles = p == -1 ? args : args.slice(0, p)
const runargs = p == -1 ? [infiles[0]] : args.slice(p + 1)
if (infiles.length == 0) {
die('no input files')
}
// const filename = args[0]
// const path = normalize(filename)
// const dir = dirname(args[0])
const fileslot = Symbol('fileslot')
// if (!isfile(filename)) {
// console.error(filename, 'is not a file')
// process.exit(1)
// }
// parse command
let fileslotInCmd = true
let cmd = [fileslot]
if (runargs.length > 0) {
cmd = runargs.map(arg => {
return (arg == ':') ? fileslot :
(arg == '\\:') ? ':' :
arg
})
fileslotInCmd = cmd.indexOf(fileslot) != -1
}
function fmtcmd(filename) {
return cmd.map(c =>
c == fileslot ? (filename ? JSON.stringify(filename) : '<file>')
: JSON.stringify(c) ).join(' ')
}
logverbose('<cmdpattern> =', fmtcmd())
const screen = new class {
constructor() {
// Note: \ec is reported to not work on the KDE console Konsole.
// TODO: detect KDE Konsole and use \e[2J instead
// Clear display: "\x1bc"
// Clear Screen: \x1b[{n}J clears the screen
// n=0 clears from cursor until end of screen
// n=1 clears from cursor to beginning of screen
// n=2 clears entire screen
this.clear = clear ? () => { process.stdout.write('\x1bc') } : ()=>{}
const tty = (
process.stdout.isTTY ? process.stdout :
process.stderr.isTTY ? process.stderr :
null
)
this.width = 80
this.height = 40
if (tty) {
const update = () => {
this.width = tty.columns
this.height = tty.rows
}
tty.on("resize", update)
update()
}
}
}
// keepalive prints and immediately erases a line every second to work around issues with
// some terminals like iTerm and SSH connections without keepalive enabled.
// Clear Line: \x1b[{n}K clears the current line
// n=0 clears from cursor to end of line
// n=1 clears from cursor to start of line
// n=2 clears entire line
let keepaliveTimer = null
let keepaliveCounter = 0
const keepalivePing = () => {
process.stdout.write(".\x1b[1D") // "." + move cursor left by 1
let id = keepaliveCounter
setTimeout(() => {
if (keepaliveTimer !== null && id == keepaliveCounter) {
process.stdout.write("\x1b[0K") // clear from cursor until end of line
}
}, 500)
}
const keepaliveStop = () => {
clearInterval(keepaliveTimer)
keepaliveTimer = null
}
const keepaliveStart = process.stdout.isTTY ? () => {
keepaliveCounter++
keepaliveStop()
keepaliveTimer = setInterval(keepalivePing, 1000)
} : ()=>{}
const message = msg => process.stdout.write(outstyle.inverse("> " + msg))
const hline = '━'
let needCR = false
const resetLine = function() {
if (needCR) {
process.stdout.write('\r')
needCR = false
}
}
const printHeaderStarting = function(name) {
if (!fileslotInCmd) { name = cmd.join(' ') }
resetLine()
message(`${name} changed -- restarting...`)
needCR = true
}
const printFooterEnded = function(code) {
resetLine()
message(`exit ${code}`)
needCR = true
}
const printHeaderStarted = function(progFilename, pid) {
// ---------------------------
// | TIME | COMMAND PID |
// ---------------------------
const linestart = "┃ "
const linesep = " ┃ "
const lineend = " ┃"
const cmdoverflow = "..."
let time = (new Date()).toLocaleTimeString()
let command = fileslotInCmd ? progFilename : cmd.join(' ')
let pidsep = " " // space between command and pid
let pidstr = pid.toString()
const timehline = hline.repeat(time.length)
const commandhline = hline.repeat(command.length)
const commandWidth = Math.max(cmdoverflow.length + 1,
screen.width
- time.length
- pidstr.length
- pidsep.length
- linestart.length
- linesep.length
- lineend.length
)
if (commandWidth < command.length) {
command = command.substr(0, commandWidth - cmdoverflow.length) + cmdoverflow
}
const cmdline = command.padEnd(commandWidth, " ")
const line1 = '━'.repeat(time.length)
const line2 = '━'.repeat(cmdline.length + pidsep.length + pidstr.length)
resetLine()
process.stdout.write(outstyle.grey(
'┏━' + line1 + '━┳━' + line2 + '━┓' + "\n" +
linestart + time + linesep + cmdline + pidsep + pidstr + lineend + "\n" +
'┗━' + line1 + '━┻━' + line2 + '━┛' + "\n"
))
}
const onStartProcess = () => {
logverbose('\nonStartProcess')
keepaliveStop()
screen.clear()
}
const onEndProcess = (exitCode, signal) => {
logverbose('\nonEndProcess', {exitCode, signal})
if (signal === null && !opts['no-banner']) {
printFooterEnded(exitCode)
} // else: process was terminated by signal
keepaliveStart()
}
const spawnfile = function(filename) {
onStartProcess()
logverbose('\nspawn', fmtcmd(filename))
const args = cmd.map(c => c == fileslot ? filename : c)
return spawn(args).catch(die).then(proc => {
if (!opts['no-banner']) {
printHeaderStarted(basename(filename), proc.pid)
}
proc.once('exit', (code, signal) => {
onEndProcess(code, signal)
})
return proc
})
}
spawnfile(infiles[0]).then(proc => {
let isRestarting = false
const restart = function(name, path) {
// (re)start process
if (isRestarting) {
return
}
isRestarting = true
setTimeout(() => {
proc.terminate().catch(die).then(() => {
isRestarting = false
if (!opts['no-banner']) {
printHeaderStarting(name)
}
return spawnfile(path).then(p => (proc = p))
})
}, reactionTime)
}
var watchers = new Map()
function stopWatching(filename) {
let watcher = watchers.get(filename)
if (watcher) {
watcher.close()
}
}
function startWatching(filename, isPrimaryInfile) {
let watcher = watchers.get(filename)
if (watcher) {
watcher.close()
}
let lastMTime = mtime(filename)
watchers.set(filename, fs.watch(filename, {}, (event, name) => {
logverbose('fsevent', event, name)
let filename2 = dirname(filename) + '/' + name
if (isfile(filename2)) {
// Sometimes we get multiple change events when the file has changed
// only once. We compare the mtime of the file to filter out
// redundant fs events.
const currMTime = mtime(filename2)
if (currMTime != lastMTime || filename != filename2) {
logverbose('mtime diff', filename, currMTime - lastMTime)
lastMTime = currMTime
if (event != 'change' || filename != filename2) {
stopWatching(filename)
setImmediate(() => startWatching(filename2, isPrimaryInfile))
} else if (isPrimaryInfile) {
restart(name, filename2)
} else {
restart(name, infiles[0])
}
}
} else {
lastMTime = 0
proc.terminate().catch(die)
if (opts.s || opts.stop) {
stopWatching(filename)
console.error(name, 'disappeared')
process.exit(1)
}
}
}))
}
// watch input files
infiles.forEach((infile, infileIndex) => {
logverbose('watch', infile)
startWatching(infile, infileIndex == 0)
})
}) // infiles.forEach
}
main()