-
Notifications
You must be signed in to change notification settings - Fork 1
/
readlineAsync.js
433 lines (373 loc) · 15 KB
/
readlineAsync.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
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
/**
* @license
* readline-async
* Copyright 2015-2016 Danny Nemer <http://dannynemer.com>
* Available under MIT license <http://opensource.org/licenses/MIT>
*/
var readline = require('readline')
var childProcess = require('child_process')
var util = require('dantil')
// Instantiate a readline `Interface`.
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
// Use a better prompt character.
prompt: '❯ ',
completer: function (line) {
// Find all command names that can follow input.
var matches = rl.commandNames.filter(function (commandName) {
return commandName.indexOf(line) === 0
})
// Show nothing if no completions found.
return [ matches, line ]
},
})
// Used by 'line' event listener to execute commands when invoked via input.
rl.commands = {}
// Used by `rl.completer` for `<tab>` autocompletion of the names of `rl.commands`.
rl.commandNames = []
// Used to map command names to strings of the command name and associated argument names, if any, for display in the usage screen.
rl.commandDisplayNames = {}
// Used for display in the usage screen.
rl.commandDescriptions = {}
// The usage screen used by `rl._printUsage()`.
rl.usage = ''
// Used by 'SIGINT' event listener to prompt the user to confirm before closing the RLI instance.
rl.sawSIGINT = false
/**
* Spawns a new process within the readline `Interface` (RLI) to asynchronously run `command` with `args`.
*
* Runs the child process within the user's shell (i.e., `$SHELL`), enabling `args` to contain pipes (e.g., `test | pbcopy`), IO redirection (e.g., `test > file`), globs (e.g., `*.js`), et cetera.
*
* Executes `command` as an asynchronous child process, leaving the event loop unblocked, but with the appearance of running synchronously. I.e., the user can not enter input (e.g., commands) during the process, but can terminate the process with `^C` and return to the RLI. In contrast, Node's default RLI blocks the event loop, requiring processes to complete before accepting any input; i.e., the user must externally kill the entire RLI process.
*
* Temporarily disables the RLI's `stdio` (input and output) while the child is processing, except for `^C` (`SIGINT`) to terminate the child. Restores the RLI `stdio` when the child exits or terminates.
*
* @memberOf rl
* @param {string} command The command to run as a child process.
* @param {string[]} args The command line arguments for `command`.
* @param {string|*[]} [stdio=[ 'ignore', process.stdout, process.stderr ]] The optional child process's `stdio` configuration.
* @param {Function} [callback] The optional function to execute after the child process exits and before returning control to the RLI.
* @returns {ChildProcess} Returns the spawned `ChildProcess`.
* @example
*
* rl.addCommands({
* name: 'test',
* description: 'Run \'myTest.js\' as terminable asynchronous child process.',
* func: function () {
* rl.spawnAsyncProcess('node', [ './myTest.js' ])
* }
* })
* ```
* ```
* ❯ .test
* ...executing stuff in 'myTest.js'...
* ...
* → user sends `^C` from command line
* Error: Child process terminated due to receipt of signal SIGINT
* ❯ .test | grep "Danny" | pbcopy
* ...executing 'myTest.js' and piping output...
*/
rl.spawnAsyncProcess = function (command, args, stdio, callback) {
// Check arity.
if (typeof stdio === 'function') {
callback = stdio
stdio = null
}
// Prevent printing prompt when executing child process, but continue processing input such as `^C` for `SIGINT` (which `rl.pause()` would prevent).
this.paused = true
/**
* Launches a new process with `command` and the command line arguments in `args`.
*
* This child process avoids blocking the event loop. Unless `stdio` is provided as an argument, the child process ignores input and inherits `stdout` and `stderr`.
*/
var child = childProcess.spawn(command, args, {
stdio: stdio || [ 'ignore', process.stdout, process.stderr ],
/**
* Run process inside in a shell to enable pipes (e.g., `test | pbcopy`), IO redirection (e.g., `test > file`), et cetera, inside `args`.
*
* Define `shell` as `process.env.SHELL` (which uses `$SHELL`) instead of `true` (which uses `sh` on UNIX) to enable IO redirection (i.e., `<` and `>`) and globs (e.g., `ls *.js`), which are unavailable in `sh`, and logging shell history.
*/
shell: process.env.SHELL,
})
// Disable output from RLI while child is processing.
var origStdoutWrite = this.output.write
this.output.write = function () {}
// Temporarily remove RLI `line` event listener(s) (when the user hits `enter`).
var lineListeners = this.listeners('line')
this.removeAllListeners('line')
// Send `SIGINT` to child process when received by the RLI.
function killChild() {
child.kill('SIGINT')
}
// Temporarily replace existing RLI `SIGINT` event listener(s).
var SIGINTListeners = this.listeners('SIGINT')
this.removeAllListeners('SIGINT')
this.on('SIGINT', killChild)
child.on('error', function (err) {
util.logError('\nFailed to start child process:', err.code)
})
var self = this
// The 'exit' event is emitted when the child process ends.
child.on('exit', function (code, signal) {
// Restore `stdout`.
self.output.write = origStdoutWrite
// Restore `SIGINT` event listeners(s).
self.removeListener('SIGINT', killChild)
SIGINTListeners.forEach(function (listener) {
self.on('SIGINT', listener)
})
if (signal) {
// `child` was killed (most often is due to `SIGINT` sent by the RLI).
util.logError('\nChild process terminated due to receipt of signal', util.colors.yellow(signal))
} else if (code !== 0) {
// `child` exited with a 'failure' code (most often after an exception is thrown).
util.logError('\nChild process exited with code', code)
} else if (callback) {
// `child` exited normally. Execute `callback` before returning control to the RLI.
callback()
}
// Restore `line` event listener(s).
lineListeners.forEach(function (listener) {
self.on('line', listener)
})
// Resume RLI.
self.prompt()
})
return child
}
/**
* Registers `commands` for the RLI to parse and execute. Automatically implements `<tab>` autocompletion for the command names.
*
* Commands are executed in the RLI with a leading period followed by the command name: `.command`. Commands are passed all arguments that follow the command name.
*
* @memberOf rl
* @param {...Object} [commands] The commands the RLI will parse and execute.
* @param {string} command.name The name that invokes `command.func` when input to RLI in the form `.name`.
* @param {string[]} [command.argNames] The optional argument names displayed in the RLI usage screen.
* @param {string} command.description The description displayed in the RLI usage screen.
* @param {Function} command.func The function the RLI executes.
* @example
*
* rl.addCommands({
* name: 'echo',
* argNames: [ '<string>' ],
* description: 'Write <string> to the standard output.',
* func: function (string) {
* console.log(string || '')
* }
* }, {
* name: 'exit',
* description: 'Terminate RLI.',
* func: function () {
* rl.close()
* }
* })
* ```
* RLI ran from command line (with autocompletion and auto-implemented commands):
* ```
* ❯ <tab>
* .test .echo .exit .repl .history .help
* ❯ . → .ec<tab> → .echo → .echo hello
* hello
* ❯ .foo
* Commands
* .echo <string> Write <string> to the standard output.
* .exit Terminate RLI.
* .repl Enter the Node.js REPL.
* .history Print the RLI history.
* .help Print this screen.
*
* Unrecognized command: .foo
*/
rl.addCommands = (function () {
var commandSchema = {
// The name that, when prepended with a period in the form `.name`, executes `command.func`.
name: { type: String, required: true },
// The optional argument names displayed in the RLI usage screen.
argNames: { type: Array, arrayType: String },
// The description displayed in the RLI usage screen.
description: { type: String, required: true },
// The function the RLI executes.
func: { type: Function, required: true },
}
return function () {
for (var a = 0, argumentsLen = arguments.length; a < argumentsLen; ++a) {
var command = arguments[a]
if (util.illFormedOpts(commandSchema, command)) {
throw new Error('Ill-formed command')
}
var commandName = '.' + command.name
if (this.commands.hasOwnProperty(commandName)) {
throw new Error('Duplicate command name: \'' + commandName + '\'')
}
// Save command name for `rl.completer` `<tab>` autocompletion.
// Add command after built-in commands to ensure the built-in commands are last in the usage screen and `rl.completer` suggestions.
this.commandNames.splice(-this.builtInCommandCount, 0, commandName)
// Generate a string of the command name and associated argument names, if any, for display in the usage screen.
var commandDisplayName = command.argNames ? [ commandName ].concat(command.argNames).join(' ') : commandName
this.commandDisplayNames[commandName] = commandDisplayName
// Determine greatest command name length for text alignment in the usage screen.
if (commandDisplayName.length > this.greatestCommandDisplayNameLength) {
this.greatestCommandDisplayNameLength = commandDisplayName.length
}
// Save command description for display in the usage screen.
this.commandDescriptions[commandName] = command.description
// Save command function.
this.commands[commandName] = command.func
}
// Update usage screen with new command(s) (and proper alignment).
this._generateUsage()
}
}())
/**
* Generates and saves the usage screen, used by `rl_printUsage(), containing the RLI instance's commands and their descriptions.
*
* @private
* @memberOf rl
*/
rl._generateUsage = function () {
// Determine greatest command name length for text alignment in the usage screen.
var greatestCommandDisplayNameLength = 0
for (var commandName in this.commandDisplayNames) {
var commandDisplayName = this.commandDisplayNames[commandName]
if (commandDisplayName.length > greatestCommandDisplayNameLength) {
greatestCommandDisplayNameLength = commandDisplayName.length
}
}
var usage = [ util.colors.bold('Commands') ]
// Use `commandNames` to ensure built-in commands are last.
for (var c = 0, commandsLen = this.commandNames.length; c < commandsLen; ++c) {
var commandName = this.commandNames[c]
var commandDisplayName = this.commandDisplayNames[commandName]
// Align command descriptions.
var padding = Array(greatestCommandDisplayNameLength - commandDisplayName.length + 1).join(' ') + ' '
usage.push(' ' + commandDisplayName + padding + this.commandDescriptions[commandName])
}
// Print trailing newline.
usage.push('')
// Save the usage screen.
this.usage = usage.join('\n')
}
/**
* Prints the usage screen containing the RLI instance's commands and their descriptions.
*
* @private
* @memberOf rl
*/
rl._printUsage = function () {
util.log(this.usage)
}
// Add built-in commands.
rl.addCommands({
name: 'help',
description: 'Print this screen.',
func: rl._printUsage.bind(rl),
}, {
name: 'history',
description: 'Print the RLI history.',
func: function () {
var historyLen = rl.history.length
for (var h = historyLen - 1; h > 0; --h) {
var idx = historyLen - h
util.log((historyLen > 10 && idx < 10 ? ' ' : '') + idx + ' ' + rl.history[h])
}
},
}, {
name: 'repl',
description: 'Enter the Node.js REPL.',
func: function () {
childProcess.execSync('node', { stdio: 'inherit' })
},
})
// The number of built-in commands. Used to ensure the built-in commands are the last commands in the usage screen and `rl.completer` suggestions.
rl.builtInCommandCount = rl.commandNames.length
/**
* Assigns an event handler to invoke when the user hits `return` or `enter` and the input is not a registered command (set by `rl.addCommands()`).
*
* @memberOf rl
* @param {Function} func The event handler invoked per RLI input that is not a registered command. Passed the input line as the only argument.
* @example
*
* // Listen for when the user hits `return` and the input is not a registered command.
* rl.onLine(function (line) {
* console.log('Thank you for your input:', line)
* })
*/
rl.onLine = function (func) {
this.lineEvent = func
}
/**
* Listens for `\n` in the input stream, usually received when the user hits `return`; parses and executes commands registered with `rl.addCommands()`; invokes the line listener set by `rl.onLine()` when the input is not a command; resets `rl.sawSIGINT`; and displays the prompt if there is no running child process.
*/
rl.on('line', function (line) {
// Reset `SIGINT` confirmation.
this.sawSIGINT = false
line = line.trim()
if (line) {
if (line[0] === '.') {
var args = line.split(' ')
var commandName = args[0]
// Execute command if found, else display usage screen.
var commandFunc = this.commands[commandName]
if (commandFunc) {
// Invoke function with all arguments that follow the command name.
commandFunc.apply(null, args.splice(1))
} else {
// Print usage screen and error for unrecognized command.
this._printUsage()
util.log(util.colors.red('Unrecognized command') + ':', commandName)
}
} else if (this.lineEvent) {
// Send input to line listener, if defined.
this.lineEvent(line)
}
}
// Do not display prompt when a child is process.
if (!this.paused) {
this.prompt()
}
})
/**
* Adds a new input line to the RLI's history list. Overrides the default `Interface.prototype._addHistory` to automatically remove older history lines that duplicate new ones.
*
* @private
* @memberOf rl
* @returns {string} Returns the newly added input line.
*/
rl._addHistory = function () {
if (this.line.length === 0) return ''
if (this.history.length === 0 || this.history[0] !== this.line) {
// Remove previous history index if duplicate.
var existingIndex = this.history.indexOf(this.line)
if (existingIndex !== -1) this.history.splice(existingIndex, 1)
this.history.unshift(this.line)
// Only store so many.
if (this.history.length > this.historySize) this.history.pop()
}
this.historyIndex = -1
return this.history[0]
}
/**
* Listens for `^C` (`SIGINT`) in the input stream and prompts the user to confirm before closing the RLI instance.
*/
rl.on('SIGINT', function () {
if (this.line.length > 0) {
// Clear line and reset `sawSIGINT`.
this.clearLine()
this.sawSIGINT = false
} else if (this.sawSIGINT) {
// Exit RLI.
this.close()
return
} else {
// Confirm before exiting.
this.output.write('\n(Press ^C again to exit)\n')
this.sawSIGINT = true
}
this.prompt()
})
// Ready RLI for input and display the prompt character.
rl.prompt()
// Export readline `Interface` instance.
module.exports = rl